Compare commits

..

1 Commits

Author SHA1 Message Date
Carlos Satorres a412d3b7a8 fix: refs #7319 fix order
gitea/salix-front/pipeline/pr-dev There was a failure building this commit Details
2025-01-16 13:04:10 +01:00
425 changed files with 9006 additions and 13367 deletions

View File

@ -1,4 +1,4 @@
export default { module.exports = {
// https://eslint.org/docs/user-guide/configuring#configuration-cascading-and-hierarchy // https://eslint.org/docs/user-guide/configuring#configuration-cascading-and-hierarchy
// This option interrupts the configuration hierarchy at this file // This option interrupts the configuration hierarchy at this file
// Remove this if you have an higher level ESLint config file (it usually happens into a monorepos) // Remove this if you have an higher level ESLint config file (it usually happens into a monorepos)
@ -58,7 +58,7 @@ export default {
rules: { rules: {
'prefer-promise-reject-errors': 'off', 'prefer-promise-reject-errors': 'off',
'no-unused-vars': 'warn', 'no-unused-vars': 'warn',
'vue/no-multiple-template-root': 'off', "vue/no-multiple-template-root": "off" ,
// allow debugger during development only // allow debugger during development only
'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off', 'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off',
}, },

8
.gitignore vendored
View File

@ -29,9 +29,5 @@ yarn-error.log*
*.sln *.sln
# Cypress directories and files # Cypress directories and files
/test/cypress/videos /tests/cypress/videos
/test/cypress/screenshots /tests/cypress/screenshots
# VitePress directories and files
/docs/.vitepress/cache
/docs/.vuepress

View File

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

View File

@ -1,4 +1,4 @@
export default { module.exports = {
singleQuote: true, singleQuote: true,
printWidth: 90, printWidth: 90,
tabWidth: 4, tabWidth: 4,

View File

@ -1,157 +1,3 @@
# Version 25.04 - 2025-01-28
### Added 🆕
- chore: add task comment by:jorgep
- chore: refs #8198 rollback by:jorgep
- chore: refs #8322 unnecessary prop by:alexm
- feat: refs #7055 added new test case by:provira
- feat: refs #7055 created FilterItemForm test by:provira
- feat: refs #7077 created test for VnInputTime by:provira
- feat: refs #7078 created test for VnJsonValue by:provira
- feat: refs #7087 added more test cases by:provira
- feat: refs #7087 added new test by:provira
- feat: refs #7087 created CardSummary test by:provira
- feat: refs #7088 created test for FetchedTags by:provira
- feat: refs #7202 added new field by:Jon
- feat: refs #7882 Added coords to create a address by:guillermo
- feat: refs #7957 add tooltip and i18n support for search link in VnSearchbar component by:jorgep
- feat: refs #7957 enhance search functionality and improve data filtering logic by:jorgep
- feat: refs #7957 open in new tab by:jorgep
- feat: refs #7957 simplify fn to by:jorgep
- feat: refs #7957 update VnSearchbar component with improved search URL handling and styling enhancements by:jorgep
- feat: refs #8117 filters and values added as needed by:jtubau
- feat: refs #8197 useHasContent and use in VnSection and RightMenu by:alexm
- feat: refs #8219 added invoice out e2e tests by:Jon
- feat: refs #8219 global invoicing e2e by:Jon
- feat: refs #8220 added barcodes e2e test by:Jon
- feat: refs #8220 created items e2e by:Jon
- feat: refs #8220 modified create item form and added respective e2e by:Jon
- feat: refs #8225 added account and invoiceOut modules by:Jon
- feat: refs #8225 added entry module and fixed translations by:Jon
- feat: refs #8225 added invoiceIn and travel module by:Jon
- feat: refs #8225 added moreOptions and use it in customer and ticket summary by:Jon
- feat: refs #8225 added route and shelving module by:Jon
- feat: refs #8225 added worker and zone modules by:Jon
- feat: refs #8225 use it in claim, item and order modules by:Jon
- feat: refs #8258 added button to pass to uppercase by:provira
- feat: refs #8258 added uppercase option to VnInput by:provira
- feat: refs #8258 added uppercase validation on supplier create by:provira
- feat: refs #8298 add price optimum input and update translations for bonus and price optimum by:jgallego
- feat: refs #8316 add entryFilter prop to VnTable component in EntryList by:jtubau
- feat: refs #8322 added department changes by:provira
- feat: refs #8372 workerPBX by:robert
- feat: refs #8381 add initial and final temperature fields to entry forms and summaries by:jgallego
- feat: refs #8381 add initial and final temperature labels in English and Spanish locales by:jgallego
- feat: refs #8381 add toCelsius filter and update temperature fields in entry forms and summaries by:jgallego
- feat: skip tests by:jorgep
- style: refs #7957 update VnSearchbar padding for improved layout by:jorgep
### Changed 📦
- perf: refs #8219 #8219 minor change by:Javier Segarra
- perf: refs #8220 on-fetch and added missing translations by:Jon
- perf: refs #8220 on-fetch by:Jon
- perf: refs #8220 translations by:Jon
- perf: refs #8220 use searchbar selector in e2e tests by:Jon
- perf: remove warning default value by:Javier Segarra
- refactor: redirect using params by:Jon
- refactor: refs #7077 removed some comments by:provira
- refactor: refs #7087 removed unused imports by:provira
- refactor: refs #7100 added const mockData by:jtubau
- refactor: refs #7100 delete unnecesary set prop by:jtubau
- refactor: refs #7100 refactorized with methods by:jtubau
- refactor: refs #7957 remove blank by:jorgep
- refactor: refs #8198 simplify data fetching and filtering logic by:jorgep
- refactor: refs #8198 simplify state management and data fetching in ItemDiary component by:jorgep
- refactor: refs #8219 modified e2e tests and fixed some translations by:Jon
- refactor: refs #8219 modified list test, created cypress download folder and added to gitignore by:Jon
- refactor: refs #8219 requested changes by:Jon
- refactor: refs #8219 use checkNotification command by:Jon
- refactor: refs #8220 added data-cy for e2e tests by:Jon
- refactor: refs #8220 requested changes by:Jon
- refactor: refs #8220 skip failling test and modifed tag test by:Jon
- refactor: refs #8225 requested changes by:Jon
- refactor: refs #8247 use new acl for sysadmin by:Jon
- refactor: refs #8316 added claimFilter by:jtubau
- refactor: refs #8316 added entryFilter by:jtubau
- refactor: refs #8316 add new localization keys and update existing ones for entry components by:jtubau
- refactor: refs #8316 moved localizations to local locale by:jtubau
- refactor: refs #8316 move order localization by:jtubau
- refactor: refs #8316 remove unused OrderSearchbar component by:jtubau
- refactor: refs #8316 update EntryCard to use user-filter prop and remove exprBuilder from EntryList by:jtubau
- refactor: refs #8316 used VnSection and VnCardBeta by:jtubau
- refactor: refs #8322 changed translations by:provira
- refactor: refs #8322 changed Worker component to use VnSection/VnCardBeta by:provira
- refactor: refs #8322 set department inside worker by:alexm
- refactor: skip intermitent failing test by:Jon
### Fixed 🛠️
- feat: refs #8225 added entry module and fixed translations by:Jon
- fix: added missing translations in InvoiceIn by:provira
- fix: changed invoiceIn for InvoiceIn by:provira
- fix: changed translations to only use "invoicein" by:provira
- fix: department descriptor link by:Jon
- fix: e2e tests by:Jon
- fix: entry summary view and build warnings by:Jon
- fix: fixed InvoiceIn filter translations by:provira
- fix: modified setData in customerDescriptor to show the icons by:Jon
- fix: redirect to TicketSale from OrderLines (origin/Fix-RedirectToTicketSale) by:Jon
- fix: redirect when confirming lines by:Jon
- fix: refs #7055 #7055 #7055 fixed some tests by:provira
- fix: refs #7077 removed unused imports by:provira
- fix: refs #7078 added missing case with array by:provira
- fix: refs #7087 fixed some tests by:provira
- fix: refs #7088 changed "vm.vm" to "vm" by:provira
- fix: refs #7088 changed wrapper to vm by:provira
- fix: refs #7699 add icons and hint by:carlossa
- fix: refs #7699 add pwd vnInput by:carlossa
- fix: refs #7699 fix component by:carlossa
- fix: refs #7699 fix password visibility by:carlossa
- fix: refs #7699 fix tfront clean code by:carlossa
- fix: refs #7699 fix vnChangePassword, clean VnInput by:carlossa
- fix: refs #7699 fix vnInputPassword by:carlossa
- fix: refs #7957 add missing closing brace by:jorgep
- fix: refs #7957 css by:jorgep
- fix: refs #7957 rollback by:jorgep
- fix: refs #7957 update data-cy by:jorgep
- fix: refs #7957 update visibility handling for clear icon in VnInput component by:jorgep
- fix: refs #7957 vn-searchbar test by:jorgep
- fix: refs #8117 update salesPersonFk filter options and URL for improved data retrieval by:jtubau
- fix: refs #8197 not use yet by:alexm
- fix: refs #8198 update query param by:jorgep
- fix: refs #8219 fixed e2e tests by:Jon
- fix: refs #8219 fixed summary and global tests by:Jon
- fix: refs #8219 forgotten dataCy by:Jon
- fix: refs #8219 global e2e by:Jon
- fix: refs #8219 requested changes by:Jon
- fix: refs #8220 itemTag test by:Javier Segarra
- fix: refs #8225 invoice in translations by:Jon
- fix: refs #8243 fixed SkeletonSummary by:provira
- fix: refs #8247 conflicts by:Jon
- fix: refs #8247 fixed acls and added lost options by:Jon
- fix: refs #8316 ref="claimFilterRef" by:alexm
- fix: refs #8316 userFilter by:alexm
- fix: refs #8316 use rightMenu by:alexm
- fix: refs #8316 use section-searchbar by:alexm
- fix: refs #8317 disable action buttons when no rows are selected in ItemFixedPrice by:jtubau
- fix: refs #8322 unnecessary section by:alexm
- fix: refs #8338 fixed VnTable translations by:provira
- fix: refs #8338 removed chipLocale property/added more translations by:provira
- fix: refs #8448 e2e by:Jon
- fix: refs #8448 not use croppie by:alexm
- fix: remove departmentCode by:Javier Segarra
- fix: removed unused searchbar by:PAU ROVIRA ROSALENY
- fix: skip failling e2e by:Jon
- fix: sort by name in description by:Jon
- fix: translations by:Jon
- fix: use entryFilter by:alexm
- fix(VnCardBeta): add userFilter by:alexm
- refactor: refs #8219 modified e2e tests and fixed some translations by:Jon
- revert: revert header by:alexm
- test: fix expedition e2e by:alexm
# Version 25.00 - 2025-01-14 # Version 25.00 - 2025-01-14
### Added 🆕 ### Added 🆕

View File

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

View File

@ -1,9 +1,9 @@
import { defineConfig } from 'cypress'; const { defineConfig } = require('cypress');
// https://docs.cypress.io/app/tooling/reporters // https://docs.cypress.io/app/tooling/reporters
// https://docs.cypress.io/app/references/configuration // https://docs.cypress.io/app/references/configuration
// https://www.npmjs.com/package/cypress-mochawesome-reporter // https://www.npmjs.com/package/cypress-mochawesome-reporter
export default defineConfig({ module.exports = defineConfig({
e2e: { e2e: {
baseUrl: 'http://localhost:9000/', baseUrl: 'http://localhost:9000/',
experimentalStudio: true, experimentalStudio: true,
@ -30,13 +30,9 @@ export default defineConfig({
testFiles: '**/*.spec.js', testFiles: '**/*.spec.js',
supportFile: 'test/cypress/support/unit.js', supportFile: 'test/cypress/support/unit.js',
}, },
setupNodeEvents: async (on, config) => { setupNodeEvents(on, config) {
const plugin = await import('cypress-mochawesome-reporter/plugin'); require('cypress-mochawesome-reporter/plugin')(on);
plugin.default(on); // implement node event listeners here
return config;
}, },
viewportWidth: 1280,
viewportHeight: 720,
}, },
}); });

View File

@ -1,38 +0,0 @@
import { defineConfig } from 'vitepress';
// https://vitepress.dev/reference/site-config
export default defineConfig({
title: 'Lilium',
description: 'Lilium docs',
themeConfig: {
// https://vitepress.dev/reference/default-theme-config
nav: [
{ text: 'Home', link: '/' },
{ text: 'Components', link: '/components/vnInput' },
{ text: 'Composables', link: '/composables/useArrayData' },
],
sidebar: [
{
items: [
{
text: 'Components',
collapsible: true,
collapsed: true,
items: [{ text: 'VnInput', link: '/components/vnInput' }],
},
{
text: 'Composables',
collapsible: true,
collapsed: true,
items: [
{ text: 'useArrayData', link: '/composables/useArrayData' },
],
},
],
},
],
socialLinks: [{ icon: 'github', link: 'https://github.com/vuejs/vitepress' }],
},
});

View File

@ -1,136 +0,0 @@
# VnInput
`VnInput` is a custom input component that provides various useful features such as validation, input clearing, and more.
## Props
### `modelValue`
- **Type:** `String | Number`
- **Default:** `null`
- **Description:** The value of the model bound to the component.
### `isOutlined`
- **Type:** `Boolean`
- **Default:** `false`
- **Description:** If `true`, the component is rendered with an outlined style.
### `info`
- **Type:** `String`
- **Default:** `''`
- **Description:** Additional information displayed alongside the component.
### `clearable`
- **Type:** `Boolean`
- **Default:** `true`
- **Description:** If `true`, the component shows a button to clear the input.
### `emptyToNull`
- **Type:** `Boolean`
- **Default:** `true`
- **Description:** If `true`, converts empty inputs to `null`.
### `insertable`
- **Type:** `Boolean`
- **Default:** `false`
- **Description:** If `true`, allows the insertion of new values.
### `maxlength`
- **Type:** `Number`
- **Default:** `null`
- **Description:** The maximum number of characters allowed in the input.
### `uppercase`
- **Type:** `Boolean`
- **Default:** `false`
- **Description:** If `true`, converts the input text to uppercase.
## Emits
### `update:modelValue`
- **Description:** Emits the updated model value.
- **Behavior:** This event is emitted whenever the input value changes. It is used to update the model value bound to the component.
### `update:options`
- **Description:** Emits the updated options.
- **Behavior:** This event is emitted when the component's options change. It is useful for components with dynamic options.
### `keyup.enter`
- **Description:** Emits an event when the Enter key is pressed.
- **Behavior:** This event is emitted whenever the Enter key is pressed while the input is focused. It can be used to handle specific actions when the input is confirmed.
### `remove`
- **Description:** Emits an event to remove the current value.
- **Behavior:** This event is emitted when the clear button (close icon) is clicked. It is used to handle the removal of the current input value.
## Functions
### `focus`
- **Description:** Focuses the input.
- **Behavior:** This function is exposed so it can be called from outside the component. It uses `vnInputRef.value.focus()` to focus the input.
### `handleKeydown`
- **Description:** Handles the `keydown` event of the input.
- **Behavior:** This function is called whenever a key is pressed while the input is focused. If the pressed key is `Backspace`, it does nothing. If `insertable` is `true` and the pressed key is a number, it calls `handleInsertMode`.
### `handleInsertMode`
- **Description:** Handles the insertion mode of values.
- **Behavior:** This function is called when `insertable` is `true` and a numeric key is pressed. It inserts the value at the cursor position and updates the input value. Then, it moves the cursor to the correct position.
### `handleUppercase`
- **Description:** Converts the input value to uppercase.
- **Behavior:** This function is called when the uppercase icon is clicked. It converts the current input value to uppercase.
## Usage
```vue
<template>
<VnInput
v-model="inputValue"
:isOutlined="true"
info="Additional information"
:clearable="true"
:emptyToNull="true"
:insertable="false"
:maxlength="50"
:uppercase="true"
@update:modelValue="handleUpdate"
@keyup.enter="handleEnter"
@remove="handleRemove"
/>
</template>
<script setup>
import { ref } from 'vue';
import VnInput from 'src/components/common/VnInput.vue';
const inputValue = ref('');
const handleUpdate = (value) => {
console.log('Updated value:', value);
};
const handleEnter = () => {
console.log('Enter pressed');
};
const handleRemove = () => {
console.log('Value removed');
};
</script>
```

View File

@ -1,215 +0,0 @@
# useArrayData
`useArrayData` is a composable function that provides a set of utilities for managing array data in a Vue component. It leverages Pinia for state management and provides various methods for fetching, filtering, and manipulating data.
## Usage
```javascript
import { useArrayData } from 'src/composables/useArrayData';
const {
fetch,
applyFilter,
addFilter,
getCurrentFilter,
setCurrentFilter,
addFilterWhere,
addOrder,
deleteOrder,
refresh,
destroy,
loadMore,
store,
totalRows,
updateStateParams,
isLoading,
deleteOption,
reset,
resetPagination,
} = useArrayData('myKey', userOptions);
```
## Parameters
### `key`
- **Type:** `String`
- **Description:** A unique key to identify the data store.
### `userOptions`
- **Type:** `Object`
- **Description:** An object containing user-defined options for configuring the data store.
## Methods
### `fetch`
Fetches data from the server.
#### Parameters
- **`options`** : An object with the following properties:
- `append` (Boolean): Whether to append the fetched data to the existing data.
- `updateRouter` (Boolean): Whether to update the router with the current filter.
#### Returns
- **`Promise`** : A promise that resolves with the fetched data.
### `applyFilter`
Applies a filter to the data.
#### Parameters
- **`filter`** : An object containing the filter criteria.
- **`params`** : Additional parameters for the filter.
- **`fetchOptions`** : Options for the fetch method.
#### Returns
- **`Promise`** : A promise that resolves with the filtered data.
### `addFilter`
Adds a filter to the existing filters.
#### Parameters
- **`filter`** : An object containing the filter criteria.
- **`params`** : Additional parameters for the filter.
#### Returns
- **`Promise`** : A promise that resolves with the updated filter and parameters.
### `getCurrentFilter`
Gets the current filter applied to the data.
#### Returns
- **`Object`** : The current filter and parameters.
### `setCurrentFilter`
Sets the current filter for the data.
#### Returns
- **`Object`** : The current filter and parameters.
### `addFilterWhere`
Adds a `where` clause to the existing filters.
#### Parameters
- **`where`** : An object containing the `where` clause.
#### Returns
- **`Promise`** : A promise that resolves when the filter is applied.
### `addOrder`
Adds an order to the existing orders.
#### Parameters
- **`field`** : The field to order by.
- **`direction`** : The direction of the order (`ASC` or `DESC`).
#### Returns
- **`Promise`** : A promise that resolves with the updated order.
### `deleteOrder`
Deletes an order from the existing orders.
#### Parameters
- **`field`** : The field to delete the order for.
#### Returns
- **`Promise`** : A promise that resolves when the order is deleted.
### `refresh`
Refreshes the data by re-fetching it from the server.
#### Returns
- **`Promise`** : A promise that resolves with the refreshed data.
### `destroy`
Destroys the data store for the given key.
### `loadMore`
Loads more data by incrementing the pagination.
#### Returns
- **`Promise`** : A promise that resolves with the additional data.
### `updateStateParams`
Updates the state parameters with the given data.
#### Parameters
- **`data`** : The data to update the state parameters with.
### `deleteOption`
Deletes an option from the store.
#### Parameters
- **`option`** : The option to delete.
### `reset`
Resets the store to its default state.
#### Parameters
- **`opts`** : An array of options to reset.
### `resetPagination`
Resets the pagination for the store.
## Computed Properties
### `totalRows`
- **Description:** The total number of rows in the data.
- **Type:** `Number`
### `isLoading`
- **Description:** Whether the data is currently being loaded.
- **Type:** `Boolean`
```vue
<script setup>
import { useArrayData } from 'src/composables/useArrayData';
const userOptions = {
url: '/api/data',
limit: 10,
};
const arrayData = useArrayData('myKey', userOptions);
</script>
```
```
```

View File

@ -1,13 +0,0 @@
---
# https://vitepress.dev/reference/default-theme-home-page
layout: home
hero:
name: 'Lilium'
text: 'Lilium docs'
tagline: Powered by Verdnatura
actions:
- theme: brand
text: Docs
link: /components/vnInput
---

View File

@ -1,12 +1,11 @@
{ {
"name": "salix-front", "name": "salix-front",
"version": "25.08.0", "version": "25.04.0",
"description": "Salix frontend", "description": "Salix frontend",
"productName": "Salix", "productName": "Salix",
"author": "Verdnatura", "author": "Verdnatura",
"private": true, "private": true,
"packageManager": "pnpm@8.15.1", "packageManager": "pnpm@8.15.1",
"type": "module",
"scripts": { "scripts": {
"resetDatabase": "cd ../salix && gulp docker", "resetDatabase": "cd ../salix && gulp docker",
"lint": "eslint --ext .js,.vue ./", "lint": "eslint --ext .js,.vue ./",
@ -18,47 +17,42 @@
"test:unit:ci": "vitest run", "test:unit:ci": "vitest run",
"commitlint": "commitlint --edit", "commitlint": "commitlint --edit",
"prepare": "npx husky install", "prepare": "npx husky install",
"addReferenceTag": "node .husky/addReferenceTag.js", "addReferenceTag": "node .husky/addReferenceTag.js"
"docs:dev": "vitepress dev docs",
"docs:build": "vitepress build docs",
"docs:preview": "vitepress preview docs"
}, },
"dependencies": { "dependencies": {
"@quasar/cli": "^2.4.1", "@quasar/cli": "^2.3.0",
"@quasar/extras": "^1.16.16", "@quasar/extras": "^1.16.9",
"axios": "^1.4.0", "axios": "^1.4.0",
"chromium": "^3.0.3", "chromium": "^3.0.3",
"croppie": "^2.6.5", "croppie": "^2.6.5",
"moment": "^2.30.1", "moment": "^2.30.1",
"pinia": "^2.1.3", "pinia": "^2.1.3",
"quasar": "^2.17.7", "quasar": "^2.14.5",
"validator": "^13.9.0", "validator": "^13.9.0",
"vue": "^3.5.13", "vue": "^3.3.4",
"vue-i18n": "^9.3.0", "vue-i18n": "^9.2.2",
"vue-router": "^4.2.5" "vue-router": "^4.2.1"
}, },
"devDependencies": { "devDependencies": {
"@commitlint/cli": "^19.2.1", "@commitlint/cli": "^19.2.1",
"@commitlint/config-conventional": "^19.1.0", "@commitlint/config-conventional": "^19.1.0",
"@intlify/unplugin-vue-i18n": "^0.8.2", "@intlify/unplugin-vue-i18n": "^0.8.1",
"@pinia/testing": "^0.1.2", "@pinia/testing": "^0.1.2",
"@quasar/app-vite": "^2.0.8", "@quasar/app-vite": "^1.7.3",
"@quasar/quasar-app-extension-qcalendar": "^4.0.2", "@quasar/quasar-app-extension-qcalendar": "4.0.0-beta.15",
"@quasar/quasar-app-extension-testing-unit-vitest": "^0.4.0", "@quasar/quasar-app-extension-testing-unit-vitest": "^0.4.0",
"@vue/test-utils": "^2.4.4", "@vue/test-utils": "^2.4.4",
"autoprefixer": "^10.4.14", "autoprefixer": "^10.4.14",
"cypress": "^13.6.6", "cypress": "^13.6.6",
"cypress-mochawesome-reporter": "^3.8.2", "cypress-mochawesome-reporter": "^3.8.2",
"eslint": "^9.18.0", "eslint": "^8.41.0",
"eslint-config-prettier": "^10.0.1", "eslint-config-prettier": "^8.8.0",
"eslint-plugin-cypress": "^4.1.0", "eslint-plugin-cypress": "^2.13.3",
"eslint-plugin-vue": "^9.32.0", "eslint-plugin-vue": "^9.14.1",
"husky": "^8.0.0", "husky": "^8.0.0",
"postcss": "^8.4.23", "postcss": "^8.4.23",
"prettier": "^3.4.2", "prettier": "^2.8.8",
"sass": "^1.83.4", "vitest": "^0.31.1"
"vitepress": "^1.6.3",
"vitest": "^0.34.0"
}, },
"engines": { "engines": {
"node": "^20 || ^18 || ^16", "node": "^20 || ^18 || ^16",
@ -67,8 +61,8 @@
"bun": ">= 1.0.25" "bun": ">= 1.0.25"
}, },
"overrides": { "overrides": {
"@vitejs/plugin-vue": "^5.2.1", "@vitejs/plugin-vue": "^5.0.4",
"vite": "^6.0.11", "vite": "^5.1.4",
"vitest": "^0.31.1" "vitest": "^0.31.1"
} }
} }

File diff suppressed because it is too large Load Diff

View File

@ -1,14 +1,10 @@
/* eslint-disable */ /* eslint-disable */
// https://github.com/michael-ciniawsky/postcss-load-config // https://github.com/michael-ciniawsky/postcss-load-config
import autoprefixer from 'autoprefixer'; module.exports = {
// Uncomment the following line if you want to support RTL CSS
// import rtlcss from 'postcss-rtlcss';
export default {
plugins: [ plugins: [
// https://github.com/postcss/autoprefixer // https://github.com/postcss/autoprefixer
autoprefixer({ require('autoprefixer')({
overrideBrowserslist: [ overrideBrowserslist: [
'last 4 Chrome versions', 'last 4 Chrome versions',
'last 4 Firefox versions', 'last 4 Firefox versions',
@ -22,7 +18,10 @@ export default {
}), }),
// https://github.com/elchininet/postcss-rtlcss // https://github.com/elchininet/postcss-rtlcss
// If you want to support RTL CSS, uncomment the following line: // If you want to support RTL css, then
// rtlcss(), // 1. yarn/npm install postcss-rtlcss
// 2. optionally set quasar.config.js > framework > lang to an RTL language
// 3. uncomment the following line:
// require('postcss-rtlcss')
], ],
}; };

View File

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

View File

@ -8,11 +8,11 @@
// Configuration for your app // Configuration for your app
// https://v2.quasar.dev/quasar-cli-vite/quasar-config-js // https://v2.quasar.dev/quasar-cli-vite/quasar-config-js
import { configure } from 'quasar/wrappers'; const { configure } = require('quasar/wrappers');
import VueI18nPlugin from '@intlify/unplugin-vue-i18n/vite'; const VueI18nPlugin = require('@intlify/unplugin-vue-i18n/vite');
import path from 'path'; const path = require('path');
export default configure(function (/* ctx */) { module.exports = configure(function (/* ctx */) {
return { return {
eslint: { eslint: {
// fix: true, // fix: true,
@ -179,6 +179,7 @@ export default configure(function (/* ctx */) {
'render', // keep this as last one 'render', // keep this as last one
], ],
}, },
// https://v2.quasar.dev/quasar-cli/developing-pwa/configuring-pwa // https://v2.quasar.dev/quasar-cli/developing-pwa/configuring-pwa
pwa: { pwa: {
workboxMode: 'generateSW', // or 'injectManifest' workboxMode: 'generateSW', // or 'injectManifest'

View File

@ -1,8 +1,6 @@
{ {
"@quasar/testing-unit-vitest": { "@quasar/testing-unit-vitest": {
"options": [ "options": ["scripts"]
"scripts"
]
}, },
"@quasar/qcalendar": {} "@quasar/qcalendar": {}
} }

View File

@ -20,7 +20,7 @@ describe('Axios boot', () => {
describe('onRequest()', async () => { describe('onRequest()', async () => {
it('should set the "Authorization" property on the headers', async () => { it('should set the "Authorization" property on the headers', async () => {
const config = { headers: {} }; const config = { headers: {} };
localStorage.setItem('token', 'DEFAULT_TOKEN');
const resultConfig = onRequest(config); const resultConfig = onRequest(config);
expect(resultConfig).toEqual( expect(resultConfig).toEqual(

View File

@ -3,9 +3,9 @@ import { useSession } from 'src/composables/useSession';
import { Router } from 'src/router'; import { Router } from 'src/router';
import useNotify from 'src/composables/useNotify.js'; import useNotify from 'src/composables/useNotify.js';
import { useStateQueryStore } from 'src/stores/useStateQueryStore'; import { useStateQueryStore } from 'src/stores/useStateQueryStore';
import { getToken, isLoggedIn } from 'src/utils/session';
import { i18n } from 'src/boot/i18n'; import { i18n } from 'src/boot/i18n';
const session = useSession();
const { notify } = useNotify(); const { notify } = useNotify();
const stateQuery = useStateQueryStore(); const stateQuery = useStateQueryStore();
const baseUrl = '/api/'; const baseUrl = '/api/';
@ -13,7 +13,7 @@ axios.defaults.baseURL = baseUrl;
const axiosNoError = axios.create({ baseURL: baseUrl }); const axiosNoError = axios.create({ baseURL: baseUrl });
const onRequest = (config) => { const onRequest = (config) => {
const token = getToken(); const token = session.getToken();
if (token.length && !config.headers.Authorization) { if (token.length && !config.headers.Authorization) {
config.headers.Authorization = token; config.headers.Authorization = token;
config.headers['Accept-Language'] = i18n.global.locale.value; config.headers['Accept-Language'] = i18n.global.locale.value;
@ -37,15 +37,15 @@ const onResponse = (response) => {
return response; return response;
}; };
const onResponseError = async (error) => { const onResponseError = (error) => {
stateQuery.remove(error.config); stateQuery.remove(error.config);
if (isLoggedIn() && error.response?.status === 401) { if (session.isLoggedIn() && error.response?.status === 401) {
await useSession().destroy(false); session.destroy(false);
const hash = window.location.hash; const hash = window.location.hash;
const url = hash.slice(1); const url = hash.slice(1);
Router.push(`/login?redirect=${url}`); Router.push(`/login?redirect=${url}`);
} else if (!isLoggedIn()) { } else if (!session.isLoggedIn()) {
return Promise.reject(error); return Promise.reject(error);
} }

View File

@ -1,2 +0,0 @@
export const langs = ['en', 'es'];
export const decimalPlaces = 2;

View File

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

View File

@ -14,7 +14,7 @@ const { t } = useI18n();
const bicInputRef = ref(null); const bicInputRef = ref(null);
const state = useState(); const state = useState();
const customer = computed(() => state.get('Customer')); const customer = computed(() => state.get('customer'));
const countriesFilter = { const countriesFilter = {
fields: ['id', 'name', 'code'], fields: ['id', 'name', 'code'],

View File

@ -1,6 +1,6 @@
<script setup> <script setup>
import axios from 'axios'; import axios from 'axios';
import { computed, ref, useAttrs, watch } from 'vue'; import { computed, ref, watch } from 'vue';
import { useRouter, onBeforeRouteLeave } from 'vue-router'; import { useRouter, onBeforeRouteLeave } from 'vue-router';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import { useQuasar } from 'quasar'; import { useQuasar } from 'quasar';
@ -17,7 +17,6 @@ const quasar = useQuasar();
const stateStore = useStateStore(); const stateStore = useStateStore();
const { t } = useI18n(); const { t } = useI18n();
const { validate } = useValidator(); const { validate } = useValidator();
const $attrs = useAttrs();
const $props = defineProps({ const $props = defineProps({
model: { model: {
@ -114,11 +113,9 @@ onBeforeRouteLeave((to, from, next) => {
}); });
async function fetch(data) { async function fetch(data) {
const keyData = $attrs['key-data']; resetData(data);
const rows = keyData ? data[keyData] : data; emit('onFetch', data);
resetData(rows); return data;
emit('onFetch', rows);
return rows;
} }
function resetData(data) { function resetData(data) {
@ -149,7 +146,7 @@ function filter(value, update, filterOptions) {
(ref) => { (ref) => {
ref.setOptionIndex(-1); ref.setOptionIndex(-1);
ref.moveOptionSelection(1, true); ref.moveOptionSelection(1, true);
}, }
); );
} }
@ -215,7 +212,7 @@ async function remove(data) {
if (preRemove.length) { if (preRemove.length) {
newData = newData.filter( newData = newData.filter(
(form) => !preRemove.some((index) => index == form.$index), (form) => !preRemove.some((index) => index == form.$index)
); );
const changes = getChanges(); const changes = getChanges();
if (!changes.creates?.length && !changes.updates?.length) if (!changes.creates?.length && !changes.updates?.length)

View File

@ -84,7 +84,7 @@ const $props = defineProps({
}, },
reload: { reload: {
type: Boolean, type: Boolean,
default: true, default: false,
}, },
defaultTrim: { defaultTrim: {
type: Boolean, type: Boolean,
@ -97,7 +97,7 @@ const $props = defineProps({
}); });
const emit = defineEmits(['onFetch', 'onDataSaved']); const emit = defineEmits(['onFetch', 'onDataSaved']);
const modelValue = computed( const modelValue = computed(
() => $props.model ?? `formModel_${route?.meta?.title ?? route.name}`, () => $props.model ?? `formModel_${route?.meta?.title ?? route.name}`
).value; ).value;
const componentIsRendered = ref(false); const componentIsRendered = ref(false);
const arrayData = useArrayData(modelValue); const arrayData = useArrayData(modelValue);
@ -105,8 +105,8 @@ const isLoading = ref(false);
// Si elegimos observar los cambios del form significa que inicialmente las actions estaran deshabilitadas // Si elegimos observar los cambios del form significa que inicialmente las actions estaran deshabilitadas
const isResetting = ref(false); const isResetting = ref(false);
const hasChanges = ref(!$props.observeFormChanges); const hasChanges = ref(!$props.observeFormChanges);
const originalData = computed(() => state.get(modelValue)); const originalData = ref({});
const formData = ref({}); const formData = computed(() => state.get(modelValue));
const defaultButtons = computed(() => ({ const defaultButtons = computed(() => ({
save: { save: {
dataCy: 'saveDefaultBtn', dataCy: 'saveDefaultBtn',
@ -127,6 +127,8 @@ const defaultButtons = computed(() => ({
})); }));
onMounted(async () => { onMounted(async () => {
originalData.value = JSON.parse(JSON.stringify($props.formInitialData ?? {}));
nextTick(() => (componentIsRendered.value = true)); nextTick(() => (componentIsRendered.value = true));
// Podemos enviarle al form la estructura de data inicial sin necesidad de fetchearla // Podemos enviarle al form la estructura de data inicial sin necesidad de fetchearla
@ -146,7 +148,7 @@ onMounted(async () => {
JSON.stringify(newVal) !== JSON.stringify(originalData.value); JSON.stringify(newVal) !== JSON.stringify(originalData.value);
isResetting.value = false; isResetting.value = false;
}, },
{ deep: true }, { deep: true }
); );
} }
}); });
@ -154,24 +156,16 @@ onMounted(async () => {
if (!$props.url) if (!$props.url)
watch( watch(
() => arrayData.store.data, () => arrayData.store.data,
(val) => updateAndEmit('onFetch', val), (val) => updateAndEmit('onFetch', val)
);
watch(
originalData,
(val) => {
if (val) formData.value = JSON.parse(JSON.stringify(val));
},
{ immediate: true },
); );
watch( watch(
() => [$props.url, $props.filter], () => [$props.url, $props.filter],
async () => { async () => {
state.set(modelValue, null); originalData.value = null;
reset(); reset();
await fetch(); await fetch();
}, }
); );
onBeforeRouteLeave((to, from, next) => { onBeforeRouteLeave((to, from, next) => {
@ -203,6 +197,7 @@ async function fetch() {
updateAndEmit('onFetch', data); updateAndEmit('onFetch', data);
} catch (e) { } catch (e) {
state.set(modelValue, {}); state.set(modelValue, {});
originalData.value = {};
throw e; throw e;
} }
} }
@ -241,7 +236,6 @@ async function saveAndGo() {
} }
function reset() { function reset() {
formData.value = JSON.parse(JSON.stringify(originalData.value));
updateAndEmit('onFetch', originalData.value); updateAndEmit('onFetch', originalData.value);
if ($props.observeFormChanges) { if ($props.observeFormChanges) {
hasChanges.value = false; hasChanges.value = false;
@ -260,12 +254,13 @@ function filter(value, update, filterOptions) {
(ref) => { (ref) => {
ref.setOptionIndex(-1); ref.setOptionIndex(-1);
ref.moveOptionSelection(1, true); ref.moveOptionSelection(1, true);
}, }
); );
} }
function updateAndEmit(evt, val, res) { function updateAndEmit(evt, val, res) {
state.set(modelValue, val); state.set(modelValue, val);
originalData.value = val && JSON.parse(JSON.stringify(val));
if (!$props.url) arrayData.store.data = val; if (!$props.url) arrayData.store.data = val;
emit(evt, state.get(modelValue), res); emit(evt, state.get(modelValue), res);

View File

@ -31,6 +31,7 @@ const props = defineProps({
const route = useRoute(); const route = useRoute();
const itemTypesOptions = ref([]); const itemTypesOptions = ref([]);
const suppliersOptions = ref([]);
const tagOptions = ref([]); const tagOptions = ref([]);
const tagValues = ref([]); const tagValues = ref([]);
const categoryList = ref(null); const categoryList = ref(null);
@ -39,13 +40,13 @@ const selectedTypeFk = ref(getParamWhere(route.query.table, 'typeFk', false));
const selectedCategory = computed(() => { const selectedCategory = computed(() => {
return (categoryList.value || []).find( return (categoryList.value || []).find(
(category) => category?.id === selectedCategoryFk.value, (category) => category?.id === selectedCategoryFk.value
); );
}); });
const selectedType = computed(() => { const selectedType = computed(() => {
return (itemTypesOptions.value || []).find( return (itemTypesOptions.value || []).find(
(type) => type?.id === selectedTypeFk.value, (type) => type?.id === selectedTypeFk.value
); );
}); });
@ -133,6 +134,13 @@ const setCategoryList = (data) => {
<template> <template>
<FetchData url="ItemCategories" limit="30" auto-load @on-fetch="setCategoryList" /> <FetchData url="ItemCategories" limit="30" auto-load @on-fetch="setCategoryList" />
<FetchData
url="Suppliers"
limit="30"
auto-load
:filter="{ fields: ['id', 'name', 'nickname'], order: 'name ASC', limit: 30 }"
@on-fetch="(data) => (suppliersOptions = data)"
/>
<FetchData <FetchData
url="Tags" url="Tags"
:filter="{ fields: ['id', 'name', 'isFree'] }" :filter="{ fields: ['id', 'name', 'isFree'] }"
@ -282,7 +290,7 @@ const setCategoryList = (data) => {
<QItem class="q-mt-lg"> <QItem class="q-mt-lg">
<QBtn <QBtn
icon="add_circle" icon="add_circle"
v-shortcut="'+'" shortcut="+"
flat flat
class="fill-icon-on-hover q-px-xs" class="fill-icon-on-hover q-px-xs"
color="primary" color="primary"
@ -341,11 +349,4 @@ es:
floramondo: Floramondo floramondo: Floramondo
salesPersonFk: Comprador salesPersonFk: Comprador
categoryFk: Categoría categoryFk: Categoría
Plant: Planta natural
Flower: Flor fresca
Handmade: Hecho a mano
Artificial: Artificial
Green: Verdes frescos
Accessories: Complementos florales
Fruit: Fruta
</i18n> </i18n>

View File

@ -10,13 +10,12 @@ import routes from 'src/router/modules';
import LeftMenuItem from './LeftMenuItem.vue'; import LeftMenuItem from './LeftMenuItem.vue';
import LeftMenuItemGroup from './LeftMenuItemGroup.vue'; import LeftMenuItemGroup from './LeftMenuItemGroup.vue';
import VnInput from './common/VnInput.vue'; import VnInput from './common/VnInput.vue';
import { useRouter } from 'vue-router';
const { t } = useI18n(); const { t } = useI18n();
const route = useRoute(); const route = useRoute();
const quasar = useQuasar(); const quasar = useQuasar();
const navigation = useNavigationStore(); const navigation = useNavigationStore();
const router = useRouter();
const props = defineProps({ const props = defineProps({
source: { source: {
type: String, type: String,
@ -41,6 +40,7 @@ const filteredItems = computed(() => {
return locale.includes(normalizedSearch); return locale.includes(normalizedSearch);
}); });
}); });
const filteredPinnedModules = computed(() => { const filteredPinnedModules = computed(() => {
if (!search.value) return pinnedModules.value; if (!search.value) return pinnedModules.value;
const normalizedSearch = search.value const normalizedSearch = search.value
@ -71,7 +71,7 @@ watch(
items.value = []; items.value = [];
getRoutes(); getRoutes();
}, },
{ deep: true }, { deep: true }
); );
function findMatches(search, item) { function findMatches(search, item) {
@ -103,22 +103,12 @@ function addChildren(module, route, parent) {
} }
function getRoutes() { function getRoutes() {
const handleRoutes = { if (props.source === 'main') {
main: getMainRoutes,
card: getCardRoutes,
};
try {
handleRoutes[props.source]();
} catch (error) {
throw new Error(`Method is not defined`);
}
}
function getMainRoutes() {
const modules = Object.assign([], navigation.getModules().value); const modules = Object.assign([], navigation.getModules().value);
for (const item of modules) { for (const item of modules) {
const moduleDef = routes.find( const moduleDef = routes.find(
(route) => toLowerCamel(route.name) === item.module, (route) => toLowerCamel(route.name) === item.module
); );
if (!moduleDef) continue; if (!moduleDef) continue;
item.children = []; item.children = [];
@ -129,15 +119,18 @@ function getMainRoutes() {
items.value = modules; items.value = modules;
} }
function getCardRoutes() { if (props.source === 'card') {
const currentRoute = route.matched[1]; const currentRoute = route.matched[1];
const currentModule = toLowerCamel(currentRoute.name); const currentModule = toLowerCamel(currentRoute.name);
let moduleDef = routes.find((route) => toLowerCamel(route.name) === currentModule); let moduleDef = routes.find(
(route) => toLowerCamel(route.name) === currentModule
);
if (!moduleDef) return; if (!moduleDef) return;
if (!moduleDef?.menus) moduleDef = betaGetRoutes(); if (!moduleDef?.menus) moduleDef = betaGetRoutes();
addChildren(currentModule, moduleDef, items.value); addChildren(currentModule, moduleDef, items.value);
} }
}
function betaGetRoutes() { function betaGetRoutes() {
let menuRoute; let menuRoute;
@ -181,10 +174,6 @@ function normalize(text) {
.replace(/[\u0300-\u036f]/g, '') .replace(/[\u0300-\u036f]/g, '')
.toLowerCase(); .toLowerCase();
} }
const searchModule = () => {
const [item] = filteredItems.value;
if (item) router.push({ name: item.name });
};
</script> </script>
<template> <template>
@ -199,11 +188,10 @@ const searchModule = () => {
filled filled
dense dense
autofocus autofocus
@keyup.enter.stop="searchModule()"
/> />
</QItem> </QItem>
<QSeparator /> <QSeparator />
<template v-if="filteredPinnedModules.size && !search"> <template v-if="filteredPinnedModules.size">
<LeftMenuItem <LeftMenuItem
v-for="[key, pinnedModule] of filteredPinnedModules" v-for="[key, pinnedModule] of filteredPinnedModules"
:key="key" :key="key"
@ -227,18 +215,11 @@ const searchModule = () => {
</LeftMenuItem> </LeftMenuItem>
<QSeparator /> <QSeparator />
</template> </template>
<template v-for="(item, index) in filteredItems" :key="item.name"> <template v-for="item in filteredItems" :key="item.name">
<template <template
v-if=" v-if="item.children && !filteredPinnedModules.has(item.name)"
search ||
(item.children && !filteredPinnedModules.has(item.name))
"
>
<LeftMenuItem
:item="item"
group="modules"
:class="search && index === 0 ? 'searched' : ''"
> >
<LeftMenuItem :item="item" group="modules">
<template #side> <template #side>
<QBtn <QBtn
v-if="item.isPinned === true" v-if="item.isPinned === true"
@ -355,9 +336,6 @@ const searchModule = () => {
.header { .header {
color: var(--vn-label-color); color: var(--vn-label-color);
} }
.searched {
background-color: var(--vn-section-hover-color);
}
</style> </style>
<i18n> <i18n>
es: es:

View File

@ -20,7 +20,6 @@ const appName = 'Lilium';
const pinnedModulesRef = ref(); const pinnedModulesRef = ref();
onMounted(() => stateStore.setMounted()); onMounted(() => stateStore.setMounted());
const refresh = () => window.location.reload();
</script> </script>
<template> <template>
<QHeader color="white" elevated> <QHeader color="white" elevated>
@ -65,13 +64,6 @@ const refresh = () => window.location.reload();
<QSpace /> <QSpace />
<div class="q-pl-sm q-gutter-sm row items-center no-wrap"> <div class="q-pl-sm q-gutter-sm row items-center no-wrap">
<div id="actions-prepend"></div> <div id="actions-prepend"></div>
<QIcon
name="refresh"
size="md"
color="red"
v-if="state.get('error')"
@click="refresh"
/>
<QBtn <QBtn
:class="{ 'q-pa-none': quasar.platform.is.mobile }" :class="{ 'q-pa-none': quasar.platform.is.mobile }"
id="pinnedModules" id="pinnedModules"

View File

@ -2,9 +2,26 @@
defineProps({ row: { type: Object, required: true } }); defineProps({ row: { type: Object, required: true } });
</script> </script>
<template> <template>
<span class="q-gutter-x-xs"> <span>
<QIcon <QIcon
v-if="row?.risk" v-if="row.isTaxDataChecked === 0"
name="vn:no036"
color="primary"
size="xs"
>
<QTooltip>{{ $t('salesTicketsTable.noVerifiedData') }}</QTooltip>
</QIcon>
<QIcon v-if="row.hasTicketRequest" name="vn:buyrequest" color="primary" size="xs">
<QTooltip>{{ $t('salesTicketsTable.purchaseRequest') }}</QTooltip>
</QIcon>
<QIcon v-if="row.itemShortage" name="vn:unavailable" color="primary" size="xs">
<QTooltip>{{ $t('salesTicketsTable.notVisible') }}</QTooltip>
</QIcon>
<QIcon v-if="row.isFreezed" name="vn:frozen" color="primary" size="xs">
<QTooltip>{{ $t('salesTicketsTable.clientFrozen') }}</QTooltip>
</QIcon>
<QIcon
v-if="row.risk"
name="vn:risk" name="vn:risk"
:color="row.hasHighRisk ? 'negative' : 'primary'" :color="row.hasHighRisk ? 'negative' : 'primary'"
size="xs" size="xs"
@ -13,57 +30,10 @@ defineProps({ row: { type: Object, required: true } });
{{ $t('salesTicketsTable.risk') }}: {{ row.risk - row.credit }} {{ $t('salesTicketsTable.risk') }}: {{ row.risk - row.credit }}
</QTooltip> </QTooltip>
</QIcon> </QIcon>
<QIcon <QIcon v-if="row.hasComponentLack" name="vn:components" color="primary" size="xs">
v-if="row?.hasComponentLack"
name="vn:components"
color="primary"
size="xs"
>
<QTooltip>{{ $t('salesTicketsTable.componentLack') }}</QTooltip> <QTooltip>{{ $t('salesTicketsTable.componentLack') }}</QTooltip>
</QIcon> </QIcon>
<QIcon v-if="row?.hasItemDelay" color="primary" size="xs" name="vn:hasItemDelay"> <QIcon v-if="row.isTooLittle" name="vn:isTooLittle" color="primary" size="xs">
<QTooltip>
{{ $t('ticket.summary.hasItemDelay') }}
</QTooltip>
</QIcon>
<QIcon v-if="row?.hasItemLost" color="primary" size="xs" name="vn:hasItemLost">
<QTooltip>
{{ $t('salesTicketsTable.hasItemLost') }}
</QTooltip>
</QIcon>
<QIcon
v-if="row?.hasItemShortage"
name="vn:unavailable"
color="primary"
size="xs"
>
<QTooltip>{{ $t('salesTicketsTable.notVisible') }}</QTooltip>
</QIcon>
<QIcon v-if="row?.hasRounding" color="primary" name="sync_problem" size="xs">
<QTooltip>
{{ $t('ticketList.rounding') }}
</QTooltip>
</QIcon>
<QIcon
v-if="row?.hasTicketRequest"
name="vn:buyrequest"
color="primary"
size="xs"
>
<QTooltip>{{ $t('salesTicketsTable.purchaseRequest') }}</QTooltip>
</QIcon>
<QIcon
v-if="!row?.isTaxDataChecked === 0"
name="vn:no036"
color="primary"
size="xs"
>
<QTooltip>{{ $t('salesTicketsTable.noVerifiedData') }}</QTooltip>
</QIcon>
<QIcon v-if="row?.isFreezed" name="vn:frozen" color="primary" size="xs">
<QTooltip>{{ $t('salesTicketsTable.clientFrozen') }}</QTooltip>
</QIcon>
<QIcon v-if="row?.isTooLittle" name="vn:isTooLittle" color="primary" size="xs">
<QTooltip>{{ $t('salesTicketsTable.tooLittle') }}</QTooltip> <QTooltip>{{ $t('salesTicketsTable.tooLittle') }}</QTooltip>
</QIcon> </QIcon>
</span> </span>

View File

@ -1,9 +1,6 @@
<script setup> <script setup>
import quasarLang from 'src/utils/quasarLang';
import { onMounted, computed, ref } from 'vue'; import { onMounted, computed, ref } from 'vue';
import { Dark, Quasar } from 'quasar';
import { Dark } from 'quasar';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import { useRouter } from 'vue-router'; import { useRouter } from 'vue-router';
import axios from 'axios'; import axios from 'axios';
@ -34,7 +31,14 @@ const userLocale = computed({
value = localeEquivalence[value] ?? value; value = localeEquivalence[value] ?? value;
quasarLang(value); try {
/* @vite-ignore */
import(`../../node_modules/quasar/lang/${value}.mjs`).then((lang) => {
Quasar.lang.set(lang.default);
});
} catch (error) {
//
}
}, },
}); });

View File

@ -181,7 +181,7 @@ onMounted(() => {
watch( watch(
() => $props.columns, () => $props.columns,
(value) => splitColumns(value), (value) => splitColumns(value),
{ immediate: true }, { immediate: true }
); );
const isTableMode = computed(() => mode.value == TABLE_MODE); const isTableMode = computed(() => mode.value == TABLE_MODE);
@ -212,7 +212,7 @@ function splitColumns(columns) {
// Status column // Status column
if (splittedColumns.value.chips.length) { if (splittedColumns.value.chips.length) {
splittedColumns.value.columnChips = splittedColumns.value.chips.filter( splittedColumns.value.columnChips = splittedColumns.value.chips.filter(
(c) => !c.isId, (c) => !c.isId
); );
if (splittedColumns.value.columnChips.length) if (splittedColumns.value.columnChips.length)
splittedColumns.value.columns.unshift({ splittedColumns.value.columns.unshift({
@ -314,19 +314,7 @@ function handleSelection({ evt, added, rows: selectedRows }, rows) {
show-if-above show-if-above
> >
<QScrollArea class="fit"> <QScrollArea class="fit">
<VnTableFilter <VnTableFilter :data-key="$attrs['data-key']" :columns="columns" :redirect="redirect" />
:data-key="$attrs['data-key']"
:columns="columns"
:redirect="redirect"
>
<template
v-for="(_, slotName) in $slots"
#[slotName]="slotData"
:key="slotName"
>
<slot :name="slotName" v-bind="slotData ?? {}" :key="slotName" />
</template>
</VnTableFilter>
</QScrollArea> </QScrollArea>
</QDrawer> </QDrawer>
<CrudModel <CrudModel
@ -484,9 +472,7 @@ function handleSelection({ evt, added, rows: selectedRows }, rows) {
btn.isPrimary ? 'text-primary-light' : 'color-vn-text ' btn.isPrimary ? 'text-primary-light' : 'color-vn-text '
" "
:style="`visibility: ${ :style="`visibility: ${
((btn.show && btn.show(row)) ?? true) (btn.show && btn.show(row)) ?? true ? 'visible' : 'hidden'
? 'visible'
: 'hidden'
}`" }`"
@click="btn.action(row)" @click="btn.action(row)"
/> />
@ -500,7 +486,7 @@ function handleSelection({ evt, added, rows: selectedRows }, rows) {
<QCard <QCard
bordered bordered
flat flat
class="row no-wrap justify-between cursor-pointer q-pa-sm" class="row no-wrap justify-between cursor-pointer"
@click=" @click="
(_, row) => { (_, row) => {
$props.rowClick && $props.rowClick(row); $props.rowClick && $props.rowClick(row);
@ -581,6 +567,7 @@ function handleSelection({ evt, added, rows: selectedRows }, rows) {
<!-- Actions --> <!-- Actions -->
<QCardSection <QCardSection
v-if="colsMap.tableActions" v-if="colsMap.tableActions"
class="column flex-center w-10 no-margin q-pa-xs q-gutter-y-xs"
@click="stopEventPropagation($event)" @click="stopEventPropagation($event)"
> >
<QBtn <QBtn
@ -629,7 +616,7 @@ function handleSelection({ evt, added, rows: selectedRows }, rows) {
size="md" size="md"
round round
flat flat
v-shortcut="'+'" shortcut="+"
:disabled="!disabledAttr" :disabled="!disabledAttr"
/> />
<QTooltip> <QTooltip>
@ -647,7 +634,7 @@ function handleSelection({ evt, added, rows: selectedRows }, rows) {
color="primary" color="primary"
fab fab
icon="add" icon="add"
v-shortcut="'+'" shortcut="+"
data-cy="vnTableCreateBtn" data-cy="vnTableCreateBtn"
/> />
<QTooltip self="top right"> <QTooltip self="top right">
@ -806,15 +793,12 @@ es:
.grid-two { .grid-two {
display: grid; display: grid;
grid-template-columns: 2fr 2fr; grid-template-columns: repeat(auto-fit, minmax(150px, max-content));
.vn-label-value { max-width: 100%;
flex-direction: column; margin: 0 auto;
white-space: nowrap; overflow: scroll;
.fields { white-space: wrap;
display: flex; width: 100%;
}
}
white-space: nowrap;
} }
.w-80 { .w-80 {

View File

@ -27,7 +27,7 @@ function columnName(col) {
</script> </script>
<template> <template>
<VnFilterPanel v-bind="$attrs" :search-button="true" :disable-submit-event="true"> <VnFilterPanel v-bind="$attrs" :search-button="true" :disable-submit-event="true">
<template #body="{ params, orders, searchFn }"> <template #body="{ params, orders }">
<div <div
class="row no-wrap flex-center" class="row no-wrap flex-center"
v-for="col of columns.filter((c) => c.columnFilter ?? true)" v-for="col of columns.filter((c) => c.columnFilter ?? true)"
@ -52,7 +52,6 @@ function columnName(col) {
<slot <slot
name="moreFilterPanel" name="moreFilterPanel"
:params="params" :params="params"
:search-fn="searchFn"
:orders="orders" :orders="orders"
:columns="columns" :columns="columns"
/> />
@ -63,8 +62,5 @@ function columnName(col) {
<span>{{ formatFn(tag.value) }}</span> <span>{{ formatFn(tag.value) }}</span>
</div> </div>
</template> </template>
<template v-for="(_, slotName) in $slots" #[slotName]="slotData" :key="slotName">
<slot :name="slotName" v-bind="slotData ?? {}" :key="slotName" />
</template>
</VnFilterPanel> </VnFilterPanel>
</template> </template>

View File

@ -1,121 +0,0 @@
import { describe, expect, it, beforeEach, afterEach, vi } from 'vitest';
import { createWrapper } from 'app/test/vitest/helper';
import VnVisibleColumn from '../VnVisibleColumn.vue';
import { axios } from 'app/test/vitest/helper';
describe('VnVisibleColumns', () => {
let wrapper;
let vm;
beforeEach(() => {
wrapper = createWrapper(VnVisibleColumn, {
propsData: {
tableCode: 'testTable',
skip: ['skippedColumn'],
},
});
vm = wrapper.vm;
});
afterEach(() => {
vi.clearAllMocks();
});
describe('setUserConfigViewData()', () => {
it('should initialize localColumns with visible configuration', () => {
vm.columns = [
{ name: 'columnMockName', label: undefined },
{ name: 'columnMockAddress', label: undefined },
{ name: 'columnMockId', label: undefined },
];
const configuration = {
columnMockName: true,
columnMockAddress: false,
columnMockId: true,
};
const expectedColumns = [
{ name: 'columnMockName', label: undefined, visible: true },
{ name: 'columnMockAddress', label: undefined, visible: false },
{ name: 'columnMockId', label: undefined, visible: true },
];
vm.setUserConfigViewData(configuration, false);
expect(vm.localColumns).toEqual(expectedColumns);
});
it('should skip columns based on props', () => {
vm.columns = [
{ name: 'columnMockName', label: undefined },
{ name: 'columnMockId', label: undefined },
{ name: 'skippedColumn', label: 'Skipped Column' },
];
const configuration = {
columnMockName: true,
skippedColumn: false,
columnMockId: true,
};
const expectedColumns = [
{ name: 'columnMockName', label: undefined, visible: true },
{ name: 'columnMockId', label: undefined, visible: true },
];
vm.setUserConfigViewData(configuration, false);
expect(vm.localColumns).toEqual(expectedColumns);
});
});
describe('toggleMarkAll()', () => {
it('should set all localColumns to visible=true', () => {
vm.localColumns = [
{ name: 'columnMockName', visible: false },
{ name: 'columnMockId', visible: false },
];
vm.toggleMarkAll(true);
expect(vm.localColumns.every((col) => col.visible)).toBe(true);
});
it('should set all localColumns to visible=false', () => {
vm.localColumns = [
{ name: 'columnMockName', visible: true },
{ name: 'columnMockId', visible: true },
];
vm.toggleMarkAll(false);
expect(vm.localColumns.every((col) => col.visible)).toBe(false);
});
});
describe('saveConfig()', () => {
it('should call setUserConfigViewData and axios.post with correct params', async () => {
const mockAxiosPost = vi.spyOn(axios, 'post').mockResolvedValue({
data: [{ id: 1 }],
});
vm.localColumns = [
{ name: 'columnMockName', visible: true },
{ name: 'columnMockId', visible: false },
];
await vm.saveConfig();
expect(mockAxiosPost).toHaveBeenCalledWith('UserConfigViews/crud', {
creates: [
{
userFk: vm.user.id,
tableCode: vm.tableCode,
tableConfig: vm.tableCode,
configuration: {
columnMockName: true,
columnMockId: false,
},
},
],
});
});
});
});

View File

@ -1,12 +0,0 @@
export default function (initialFooter, data) {
const footer = data.reduce(
(acc, row) => {
Object.entries(initialFooter).forEach(([key, initialValue]) => {
acc[key] += row?.[key] !== undefined ? row[key] : initialValue;
});
return acc;
},
{ ...initialFooter }
);
return footer;
}

View File

@ -93,7 +93,7 @@ describe('FormModel', () => {
it('should call axios.patch with the right data', async () => { it('should call axios.patch with the right data', async () => {
const spy = vi.spyOn(axios, 'patch').mockResolvedValue({ data: {} }); const spy = vi.spyOn(axios, 'patch').mockResolvedValue({ data: {} });
const { vm } = mount({ propsData: { url, model } }); const { vm } = mount({ propsData: { url, model, formInitialData } });
vm.formData.mockKey = 'newVal'; vm.formData.mockKey = 'newVal';
await vm.$nextTick(); await vm.$nextTick();
await vm.save(); await vm.save();
@ -106,7 +106,6 @@ describe('FormModel', () => {
const { vm } = mount({ const { vm } = mount({
propsData: { url, model, formInitialData, urlCreate: 'mockUrlCreate' }, propsData: { url, model, formInitialData, urlCreate: 'mockUrlCreate' },
}); });
await vm.$nextTick();
vm.formData.mockKey = 'newVal'; vm.formData.mockKey = 'newVal';
await vm.$nextTick(); await vm.$nextTick();
await vm.save(); await vm.save();
@ -120,7 +119,7 @@ describe('FormModel', () => {
}); });
const spyPatch = vi.spyOn(axios, 'patch').mockResolvedValue({ data: {} }); const spyPatch = vi.spyOn(axios, 'patch').mockResolvedValue({ data: {} });
const spySaveFn = vi.spyOn(vm.$props, 'saveFn'); const spySaveFn = vi.spyOn(vm.$props, 'saveFn');
await vm.$nextTick();
vm.formData.mockKey = 'newVal'; vm.formData.mockKey = 'newVal';
await vm.$nextTick(); await vm.$nextTick();
await vm.save(); await vm.save();

View File

@ -1,11 +1,8 @@
import { vi, describe, expect, it, beforeAll, beforeEach, afterEach } from 'vitest'; import { vi, describe, expect, it, beforeAll } from 'vitest';
import { createWrapper, axios } from 'app/test/vitest/helper'; import { createWrapper, axios } from 'app/test/vitest/helper';
import Leftmenu from 'components/LeftMenu.vue'; import Leftmenu from 'components/LeftMenu.vue';
import * as vueRouter from 'vue-router';
import { useNavigationStore } from 'src/stores/useNavigationStore';
let vm; import { useNavigationStore } from 'src/stores/useNavigationStore';
let navigation;
vi.mock('src/router/modules', () => ({ vi.mock('src/router/modules', () => ({
default: [ default: [
@ -24,16 +21,6 @@ vi.mock('src/router/modules', () => ({
{ {
path: '', path: '',
name: 'CustomerMain', name: 'CustomerMain',
meta: {
menu: 'Customer',
menuChildren: [
{
name: 'CustomerCreditContracts',
title: 'creditContracts',
icon: 'vn:solunion',
},
],
},
children: [ children: [
{ {
path: 'list', path: 'list',
@ -41,13 +28,6 @@ vi.mock('src/router/modules', () => ({
meta: { meta: {
title: 'list', title: 'list',
icon: 'view_list', icon: 'view_list',
menuChildren: [
{
name: 'CustomerCreditContracts',
title: 'creditContracts',
icon: 'vn:solunion',
},
],
}, },
}, },
{ {
@ -64,59 +44,20 @@ vi.mock('src/router/modules', () => ({
}, },
], ],
})); }));
vi.spyOn(vueRouter, 'useRoute').mockReturnValue({
matched: [ describe('Leftmenu', () => {
{ let vm;
path: '/', let navigation;
redirect: { beforeAll(() => {
name: 'Dashboard',
},
name: 'Main',
meta: {},
props: {
default: false,
},
children: [
{
path: '/dashboard',
name: 'Dashboard',
meta: {
title: 'dashboard',
icon: 'dashboard',
},
},
],
},
{
path: '/customer',
redirect: {
name: 'CustomerMain',
},
name: 'Customer',
meta: {
title: 'customers',
icon: 'vn:client',
moduleName: 'Customer',
keyBinding: 'c',
menu: 'customer',
},
},
],
query: {},
params: {},
meta: { moduleName: 'mockName' },
path: 'mockName/1',
name: 'Customer',
});
function mount(source = 'main') {
vi.spyOn(axios, 'get').mockResolvedValue({ vi.spyOn(axios, 'get').mockResolvedValue({
data: [], data: [],
}); });
const wrapper = createWrapper(Leftmenu, {
vm = createWrapper(Leftmenu, {
propsData: { propsData: {
source, source: 'main',
}, },
}); }).vm;
navigation = useNavigationStore(); navigation = useNavigationStore();
navigation.fetchPinned = vi.fn().mockReturnValue(Promise.resolve(true)); navigation.fetchPinned = vi.fn().mockReturnValue(Promise.resolve(true));
@ -130,259 +71,24 @@ function mount(source = 'main') {
}, },
], ],
}); });
return wrapper;
}
describe('getRoutes', () => {
afterEach(() => vi.clearAllMocks());
const getRoutes = vi.fn().mockImplementation((props, getMethodA, getMethodB) => {
const handleRoutes = {
methodA: getMethodA,
methodB: getMethodB,
};
try {
handleRoutes[props.source]();
} catch (error) {
throw Error('Method not defined');
}
}); });
const getMethodA = vi.fn(); it('should return a proper formated object with two child items', async () => {
const getMethodB = vi.fn(); const expectedMenuItem = [
const fn = (props) => getRoutes(props, getMethodA, getMethodB); {
children: null,
it('should call getMethodB when source is card', () => { name: 'CustomerList',
let props = { source: 'methodB' }; title: 'globals.pageTitles.list',
fn(props); icon: 'view_list',
},
expect(getMethodB).toHaveBeenCalled(); {
expect(getMethodA).not.toHaveBeenCalled(); children: null,
}); name: 'CustomerCreate',
it('should call getMethodA when source is main', () => { title: 'globals.pageTitles.createCustomer',
let props = { source: 'methodA' }; icon: 'vn:addperson',
fn(props); },
expect(getMethodA).toHaveBeenCalled();
expect(getMethodB).not.toHaveBeenCalled();
});
it('should call getMethodA when source is not exists or undefined', () => {
let props = { source: 'methodC' };
expect(() => fn(props)).toThrowError('Method not defined');
expect(getMethodA).not.toHaveBeenCalled();
expect(getMethodB).not.toHaveBeenCalled();
});
});
describe('Leftmenu as card', () => {
beforeAll(() => {
vm = mount('card').vm;
});
it('should get routes for card source', async () => {
vm.getRoutes();
});
});
describe('Leftmenu as main', () => {
beforeEach(() => {
vm = mount().vm;
});
it('should initialize with default props', () => {
expect(vm.source).toBe('main');
});
it('should filter items based on search input', async () => {
vm.search = 'cust';
await vm.$nextTick();
expect(vm.filteredItems[0].name).toEqual('customer');
expect(vm.filteredItems[0].module).toEqual('customer');
});
it('should filter items based on search input', async () => {
vm.search = 'Rou';
await vm.$nextTick();
expect(vm.filteredItems).toEqual([]);
});
it('should return pinned items', () => {
vm.items = [
{ name: 'Item 1', isPinned: false },
{ name: 'Item 2', isPinned: true },
]; ];
expect(vm.pinnedModules).toEqual( const firstMenuItem = vm.items[0];
new Map([['Item 2', { name: 'Item 2', isPinned: true }]]), expect(firstMenuItem.children).toEqual(expect.arrayContaining(expectedMenuItem));
);
});
it('should find matches in routes', () => {
const search = 'child1';
const item = {
children: [
{ name: 'child1', children: [] },
{ name: 'child2', children: [] },
],
};
const matches = vm.findMatches(search, item);
expect(matches).toEqual([{ name: 'child1', children: [] }]);
});
it('should not proceed if event is already prevented', async () => {
const item = { module: 'testModule', isPinned: false };
const event = {
preventDefault: vi.fn(),
stopPropagation: vi.fn(),
defaultPrevented: true,
};
await vm.togglePinned(item, event);
expect(event.preventDefault).not.toHaveBeenCalled();
expect(event.stopPropagation).not.toHaveBeenCalled();
});
it('should call quasar.notify with success message', async () => {
const item = { module: 'testModule', isPinned: false };
const event = {
preventDefault: vi.fn(),
stopPropagation: vi.fn(),
defaultPrevented: false,
};
const response = { data: { id: 1 } };
vi.spyOn(axios, 'post').mockResolvedValue(response);
vi.spyOn(vm.quasar, 'notify');
await vm.togglePinned(item, event);
expect(vm.quasar.notify).toHaveBeenCalledWith({
message: 'Data saved',
type: 'positive',
});
});
it('should handle a single matched route with a menu', () => {
const route = {
matched: [{ meta: { menu: 'customer' } }],
};
const result = vm.betaGetRoutes();
expect(result.meta.menu).toEqual(route.matched[0].meta.menu);
});
it('should get routes for main source', () => {
vm.props.source = 'main';
vm.getRoutes();
expect(navigation.getModules).toHaveBeenCalled();
});
it('should find direct child matches', () => {
const search = 'child1';
const item = {
children: [{ name: 'child1' }, { name: 'child2' }],
};
const result = vm.findMatches(search, item);
expect(result).toEqual([{ name: 'child1' }]);
});
it('should find nested child matches', () => {
const search = 'child3';
const item = {
children: [
{ name: 'child1' },
{
name: 'child2',
children: [{ name: 'child3' }],
},
],
};
const result = vm.findMatches(search, item);
expect(result).toEqual([{ name: 'child3' }]);
});
});
describe('normalize', () => {
beforeAll(() => {
vm = mount('card').vm;
});
it('should normalize and lowercase text', () => {
const input = 'ÁÉÍÓÚáéíóú';
const expected = 'aeiouaeiou';
expect(vm.normalize(input)).toBe(expected);
});
it('should handle empty string', () => {
const input = '';
const expected = '';
expect(vm.normalize(input)).toBe(expected);
});
it('should handle text without diacritics', () => {
const input = 'hello';
const expected = 'hello';
expect(vm.normalize(input)).toBe(expected);
});
it('should handle mixed text', () => {
const input = 'Héllo Wórld!';
const expected = 'hello world!';
expect(vm.normalize(input)).toBe(expected);
});
});
describe('addChildren', () => {
const module = 'testModule';
beforeEach(() => {
vm = mount().vm;
vi.clearAllMocks();
});
it('should add menu items to parent if matches are found', () => {
const parent = 'testParent';
const route = {
meta: {
menu: 'testMenu',
},
children: [{ name: 'child1' }, { name: 'child2' }],
};
vm.addChildren(module, route, parent);
expect(navigation.addMenuItem).toHaveBeenCalled();
});
it('should handle routes with no meta menu', () => {
const route = {
meta: {},
menus: {},
};
const parent = [];
vm.addChildren(module, route, parent);
expect(navigation.addMenuItem).toHaveBeenCalled();
});
it('should handle empty parent array', () => {
const parent = [];
const route = {
meta: {
menu: 'child11',
},
children: [
{
name: 'child1',
meta: {
menuChildren: [
{
name: 'CustomerCreditContracts',
title: 'creditContracts',
icon: 'vn:solunion',
},
],
},
},
],
};
vm.addChildren(module, route, parent);
expect(navigation.addMenuItem).toHaveBeenCalled();
}); });
}); });

View File

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

View File

@ -1,53 +0,0 @@
<script setup>
import { useI18n } from 'vue-i18n';
import { useStateStore } from 'stores/useStateStore';
import { useHasContent } from 'src/composables/useHasContent';
import { watch } from 'vue';
const { t } = useI18n();
const stateStore = useStateStore();
const hasContent = useHasContent('#advanced-menu');
const $props = defineProps({
isMainSection: {
type: Boolean,
default: false,
},
});
watch(
() => $props.isMainSection,
(val) => {
if (stateStore) stateStore.rightAdvancedDrawer = val;
},
{ immediate: true },
);
</script>
<template>
<Teleport to="#searchbar-after" v-if="stateStore.isHeaderMounted()">
<QBtn
v-if="hasContent || $slots['advanced-menu']"
flat
@click="stateStore.toggleRightAdvancedDrawer()"
round
icon="tune"
color="white"
>
<QTooltip bottom anchor="bottom right">
{{ t('globals.advancedMenu') }}
</QTooltip>
</QBtn>
</Teleport>
<QDrawer
v-model="stateStore.rightAdvancedDrawer"
side="right"
:width="256"
:overlay="!isMainSection"
v-bind="$attrs"
>
<QScrollArea class="fit">
<div id="advanced-menu"></div>
<slot v-if="!hasContent" name="advanced-menu" />
</QScrollArea>
</QDrawer>
</template>

View File

@ -17,7 +17,7 @@ onMounted(() => {
}); });
</script> </script>
<template> <template>
<Teleport to="#actions-prepend" v-if="stateStore.isHeaderMounted()"> <Teleport to="#actions-append" v-if="stateStore.isHeaderMounted()">
<div class="row q-gutter-x-sm"> <div class="row q-gutter-x-sm">
<QBtn <QBtn
v-if="hasContent || $slots['right-panel']" v-if="hasContent || $slots['right-panel']"
@ -26,7 +26,6 @@ onMounted(() => {
round round
dense dense
icon="dock_to_left" icon="dock_to_left"
data-cy="toggle-right-drawer"
> >
<QTooltip bottom anchor="bottom right"> <QTooltip bottom anchor="bottom right">
{{ t('globals.collapseMenu') }} {{ t('globals.collapseMenu') }}

View File

@ -10,11 +10,11 @@ import LeftMenu from 'components/LeftMenu.vue';
import RightMenu from 'components/common/RightMenu.vue'; import RightMenu from 'components/common/RightMenu.vue';
const props = defineProps({ const props = defineProps({
dataKey: { type: String, required: true }, dataKey: { type: String, required: true },
url: { type: String, default: undefined }, baseUrl: { type: String, default: undefined },
customUrl: { type: String, default: undefined },
filter: { type: Object, default: () => {} }, filter: { type: Object, default: () => {} },
descriptor: { type: Object, required: true }, descriptor: { type: Object, required: true },
filterPanel: { type: Object, default: undefined }, filterPanel: { type: Object, default: undefined },
idInWhere: { type: Boolean, default: false },
searchDataKey: { type: String, default: undefined }, searchDataKey: { type: String, default: undefined },
searchbarProps: { type: Object, default: undefined }, searchbarProps: { type: Object, default: undefined },
redirectOnError: { type: Boolean, default: false }, redirectOnError: { type: Boolean, default: false },
@ -23,20 +23,25 @@ const props = defineProps({
const stateStore = useStateStore(); const stateStore = useStateStore();
const route = useRoute(); const route = useRoute();
const router = useRouter(); const router = useRouter();
const url = computed(() => {
if (props.baseUrl) {
return `${props.baseUrl}/${route.params.id}`;
}
return props.customUrl;
});
const searchRightDataKey = computed(() => { const searchRightDataKey = computed(() => {
if (!props.searchDataKey) return route.name; if (!props.searchDataKey) return route.name;
return props.searchDataKey; return props.searchDataKey;
}); });
const arrayData = useArrayData(props.dataKey, { const arrayData = useArrayData(props.dataKey, {
url: props.url, url: url.value,
userFilter: props.filter, filter: props.filter,
oneRecord: true,
}); });
onBeforeMount(async () => { onBeforeMount(async () => {
try { try {
await fetch(route.params.id); if (!props.baseUrl) arrayData.store.filter.where = { id: route.params.id };
await arrayData.fetch({ append: false, updateRouter: false });
} catch { } catch {
const { matched: matches } = router.currentRoute.value; const { matched: matches } = router.currentRoute.value;
const { path } = matches.at(-1); const { path } = matches.at(-1);
@ -44,17 +49,13 @@ onBeforeMount(async () => {
} }
}); });
if (props.baseUrl) {
onBeforeRouteUpdate(async (to, from) => { onBeforeRouteUpdate(async (to, from) => {
const id = to.params.id; if (to.params.id !== from.params.id) {
if (id !== from.params.id) await fetch(id, true); arrayData.store.url = `${props.baseUrl}/${to.params.id}`;
await arrayData.fetch({ append: false, updateRouter: false });
}
}); });
async function fetch(id, append = false) {
const regex = /\/(\d+)/;
if (props.idInWhere) arrayData.store.filter.where = { id };
else if (!regex.test(props.url)) arrayData.store.url = `${props.url}/${id}`;
else arrayData.store.url = props.url.replace(regex, `/${id}`);
await arrayData.fetch({ append, updateRouter: false });
} }
</script> </script>
<template> <template>
@ -82,7 +83,7 @@ async function fetch(id, append = false) {
<QPage> <QPage>
<VnSubToolbar /> <VnSubToolbar />
<div :class="[useCardSize(), $attrs.class]"> <div :class="[useCardSize(), $attrs.class]">
<RouterView :key="$route.path" /> <RouterView :key="route.path" />
</div> </div>
</QPage> </QPage>
</QPageContainer> </QPageContainer>

View File

@ -1,6 +1,6 @@
<script setup> <script setup>
import { onBeforeMount } from 'vue'; import { onBeforeMount, computed } from 'vue';
import { useRouter, onBeforeRouteUpdate } from 'vue-router'; import { useRoute, useRouter, onBeforeRouteUpdate } from 'vue-router';
import { useArrayData } from 'src/composables/useArrayData'; import { useArrayData } from 'src/composables/useArrayData';
import { useStateStore } from 'stores/useStateStore'; import { useStateStore } from 'stores/useStateStore';
import useCardSize from 'src/composables/useCardSize'; import useCardSize from 'src/composables/useCardSize';
@ -9,8 +9,8 @@ import VnSubToolbar from '../ui/VnSubToolbar.vue';
const props = defineProps({ const props = defineProps({
dataKey: { type: String, required: true }, dataKey: { type: String, required: true },
url: { type: String, default: undefined }, baseUrl: { type: String, default: undefined },
idInWhere: { type: Boolean, default: false }, customUrl: { type: String, default: undefined },
filter: { type: Object, default: () => {} }, filter: { type: Object, default: () => {} },
descriptor: { type: Object, required: true }, descriptor: { type: Object, required: true },
filterPanel: { type: Object, default: undefined }, filterPanel: { type: Object, default: undefined },
@ -20,35 +20,38 @@ const props = defineProps({
}); });
const stateStore = useStateStore(); const stateStore = useStateStore();
const route = useRoute();
const router = useRouter(); const router = useRouter();
const url = computed(() => {
if (props.baseUrl) {
return `${props.baseUrl}/${route.params.id}`;
}
return props.customUrl;
});
const arrayData = useArrayData(props.dataKey, { const arrayData = useArrayData(props.dataKey, {
url: props.url, url: url.value,
userFilter: props.filter, filter: props.filter,
oneRecord: true,
}); });
onBeforeMount(async () => { onBeforeMount(async () => {
const route = router.currentRoute.value;
try { try {
await fetch(route.params.id); if (!props.baseUrl) arrayData.store.filter.where = { id: route.params.id };
await arrayData.fetch({ append: false, updateRouter: false });
} catch { } catch {
const { matched: matches } = route; const { matched: matches } = router.currentRoute.value;
const { path } = matches.at(-1); const { path } = matches.at(-1);
router.push({ path: path.replace(/:id.*/, '') }); router.push({ path: path.replace(/:id.*/, '') });
} }
}); });
if (props.baseUrl) {
onBeforeRouteUpdate(async (to, from) => { onBeforeRouteUpdate(async (to, from) => {
const id = to.params.id; if (to.params.id !== from.params.id) {
if (id !== from.params.id) await fetch(id, true); arrayData.store.url = `${props.baseUrl}/${to.params.id}`;
await arrayData.fetch({ append: false, updateRouter: false });
}
}); });
async function fetch(id, append = false) {
const regex = /\/(\d+)/;
if (props.idInWhere) arrayData.store.filter.where = { id };
else if (!regex.test(props.url)) arrayData.store.url = `${props.url}/${id}`;
else arrayData.store.url = props.url.replace(regex, `/${id}`);
await arrayData.fetch({ append, updateRouter: false });
} }
</script> </script>
<template> <template>
@ -59,6 +62,6 @@ async function fetch(id, append = false) {
</Teleport> </Teleport>
<VnSubToolbar /> <VnSubToolbar />
<div :class="[useCardSize(), $attrs.class]"> <div :class="[useCardSize(), $attrs.class]">
<RouterView :key="$route.path" /> <RouterView :key="route.path" />
</div> </div>
</template> </template>

View File

@ -17,7 +17,7 @@ import { useSession } from 'src/composables/useSession';
const route = useRoute(); const route = useRoute();
const quasar = useQuasar(); const quasar = useQuasar();
const { t } = useI18n(); const { t } = useI18n();
const rows = ref([]); const rows = ref();
const dmsRef = ref(); const dmsRef = ref();
const formDialog = ref({}); const formDialog = ref({});
const token = useSession().getTokenMultimedia(); const token = useSession().getTokenMultimedia();
@ -102,7 +102,7 @@ const columns = computed(() => [
storage: 'dms', storage: 'dms',
collection: null, collection: null,
resolution: null, resolution: null,
id: Number(prop.row.file.split('.')[0]), id: prop.row.file.split('.')[0],
token: token, token: token,
class: 'rounded', class: 'rounded',
ratio: 1, ratio: 1,
@ -202,7 +202,7 @@ const columns = computed(() => [
prop.row.id, prop.row.id,
$props.downloadModel, $props.downloadModel,
undefined, undefined,
prop.row.download, prop.row.download
), ),
}, },
{ {
@ -299,12 +299,11 @@ defineExpose({
:url="$props.model" :url="$props.model"
:user-filter="dmsFilter" :user-filter="dmsFilter"
:order="['dmsFk DESC']" :order="['dmsFk DESC']"
auto-load :auto-load="true"
@on-fetch="setData" @on-fetch="setData"
> >
<template #body> <template #body>
<QTable <QTable
v-if="rows"
:columns="columns" :columns="columns"
:rows="rows" :rows="rows"
class="full-width q-mt-md" class="full-width q-mt-md"
@ -374,7 +373,7 @@ defineExpose({
v-if=" v-if="
shouldRenderButton( shouldRenderButton(
button.name, button.name,
props.row.isDocuware, props.row.isDocuware
) )
" "
:is="button.component" :is="button.component"
@ -389,14 +388,6 @@ defineExpose({
</div> </div>
</template> </template>
</QTable> </QTable>
<div
v-else
class="info-row q-pa-md text-center"
>
<h5>
{{ t('No data to display') }}
</h5>
</div>
</template> </template>
</VnPaginate> </VnPaginate>
<QDialog v-model="formDialog.show"> <QDialog v-model="formDialog.show">
@ -413,7 +404,7 @@ defineExpose({
fab fab
color="primary" color="primary"
icon="add" icon="add"
v-shortcut shortcut="+"
@click="showFormDialog()" @click="showFormDialog()"
class="fill-icon" class="fill-icon"
> >

View File

@ -42,13 +42,10 @@ const $props = defineProps({
type: Number, type: Number,
default: null, default: null,
}, },
uppercase: {
type: Boolean,
default: false,
},
}); });
const vnInputRef = ref(null); const vnInputRef = ref(null);
const showPassword = ref(false);
const value = computed({ const value = computed({
get() { get() {
return $props.modelValue; return $props.modelValue;
@ -75,7 +72,6 @@ const focus = () => {
defineExpose({ defineExpose({
focus, focus,
vnInputRef,
}); });
const mixinRules = [ const mixinRules = [
@ -121,10 +117,6 @@ const handleInsertMode = (e) => {
input.setSelectionRange(cursorPos + 1, cursorPos + 1); input.setSelectionRange(cursorPos + 1, cursorPos + 1);
}); });
}; };
const handleUppercase = () => {
value.value = value.value?.toUpperCase() || '';
};
</script> </script>
<template> <template>
@ -167,20 +159,7 @@ const handleUppercase = () => {
emit('remove'); emit('remove');
} }
" "
></QIcon> />
<QIcon
name="match_case"
size="xs"
v-if="!$attrs.disabled && !($attrs.readonly) && $props.uppercase"
@click="handleUppercase"
class="uppercase-icon"
>
<QTooltip>
{{ t('Convert to uppercase') }}
</QTooltip>
</QIcon>
<slot name="append" v-if="$slots.append && !$attrs.disabled" /> <slot name="append" v-if="$slots.append && !$attrs.disabled" />
<QIcon v-if="info" name="info"> <QIcon v-if="info" name="info">
<QTooltip max-width="350px"> <QTooltip max-width="350px">
@ -191,27 +170,3 @@ const handleUppercase = () => {
</QInput> </QInput>
</div> </div>
</template> </template>
<style>
.uppercase-icon {
transition: color 0.3s, transform 0.2s;
cursor: pointer;
}
.uppercase-icon:hover {
color: #ed9937;
transform: scale(1.2);
}
</style>
<i18n>
en:
inputMin: Must be more than {value}
maxLength: The value exceeds {value} characters
inputMax: Must be less than {value}
es:
inputMin: Debe ser mayor a {value}
maxLength: El valor excede los {value} carácteres
inputMax: Debe ser menor a {value}
Convert to uppercase: Convertir a mayúsculas
</i18n>

View File

@ -105,7 +105,6 @@ const manageDate = (date) => {
:rules="mixinRules" :rules="mixinRules"
:clearable="false" :clearable="false"
@click="isPopupOpen = !isPopupOpen" @click="isPopupOpen = !isPopupOpen"
@keydown="isPopupOpen = false"
hide-bottom-space hide-bottom-space
> >
<template #append> <template #append>

View File

@ -79,7 +79,6 @@ function dateToTime(newDate) {
style="min-width: 100px" style="min-width: 100px"
:rules="mixinRules" :rules="mixinRules"
@click="isPopupOpen = !isPopupOpen" @click="isPopupOpen = !isPopupOpen"
@keydown="isPopupOpen = false"
type="time" type="time"
hide-bottom-space hide-bottom-space
> >

View File

@ -15,7 +15,6 @@ import FetchData from '../FetchData.vue';
import VnSelect from './VnSelect.vue'; import VnSelect from './VnSelect.vue';
import VnUserLink from '../ui/VnUserLink.vue'; import VnUserLink from '../ui/VnUserLink.vue';
import VnPaginate from '../ui/VnPaginate.vue'; import VnPaginate from '../ui/VnPaginate.vue';
import RightMenu from './RightMenu.vue';
const stateStore = useStateStore(); const stateStore = useStateStore();
const validationsStore = useValidator(); const validationsStore = useValidator();
@ -131,7 +130,7 @@ const actionsIcon = {
}; };
const validDate = new RegExp( const validDate = new RegExp(
/^(-?(?:[1-9][0-9]*)?[0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9])/.source + /^(-?(?:[1-9][0-9]*)?[0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9])/.source +
/T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])(.[0-9]+)?(Z)?$/.source, /T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])(.[0-9]+)?(Z)?$/.source
); );
function castJsonValue(value) { function castJsonValue(value) {
@ -193,7 +192,7 @@ function getLogTree(data) {
user: log.user, user: log.user,
userFk: log.userFk, userFk: log.userFk,
logs: [], logs: [],
}), })
); );
} }
// Model // Model
@ -211,7 +210,7 @@ function getLogTree(data) {
id: log.changedModelId, id: log.changedModelId,
showValue: log.changedModelValue, showValue: log.changedModelValue,
logs: [], logs: [],
}), })
); );
nLogs = 0; nLogs = 0;
} }
@ -268,7 +267,7 @@ async function applyFilter() {
filter.where.and.push(selectedFilters.value); filter.where.and.push(selectedFilters.value);
} }
paginate.value.fetch({ filter }); paginate.value.fetch(filter);
} }
function setDate(type) { function setDate(type) {
@ -283,7 +282,7 @@ function setDate(type) {
to = date.adjustDate( to = date.adjustDate(
to, to,
{ hour: 21, minute: 59, second: 59, millisecond: 999 }, { hour: 21, minute: 59, second: 59, millisecond: 999 },
true, true
); );
switch (type) { switch (type) {
@ -366,7 +365,7 @@ async function clearFilter() {
dateTo.value = undefined; dateTo.value = undefined;
userRadio.value = undefined; userRadio.value = undefined;
Object.keys(checkboxOptions.value).forEach( Object.keys(checkboxOptions.value).forEach(
(opt) => (checkboxOptions.value[opt].selected = false), (opt) => (checkboxOptions.value[opt].selected = false)
); );
await applyFilter(); await applyFilter();
} }
@ -379,7 +378,7 @@ watch(
() => router.currentRoute.value.params.id, () => router.currentRoute.value.params.id,
() => { () => {
applyFilter(); applyFilter();
}, }
); );
</script> </script>
<template> <template>
@ -392,7 +391,7 @@ watch(
const changedModel = item.changedModel; const changedModel = item.changedModel;
return { return {
locale: useCapitalize( locale: useCapitalize(
validations[changedModel]?.locale?.name ?? changedModel, validations[changedModel]?.locale?.name ?? changedModel
), ),
value: changedModel, value: changedModel,
}; };
@ -404,7 +403,7 @@ watch(
ref="paginate" ref="paginate"
:data-key="`${model}Log`" :data-key="`${model}Log`"
:url="`${model}Logs`" :url="`${model}Logs`"
:user-filter="filter" :filter="filter"
:skeleton="false" :skeleton="false"
auto-load auto-load
@on-fetch="setLogTree" @on-fetch="setLogTree"
@ -508,7 +507,7 @@ watch(
:title=" :title="
date.formatDate( date.formatDate(
log.creationDate, log.creationDate,
'DD/MM/YYYY hh:mm:ss', 'DD/MM/YYYY hh:mm:ss'
) ?? `date:'dd/MM/yyyy HH:mm:ss'` ) ?? `date:'dd/MM/yyyy HH:mm:ss'`
" "
> >
@ -578,7 +577,7 @@ watch(
t( t(
`actions.${ `actions.${
actionsText[log.action] actionsText[log.action]
}`, }`
) )
" "
/> />
@ -678,8 +677,7 @@ watch(
</div> </div>
</template> </template>
</VnPaginate> </VnPaginate>
<RightMenu> <Teleport to="#right-panel" v-if="stateStore.isHeaderMounted()">
<template #right-panel>
<QList dense> <QList dense>
<QSeparator /> <QSeparator />
<QItem class="q-mt-sm"> <QItem class="q-mt-sm">
@ -734,17 +732,14 @@ watch(
v-model="userSelect" v-model="userSelect"
option-label="name" option-label="name"
option-value="id" option-value="id"
:url="`${model}Logs/${route.params.id}/editors`" :url="`${model}Logs/${$route.params.id}/editors`"
:fields="['id', 'nickname', 'name', 'image']" :fields="['id', 'nickname', 'name', 'image']"
sort-by="nickname" sort-by="nickname"
@update:model-value="selectFilter('userSelect')" @update:model-value="selectFilter('userSelect')"
hide-selected hide-selected
> >
<template #option="{ opt, itemProps }"> <template #option="{ opt, itemProps }">
<QItem <QItem v-bind="itemProps" class="q-pa-xs row items-center">
v-bind="itemProps"
class="q-pa-xs row items-center"
>
<QItemSection class="col-3 items-center"> <QItemSection class="col-3 items-center">
<VnAvatar :worker-id="opt.id" /> <VnAvatar :worker-id="opt.id" />
</QItemSection> </QItemSection>
@ -804,7 +799,7 @@ watch(
<QItem class="q-mt-sm"> <QItem class="q-mt-sm">
<QInput <QInput
class="full-width" class="full-width"
:label="t('globals.to')" :label="t('to')"
@click="dateToDialog = true" @click="dateToDialog = true"
@focus="(evt) => evt.target.blur()" @focus="(evt) => evt.target.blur()"
@clear="selectFilter('date', 'from')" @clear="selectFilter('date', 'from')"
@ -814,8 +809,7 @@ watch(
/> />
</QItem> </QItem>
</QList> </QList>
</template> </Teleport>
</RightMenu>
<QDialog v-model="dateFromDialog"> <QDialog v-model="dateFromDialog">
<QDate <QDate
:years-in-month-view="false" :years-in-month-view="false"
@ -1059,9 +1053,9 @@ en:
Deletes: Deletes Deletes: Deletes
Accesses: Accesses Accesses: Accesses
Users: Users:
User: User User: Usuario
All: All All: Todo
System: System System: Sistema
properties: properties:
id: ID id: ID
claimFk: Claim ID claimFk: Claim ID

View File

@ -1,10 +1,10 @@
<script setup> <script setup>
import RightAdvancedMenu from './RightAdvancedMenu.vue'; import RightMenu from './RightMenu.vue';
import VnSearchbar from 'components/ui/VnSearchbar.vue'; import VnSearchbar from 'components/ui/VnSearchbar.vue';
import VnTableFilter from '../VnTable/VnTableFilter.vue'; import VnTableFilter from '../VnTable/VnTableFilter.vue';
import { onBeforeMount, onMounted, onUnmounted, computed, ref } from 'vue'; import { onBeforeMount, computed, ref } from 'vue';
import { useArrayData } from 'src/composables/useArrayData'; import { useArrayData } from 'src/composables/useArrayData';
import { useRoute, useRouter } from 'vue-router'; import { useRoute } from 'vue-router';
import { useHasContent } from 'src/composables/useHasContent'; import { useHasContent } from 'src/composables/useHasContent';
const $props = defineProps({ const $props = defineProps({
@ -47,14 +47,16 @@ const $props = defineProps({
}); });
const route = useRoute(); const route = useRoute();
const router = useRouter();
let arrayData; let arrayData;
const sectionValue = computed(() => $props.section ?? $props.dataKey); const sectionValue = computed(() => $props.section ?? $props.dataKey);
const isMainSection = ref(false); const isMainSection = computed(() => {
const isSame = sectionValue.value == route.name;
if (!isSame && arrayData) {
arrayData.reset(['userParams', 'userFilter']);
}
return isSame;
});
const searchbarId = 'section-searchbar'; const searchbarId = 'section-searchbar';
const advancedMenuSlot = 'advanced-menu';
const hasContent = useHasContent(`#${searchbarId}`); const hasContent = useHasContent(`#${searchbarId}`);
onBeforeMount(() => { onBeforeMount(() => {
@ -65,27 +67,7 @@ onBeforeMount(() => {
...$props.arrayDataProps, ...$props.arrayDataProps,
navigate: $props.redirect, navigate: $props.redirect,
}); });
checkIsMain();
}); });
onMounted(() => {
const unsubscribe = router.afterEach(() => {
checkIsMain();
});
onUnmounted(unsubscribe);
});
onUnmounted(() => {
if (arrayData) arrayData.destroy();
});
function checkIsMain() {
isMainSection.value = sectionValue.value == route.name;
if (!isMainSection.value && arrayData) {
arrayData.reset(['userParams', 'filter']);
arrayData.setCurrentFilter();
}
}
</script> </script>
<template> <template>
<slot name="searchbar"> <slot name="searchbar">
@ -98,25 +80,18 @@ function checkIsMain() {
/> />
<div :id="searchbarId"></div> <div :id="searchbarId"></div>
</slot> </slot>
<RightAdvancedMenu :is-main-section="isMainSection"> <RightMenu>
<template #advanced-menu v-if="$slots[advancedMenuSlot] || rightFilter"> <template #right-panel v-if="$slots['rightMenu'] || rightFilter">
<slot :name="advancedMenuSlot"> <slot name="rightMenu">
<VnTableFilter <VnTableFilter
v-if="rightFilter && columns" v-if="rightFilter && columns"
:data-key="dataKey" :data-key="dataKey"
:array-data="arrayData" :array-data="arrayData"
:columns="columns" :columns="columns"
>
<template #moreFilterPanel="{ params, orders, searchFn }">
<slot
name="moreFilterPanel"
v-bind="{ params, orders, searchFn }"
/> />
</template>
</VnTableFilter>
</slot> </slot>
</template> </template>
</RightAdvancedMenu> </RightMenu>
<slot name="body" v-if="isMainSection" /> <slot name="body" v-if="isMainSection" />
<RouterView v-else /> <RouterView v-else />
</template> </template>

View File

@ -27,7 +27,7 @@ const $props = defineProps({
default: () => [], default: () => [],
}, },
optionLabel: { optionLabel: {
type: [String, Function], type: [String],
default: 'name', default: 'name',
}, },
optionValue: { optionValue: {
@ -171,8 +171,7 @@ onMounted(() => {
}); });
const arrayDataKey = const arrayDataKey =
$props.dataKey ?? $props.dataKey ?? ($props.url?.length > 0 ? $props.url : $attrs.name ?? $attrs.label);
($props.url?.length > 0 ? $props.url : ($attrs.name ?? $attrs.label));
const arrayData = useArrayData(arrayDataKey, { const arrayData = useArrayData(arrayDataKey, {
url: $props.url, url: $props.url,
@ -221,7 +220,7 @@ async function fetchFilter(val) {
optionFilterValue.value ?? optionFilterValue.value ??
(new RegExp(/\d/g).test(val) (new RegExp(/\d/g).test(val)
? optionValue.value ? optionValue.value
: (optionFilter.value ?? optionLabel.value)); : optionFilter.value ?? optionLabel.value);
let defaultWhere = {}; let defaultWhere = {};
if ($props.filterOptions.length) { if ($props.filterOptions.length) {
@ -233,15 +232,12 @@ async function fetchFilter(val) {
} else defaultWhere = { [key]: getVal(val) }; } else defaultWhere = { [key]: getVal(val) };
const where = { ...(val ? defaultWhere : {}), ...$props.where }; const where = { ...(val ? defaultWhere : {}), ...$props.where };
$props.exprBuilder && Object.assign(where, $props.exprBuilder(key, val)); $props.exprBuilder && Object.assign(where, $props.exprBuilder(key, val));
const filterOptions = { where, include, limit }; const fetchOptions = { where, include, limit };
if (fields) filterOptions.fields = fields; if (fields) fetchOptions.fields = fields;
if (sortBy) filterOptions.order = sortBy; if (sortBy) fetchOptions.order = sortBy;
arrayData.resetPagination(); arrayData.resetPagination();
const { data } = await arrayData.applyFilter( const { data } = await arrayData.applyFilter({ filter: fetchOptions });
{ filter: filterOptions },
{ updateRouter: false },
);
setOptions(data); setOptions(data);
return data; return data;
} }
@ -273,7 +269,7 @@ async function filterHandler(val, update) {
ref.setOptionIndex(-1); ref.setOptionIndex(-1);
ref.moveOptionSelection(1, true); ref.moveOptionSelection(1, true);
} }
}, }
); );
} }
@ -298,7 +294,7 @@ async function onScroll({ to, direction, from, index }) {
} }
} }
defineExpose({ opts: myOptions, vnSelectRef }); defineExpose({ opts: myOptions });
function handleKeyDown(event) { function handleKeyDown(event) {
if (event.key === 'Tab' && !event.shiftKey) { if (event.key === 'Tab' && !event.shiftKey) {
@ -309,7 +305,7 @@ function handleKeyDown(event) {
if (inputValue) { if (inputValue) {
const matchingOption = myOptions.value.find( const matchingOption = myOptions.value.find(
(option) => (option) =>
option[optionLabel.value].toLowerCase() === inputValue.toLowerCase(), option[optionLabel.value].toLowerCase() === inputValue.toLowerCase()
); );
if (matchingOption) { if (matchingOption) {
@ -321,11 +317,11 @@ function handleKeyDown(event) {
} }
const focusableElements = document.querySelectorAll( const focusableElements = document.querySelectorAll(
'a:not([disabled]), button:not([disabled]), input:not([disabled]), textarea:not([disabled]), select:not([disabled]), details:not([disabled]), [tabindex]:not([tabindex="-1"]):not([disabled])', 'a:not([disabled]), button:not([disabled]), input:not([disabled]), textarea:not([disabled]), select:not([disabled]), details:not([disabled]), [tabindex]:not([tabindex="-1"]):not([disabled])'
); );
const currentIndex = Array.prototype.indexOf.call( const currentIndex = Array.prototype.indexOf.call(
focusableElements, focusableElements,
event.target, event.target
); );
if (currentIndex >= 0 && currentIndex < focusableElements.length - 1) { if (currentIndex >= 0 && currentIndex < focusableElements.length - 1) {
focusableElements[currentIndex + 1].focus(); focusableElements[currentIndex + 1].focus();

View File

@ -1,5 +1,5 @@
<script setup> <script setup>
import { ref, computed } from 'vue'; import { computed } from 'vue';
import { useRole } from 'src/composables/useRole'; import { useRole } from 'src/composables/useRole';
import { useAcl } from 'src/composables/useAcl'; import { useAcl } from 'src/composables/useAcl';
@ -7,7 +7,6 @@ import VnSelect from 'src/components/common/VnSelect.vue';
const emit = defineEmits(['update:modelValue']); const emit = defineEmits(['update:modelValue']);
const value = defineModel({ type: [String, Number, Object] }); const value = defineModel({ type: [String, Number, Object] });
const select = ref(null);
const $props = defineProps({ const $props = defineProps({
rolesAllowedToCreate: { rolesAllowedToCreate: {
type: Array, type: Array,
@ -34,13 +33,10 @@ const isAllowedToCreate = computed(() => {
if ($props.acls.length) return acl.hasAny($props.acls); if ($props.acls.length) return acl.hasAny($props.acls);
return role.hasAny($props.rolesAllowedToCreate); return role.hasAny($props.rolesAllowedToCreate);
}); });
defineExpose({ vnSelectDialogRef: select });
</script> </script>
<template> <template>
<VnSelect <VnSelect
ref="select"
v-model="value" v-model="value"
v-bind="$attrs" v-bind="$attrs"
@update:model-value="(...args) => emit('update:modelValue', ...args)" @update:model-value="(...args) => emit('update:modelValue', ...args)"

View File

@ -1,34 +0,0 @@
<script setup>
import VnSelect from 'components/common/VnSelect.vue';
const model = defineModel({ type: [String, Number, Object] });
</script>
<template>
<VnSelect
:label="$t('globals.supplier')"
v-bind="$attrs"
v-model="model"
url="Suppliers"
option-value="id"
option-label="nickname"
:fields="['id', 'name', 'nickname', 'nif']"
:filter-options="['id', 'name', 'nickname', 'nif']"
sort-by="name ASC"
>
<template #option="scope">
<QItem v-bind="scope.itemProps">
<QItemSection>
<QItemLabel>
{{ scope.opt?.name }}
</QItemLabel>
<QItemLabel caption>
{{
`#${scope.opt?.id} , ${scope.opt?.nickname} (${scope.opt?.nif})`
}}
</QItemLabel>
</QItemSection>
</QItem>
</template>
</VnSelect>
</template>

View File

@ -9,9 +9,9 @@ const $props = defineProps({
type: Boolean, type: Boolean,
default: false, default: false,
}, },
info: { hasInfo: {
type: String, type: Boolean,
default: undefined, default: false,
}, },
modelValue: { modelValue: {
type: [String, Number, Object], type: [String, Number, Object],
@ -53,14 +53,13 @@ const url = computed(() => {
:fields="['id', 'name', 'nickname', 'code']" :fields="['id', 'name', 'nickname', 'code']"
:filter-options="['id', 'name', 'nickname', 'code']" :filter-options="['id', 'name', 'nickname', 'code']"
sort-by="nickname ASC" sort-by="nickname ASC"
data-cy="vnWorkerSelect"
> >
<template #prepend v-if="$props.hasAvatar"> <template #prepend v-if="$props.hasAvatar">
<VnAvatar :worker-id="value" color="primary" v-bind="$attrs" /> <VnAvatar :worker-id="value" color="primary" :title="title" />
</template> </template>
<template #append v-if="$props.info"> <template #append v-if="$props.hasInfo">
<QIcon name="info" class="cursor-pointer"> <QIcon name="info" class="cursor-pointer">
<QTooltip>{{ $t($props.info) }}</QTooltip> <QTooltip>{{ $t($props.hasInfo) }}</QTooltip>
</QIcon> </QIcon>
</template> </template>
<template #option="scope"> <template #option="scope">
@ -73,8 +72,7 @@ const url = computed(() => {
{{ scope.opt.nickname }} {{ scope.opt.nickname }}
</QItemLabel> </QItemLabel>
<QItemLabel caption v-else> <QItemLabel caption v-else>
#{{ scope.opt.id }}, {{ scope.opt.nickname }}, #{{ scope.opt.id }}, {{ scope.opt.nickname }}, {{ scope.opt.code }}
{{ scope.opt.code }}
</QItemLabel> </QItemLabel>
</QItemSection> </QItemSection>
</QItem> </QItem>

View File

@ -10,10 +10,6 @@ defineProps({
type: Object, type: Object,
required: true, required: true,
}, },
width: {
type: String,
default: 'md-width',
},
}); });
defineEmits([...useDialogPluginComponent.emits]); defineEmits([...useDialogPluginComponent.emits]);
@ -21,19 +17,7 @@ defineEmits([...useDialogPluginComponent.emits]);
const { dialogRef, onDialogHide } = useDialogPluginComponent(); const { dialogRef, onDialogHide } = useDialogPluginComponent();
</script> </script>
<template> <template>
<QDialog ref="dialogRef" @hide="onDialogHide"> <QDialog ref="dialogRef" @hide="onDialogHide" full-width>
<component :is="summary" :id="id" :class="width" /> <component :is="summary" :id="id" />
</QDialog> </QDialog>
</template> </template>
<style lang="scss" scoped>
.md-width {
max-width: $width-md;
}
.lg-width {
max-width: $width-lg;
}
.xlg-width {
max-width: $width-xl;
}
</style>

View File

@ -1,146 +0,0 @@
import { createWrapper, axios } from 'app/test/vitest/helper';
import { vi, afterEach, beforeEach, beforeAll, describe, expect, it } from 'vitest';
import VnDms from 'src/components/common/VnDms.vue';
class MockFormData {
constructor() {
this.entries = {};
}
append(key, value) {
if (!key) {
throw new Error('Key is required for FormData.append');
}
this.entries[key] = value;
}
get(key) {
return this.entries[key] || null;
}
getAll() {
return this.entries;
}
}
global.FormData = MockFormData;
describe('VnDms', () => {
let wrapper;
let vm;
let postMock;
const postResponseMock = { data: { success: true } };
const data = {
hasFile: true,
hasFileAttached: true,
reference: 'DMS-test',
warehouseFk: 1,
companyFk: 2,
dmsTypeFk: 3,
description: 'This is a test description',
files: { name: 'example.txt', content: new Blob(['file content'], { type: 'text/plain' })},
};
const expectedBody = {
hasFile: true,
hasFileAttached: true,
reference: 'DMS-test',
warehouseId: 1,
companyId: 2,
dmsTypeId: 3,
description: 'This is a test description',
};
beforeAll(() => {
wrapper = createWrapper(VnDms, {
propsData: {
url: '/test',
formInitialData: { id: 1, reference: 'test' },
model: 'Worker',
}
});
wrapper = wrapper.wrapper;
vm = wrapper.vm;
vi.spyOn(vm, '$emit');
});
beforeEach(() => {
postMock = vi.spyOn(axios, 'post').mockResolvedValue(postResponseMock);
vm.dms = data;
});
afterEach(() => {
vi.clearAllMocks();
});
describe('mapperDms', () => {
it('should map DMS data correctly and add file to FormData', () => {
const [formData, params] = vm.mapperDms(data);
expect(formData.get('example.txt')).toBe(data.files);
expect(expectedBody).toEqual(params.params);
});
it('should map DMS data correctly without file', () => {
delete data.files;
const [formData, params] = vm.mapperDms(data);
expect(formData.getAll()).toEqual({});
expect(expectedBody).toEqual(params.params);
});
});
describe('getUrl', () => {
it('should returns prop url when is set', async () => {
expect(vm.getUrl()).toBe('/test');
});
it('should returns url dms/"props.formInitialData.id"/updateFile when prop url is null', async () => {
await wrapper.setProps({ url: null });
expect(vm.getUrl()).toBe('dms/1/updateFile');
});
it('should returns url "props.model"/"route.params.id"/uploadFile when formInitialData is null', async () => {
await wrapper.setProps({ formInitialData: null });
vm.route.params.id = '123';
expect(vm.getUrl()).toBe('Worker/123/uploadFile');
});
});
describe('save', () => {
it('should save data correctly', async () => {
await vm.save();
expect(postMock).toHaveBeenCalledWith(vm.getUrl(), expect.any(FormData), { params: expectedBody });
expect(wrapper.emitted('onDataSaved')).toBeTruthy();
});
});
describe('defaultData', () => {
it('should set dms with formInitialData', async () => {
const testData = {
hasFile: false,
hasFileAttached: false,
reference: 'defaultData-test',
warehouseFk: 2,
companyFk: 3,
dmsTypeFk: 2,
description: 'This is a test description'
}
await wrapper.setProps({ formInitialData: testData });
vm.defaultData();
expect(vm.dms).toEqual(testData);
});
it('should add reference with "route.params.id" to dms if formInitialData is null', async () => {
await wrapper.setProps({ formInitialData: null });
vm.route.params.id= '111';
vm.defaultData();
expect(vm.dms.reference).toBe('111');
});
});
});

View File

@ -1,91 +0,0 @@
import { createWrapper } from 'app/test/vitest/helper';
import { vi, describe, expect, it } from 'vitest';
import VnInput from 'src/components/common/VnInput.vue';
describe('VnInput', () => {
let vm;
let wrapper;
let input;
function generateWrapper(value, isOutlined, emptyToNull, insertable) {
wrapper = createWrapper(VnInput, {
props: {
modelValue: value,
isOutlined, emptyToNull, insertable,
maxlength: 101
},
attrs: {
label: 'test',
required: true,
maxlength: 101,
maxLength: 10,
'max-length':20
},
});
wrapper = wrapper.wrapper;
vm = wrapper.vm;
input = wrapper.find('[data-cy="test_input"]');
};
describe('value', () => {
it('should emit update:modelValue when value changes', async () => {
generateWrapper('12345', false, false, true)
await input.setValue('123');
expect(wrapper.emitted('update:modelValue')).toBeTruthy();
expect(wrapper.emitted('update:modelValue')[0]).toEqual(['123']);
});
it('should emit update:modelValue with null when input is empty', async () => {
generateWrapper('12345', false, true, true);
await input.setValue('');
expect(wrapper.emitted('update:modelValue')[0]).toEqual([null]);
});
});
describe('styleAttrs', () => {
it('should return empty styleAttrs when isOutlined is false', async () => {
generateWrapper('123', false, false, false);
expect(vm.styleAttrs).toEqual({});
});
it('should set styleAttrs when isOutlined is true', async () => {
generateWrapper('123', true, false, false);
expect(vm.styleAttrs.outlined).toBe(true);
});
});
describe('handleKeydown', () => {
it('should do nothing when "Backspace" key is pressed', async () => {
generateWrapper('12345', false, false, true);
await input.trigger('keydown', { key: 'Backspace' });
expect(wrapper.emitted('update:modelValue')).toBeUndefined();
const spyhandler = vi.spyOn(vm, 'handleInsertMode');
expect(spyhandler).not.toHaveBeenCalled();
});
/*
TODO: #8399 REDMINE
*/
it.skip('handleKeydown respects insertable behavior', async () => {
const expectedValue = '12345';
generateWrapper('1234', false, false, true);
vm.focus()
await input.trigger('keydown', { key: '5' });
await vm.$nextTick();
expect(wrapper.emitted('update:modelValue')).toBeTruthy();
expect(wrapper.emitted('update:modelValue')[0]).toEqual([expectedValue ]);
expect(vm.value).toBe( expectedValue);
});
});
describe('focus', () => {
it('should call focus method when input is focused', async () => {
generateWrapper('123', false, false, true);
const focusSpy = vi.spyOn(input.element, 'focus');
vm.focus();
expect(focusSpy).toHaveBeenCalled();
});
});
});

View File

@ -1,78 +1,51 @@
import { import { describe, it, expect, vi, beforeAll, afterEach, beforeEach } from 'vitest';
describe,
it,
expect,
vi,
beforeAll,
afterEach,
beforeEach,
afterAll,
} from 'vitest';
import { createWrapper, axios } from 'app/test/vitest/helper'; import { createWrapper, axios } from 'app/test/vitest/helper';
import VnNotes from 'src/components/ui/VnNotes.vue'; import VnNotes from 'src/components/ui/VnNotes.vue';
import vnDate from 'src/boot/vnDate';
describe('VnNotes', () => { describe('VnNotes', () => {
let vm; let vm;
let wrapper; let wrapper;
let spyFetch; let spyFetch;
let postMock; let postMock;
let patchMock; let expectedBody;
let expectedInsertBody; const mockData= {name: 'Tony', lastName: 'Stark', text: 'Test Note', observationTypeFk: 1};
let expectedUpdateBody;
const defaultOptions = { function generateExpectedBody() {
expectedBody = {...vm.$props.body, ...{ text: vm.newNote.text, observationTypeFk: vm.newNote.observationTypeFk }};
}
async function setTestParams(text, observationType, type){
vm.newNote.text = text;
vm.newNote.observationTypeFk = observationType;
wrapper.setProps({ selectType: type });
}
beforeAll(async () => {
vi.spyOn(axios, 'get').mockReturnValue({ data: [] });
wrapper = createWrapper(VnNotes, {
propsData: {
url: '/test', url: '/test',
body: { name: 'Tony', lastName: 'Stark' }, body: { name: 'Tony', lastName: 'Stark' },
selectType: false, }
saveUrl: null,
justInput: false,
};
function generateWrapper(
options = defaultOptions,
text = null,
observationType = null,
) {
vi.spyOn(axios, 'get').mockResolvedValue({ data: [] });
wrapper = createWrapper(VnNotes, {
propsData: options,
}); });
wrapper = wrapper.wrapper; wrapper = wrapper.wrapper;
vm = wrapper.vm; vm = wrapper.vm;
vm.newNote.text = text; });
vm.newNote.observationTypeFk = observationType;
}
function createSpyFetch() {
spyFetch = vi.spyOn(vm.$refs.vnPaginateRef, 'fetch');
}
function generateExpectedBody() {
expectedInsertBody = {
...vm.$props.body,
...{ text: vm.newNote.text, observationTypeFk: vm.newNote.observationTypeFk },
};
expectedUpdateBody = { ...vm.$props.body, ...{ notes: vm.newNote.text } };
}
beforeEach(() => { beforeEach(() => {
postMock = vi.spyOn(axios, 'post'); postMock = vi.spyOn(axios, 'post').mockResolvedValue(mockData);
patchMock = vi.spyOn(axios, 'patch'); spyFetch = vi.spyOn(vm.vnPaginateRef, 'fetch').mockImplementation(() => vi.fn());
}); });
afterEach(() => { afterEach(() => {
vi.clearAllMocks(); vi.clearAllMocks();
expectedInsertBody = {}; expectedBody = {};
expectedUpdateBody = {};
});
afterAll(() => {
vi.restoreAllMocks();
}); });
describe('insert', () => { describe('insert', () => {
it('should not call axios.post and vnPaginateRef.fetch when newNote.text is null', async () => { it('should not call axios.post and vnPaginateRef.fetch if newNote.text is null', async () => {
generateWrapper({ selectType: true }); await setTestParams( null, null, true );
createSpyFetch();
await vm.insert(); await vm.insert();
@ -80,9 +53,8 @@ describe('VnNotes', () => {
expect(spyFetch).not.toHaveBeenCalled(); expect(spyFetch).not.toHaveBeenCalled();
}); });
it('should not call axios.post and vnPaginateRef.fetch when newNote.text is empty', async () => { it('should not call axios.post and vnPaginateRef.fetch if newNote.text is empty', async () => {
generateWrapper(null, ''); await setTestParams( "", null, false );
createSpyFetch();
await vm.insert(); await vm.insert();
@ -90,9 +62,8 @@ describe('VnNotes', () => {
expect(spyFetch).not.toHaveBeenCalled(); expect(spyFetch).not.toHaveBeenCalled();
}); });
it('should not call axios.post and vnPaginateRef.fetch when observationTypeFk is null and selectType is true', async () => { it('should not call axios.post and vnPaginateRef.fetch if observationTypeFk is missing and selectType is true', async () => {
generateWrapper({ selectType: true }, 'Test Note'); await setTestParams( "Test Note", null, true );
createSpyFetch();
await vm.insert(); await vm.insert();
@ -100,57 +71,37 @@ describe('VnNotes', () => {
expect(spyFetch).not.toHaveBeenCalled(); expect(spyFetch).not.toHaveBeenCalled();
}); });
it('should call axios.post and vnPaginateRef.fetch when observationTypeFk is missing and selectType is false', async () => { it('should call axios.post and vnPaginateRef.fetch if observationTypeFk is missing and selectType is false', async () => {
generateWrapper(null, 'Test Note'); await setTestParams( "Test Note", null, false );
createSpyFetch();
generateExpectedBody(); generateExpectedBody();
await vm.insert(); await vm.insert();
expect(postMock).toHaveBeenCalledWith(vm.$props.url, expectedInsertBody); expect(postMock).toHaveBeenCalledWith(vm.$props.url, expectedBody);
expect(spyFetch).toHaveBeenCalled();
});
it('should call axios.post and vnPaginateRef.fetch if observationTypeFk is setted and selectType is false', async () => {
await setTestParams( "Test Note", 1, false );
generateExpectedBody();
await vm.insert();
expect(postMock).toHaveBeenCalledWith(vm.$props.url, expectedBody);
expect(spyFetch).toHaveBeenCalled(); expect(spyFetch).toHaveBeenCalled();
}); });
it('should call axios.post and vnPaginateRef.fetch when newNote is valid', async () => { it('should call axios.post and vnPaginateRef.fetch when newNote is valid', async () => {
generateWrapper({ selectType: true }, 'Test Note', 1); await setTestParams( "Test Note", 1, true );
createSpyFetch();
generateExpectedBody(); generateExpectedBody();
await vm.insert(); await vm.insert();
expect(postMock).toHaveBeenCalledWith(vm.$props.url, expectedInsertBody); expect(postMock).toHaveBeenCalledWith(vm.$props.url, expectedBody);
expect(spyFetch).toHaveBeenCalled(); expect(spyFetch).toHaveBeenCalled();
}); });
}); });
describe('update', () => {
it('should call axios.patch with saveUrl when saveUrl is set and justInput is true', async () => {
generateWrapper({
url: '/business',
justInput: true,
saveUrl: '/saveUrlTest',
});
generateExpectedBody();
await vm.update();
expect(patchMock).toHaveBeenCalledWith(vm.$props.saveUrl, expectedUpdateBody);
});
it('should call axios.patch with url when saveUrl is not set and justInput is true', async () => {
generateWrapper({
url: '/business',
body: { workerFk: 1110 },
justInput: true,
});
generateExpectedBody();
await vm.update();
expect(patchMock).toHaveBeenCalledWith(
`${vm.$props.url}/${vm.$props.body.workerFk}`,
expectedUpdateBody,
);
});
});
}); });

View File

@ -37,10 +37,6 @@ const $props = defineProps({
type: Object, type: Object,
default: null, default: null,
}, },
width: {
type: String,
default: 'md-width',
},
}); });
const state = useState(); const state = useState();
@ -59,11 +55,10 @@ onBeforeMount(async () => {
url: $props.url, url: $props.url,
filter: $props.filter, filter: $props.filter,
skip: 0, skip: 0,
oneRecord: true,
}); });
store = arrayData.store; store = arrayData.store;
entity = computed(() => { entity = computed(() => {
const data = store.data ?? {}; const data = (Array.isArray(store.data) ? store.data[0] : store.data) ?? {};
if (data) emit('onFetch', data); if (data) emit('onFetch', data);
return data; return data;
}); });
@ -74,7 +69,7 @@ onBeforeMount(async () => {
() => [$props.url, $props.filter], () => [$props.url, $props.filter],
async () => { async () => {
if (!isSameDataKey.value) await getData(); if (!isSameDataKey.value) await getData();
}, }
); );
}); });
@ -85,7 +80,7 @@ async function getData() {
try { try {
const { data } = await arrayData.fetch({ append: false, updateRouter: false }); const { data } = await arrayData.fetch({ append: false, updateRouter: false });
state.set($props.dataKey, data); state.set($props.dataKey, data);
emit('onFetch', data); emit('onFetch', Array.isArray(data) ? data[0] : data);
} finally { } finally {
isLoading.value = false; isLoading.value = false;
} }
@ -109,7 +104,7 @@ const iconModule = computed(() => route.matched[1].meta.icon);
const toModule = computed(() => const toModule = computed(() =>
route.matched[1].path.split('/').length > 2 route.matched[1].path.split('/').length > 2
? route.matched[1].redirect ? route.matched[1].redirect
: route.matched[1].children[0].redirect, : route.matched[1].children[0].redirect
); );
</script> </script>
@ -133,8 +128,9 @@ const toModule = computed(() =>
</QTooltip> </QTooltip>
</QBtn></slot </QBtn></slot
> >
<QBtn <QBtn
@click.stop="viewSummary(entity.id, $props.summary, $props.width)" @click.stop="viewSummary(entity.id, $props.summary)"
round round
flat flat
dense dense

View File

@ -15,10 +15,6 @@ const props = defineProps({
type: Object, type: Object,
default: null, default: null,
}, },
userFilter: {
type: Object,
default: null,
},
entityId: { entityId: {
type: [Number, String], type: [Number, String],
default: null, default: null,
@ -38,12 +34,10 @@ const isSummary = ref();
const arrayData = useArrayData(props.dataKey, { const arrayData = useArrayData(props.dataKey, {
url: props.url, url: props.url,
filter: props.filter, filter: props.filter,
userFilter: props.userFilter,
skip: 0, skip: 0,
oneRecord: true,
}); });
const { store } = arrayData; const { store } = arrayData;
const entity = computed(() => store.data); const entity = computed(() => (Array.isArray(store.data) ? store.data[0] : store.data));
const isLoading = ref(false); const isLoading = ref(false);
defineExpose({ defineExpose({
@ -62,7 +56,7 @@ async function fetch() {
store.filter = props.filter ?? {}; store.filter = props.filter ?? {};
isLoading.value = true; isLoading.value = true;
const { data } = await arrayData.fetch({ append: false, updateRouter: false }); const { data } = await arrayData.fetch({ append: false, updateRouter: false });
emit('onFetch', data); emit('onFetch', Array.isArray(data) ? data[0] : data);
isLoading.value = false; isLoading.value = false;
} }
</script> </script>
@ -181,7 +175,7 @@ async function fetch() {
display: inline-block; display: inline-block;
} }
.header.link:hover { .header.link:hover {
color: rgba(var(--q-primary), 0.8); color: lighten($primary, 20%);
} }
.q-checkbox { .q-checkbox {
& .q-checkbox__label { & .q-checkbox__label {
@ -209,13 +203,4 @@ async function fetch() {
.summaryHeader { .summaryHeader {
color: $white; color: $white;
} }
.cardSummary :deep(.q-card__section[content]) {
display: flex;
flex-wrap: wrap;
padding: 0;
> * {
flex: 1;
}
}
</style> </style>

View File

@ -41,7 +41,7 @@ const card = toRef(props, 'item');
</div> </div>
</div> </div>
<div class="content"> <div class="content">
<span class="link" @click.stop> <span class="link">
{{ card.name }} {{ card.name }}
<ItemDescriptorProxy :id="card.id" /> <ItemDescriptorProxy :id="card.id" />
</span> </span>

View File

@ -1,7 +1,7 @@
<script setup> <script setup>
import { computed } from 'vue'; import { computed } from 'vue';
import { useQuasar } from 'quasar'; import { useQuasar } from 'quasar';
import '@quasar/quasar-ui-qcalendar/src/QCalendarVariables.scss'; import '@quasar/quasar-ui-qcalendar/src/QCalendarVariables.sass';
const $props = defineProps({ const $props = defineProps({
bordered: { bordered: {

View File

@ -1,42 +1,32 @@
<template> <template>
<div class="header bg-primary q-pa-sm q-mb-md"> <div class="header bg-primary q-pa-sm q-mb-md">
<QSkeleton type="rect" square /> <QSkeleton type="rect" square />
<QSkeleton type="rect" square />
</div> </div>
<div class="row q-pa-md q-col-gutter-md q-mb-md"> <div class="row q-pa-md q-col-gutter-md q-mb-md">
<div class="col">
<QSkeleton type="rect" class="q-mb-md" square /> <QSkeleton type="rect" class="q-mb-md" square />
<QSkeleton type="text" square /> <QSkeleton type="text" square />
<QSkeleton type="text" square /> <QSkeleton type="text" square />
<QSkeleton type="text" square /> <QSkeleton type="text" square />
<QSkeleton type="text" square /> <QSkeleton type="text" square />
<QSkeleton type="text" square /> <QSkeleton type="text" square />
</div>
<div class="col">
<QSkeleton type="rect" class="q-mb-md" square /> <QSkeleton type="rect" class="q-mb-md" square />
<QSkeleton type="text" square /> <QSkeleton type="text" square />
<QSkeleton type="text" square /> <QSkeleton type="text" square />
<QSkeleton type="text" square /> <QSkeleton type="text" square />
<QSkeleton type="text" square /> <QSkeleton type="text" square />
<QSkeleton type="text" square /> <QSkeleton type="text" square />
</div>
<div class="col">
<QSkeleton type="rect" class="q-mb-md" square /> <QSkeleton type="rect" class="q-mb-md" square />
<QSkeleton type="text" square /> <QSkeleton type="text" square />
<QSkeleton type="text" square /> <QSkeleton type="text" square />
<QSkeleton type="text" square /> <QSkeleton type="text" square />
<QSkeleton type="text" square /> <QSkeleton type="text" square />
<QSkeleton type="text" square /> <QSkeleton type="text" square />
</div>
<div class="col">
<QSkeleton type="rect" class="q-mb-md" square /> <QSkeleton type="rect" class="q-mb-md" square />
<QSkeleton type="text" square /> <QSkeleton type="text" square />
<QSkeleton type="text" square /> <QSkeleton type="text" square />
<QSkeleton type="text" square /> <QSkeleton type="text" square />
<QSkeleton type="text" square /> <QSkeleton type="text" square />
<QSkeleton type="text" square /> <QSkeleton type="text" square />
</div>
<div class="col">
<QSkeleton type="rect" class="q-mb-md" square /> <QSkeleton type="rect" class="q-mb-md" square />
<QSkeleton type="text" square /> <QSkeleton type="text" square />
<QSkeleton type="text" square /> <QSkeleton type="text" square />
@ -44,7 +34,6 @@
<QSkeleton type="text" square /> <QSkeleton type="text" square />
<QSkeleton type="text" square /> <QSkeleton type="text" square />
</div> </div>
</div>
</template> </template>
<style lang="scss" scoped> <style lang="scss" scoped>

View File

@ -114,7 +114,7 @@ async function clearFilters() {
arrayData.resetPagination(); arrayData.resetPagination();
// Filtrar los params no removibles // Filtrar los params no removibles
const removableFilters = Object.keys(userParams.value).filter((param) => const removableFilters = Object.keys(userParams.value).filter((param) =>
$props.unremovableParams.includes(param), $props.unremovableParams.includes(param)
); );
const newParams = {}; const newParams = {};
// Conservar solo los params que no son removibles // Conservar solo los params que no son removibles
@ -162,13 +162,13 @@ const formatTags = (tags) => {
const tags = computed(() => { const tags = computed(() => {
const filteredTags = tagsList.value.filter( const filteredTags = tagsList.value.filter(
(tag) => !($props.customTags || []).includes(tag.label), (tag) => !($props.customTags || []).includes(tag.label)
); );
return formatTags(filteredTags); return formatTags(filteredTags);
}); });
const customTags = computed(() => const customTags = computed(() =>
tagsList.value.filter((tag) => ($props.customTags || []).includes(tag.label)), tagsList.value.filter((tag) => ($props.customTags || []).includes(tag.label))
); );
async function remove(key) { async function remove(key) {
@ -188,15 +188,9 @@ function formatValue(value) {
const getLocale = (label) => { const getLocale = (label) => {
const param = label.split('.').at(-1); const param = label.split('.').at(-1);
const globalLocale = `globals.params.${param}`; const globalLocale = `globals.params.${param}`;
const moduleName = route.meta.moduleName;
const moduleLocale = `${moduleName.toLowerCase()}.${param}`;
if (te(globalLocale)) return t(globalLocale); if (te(globalLocale)) return t(globalLocale);
else if (te(moduleLocale)) return t(moduleLocale); else if (te(t(`params.${param}`)));
else { else return t(`${route.meta.moduleName.toLowerCase()}.params.${param}`);
const camelCaseModuleName =
moduleName.charAt(0).toLowerCase() + moduleName.slice(1);
return t(`${camelCaseModuleName}.params.${param}`);
}
}; };
</script> </script>

View File

@ -1,6 +1,6 @@
<script setup> <script setup>
import axios from 'axios'; import axios from 'axios';
import { ref, reactive, useAttrs, computed } from 'vue'; import { ref, reactive } from 'vue';
import { onBeforeRouteLeave } from 'vue-router'; import { onBeforeRouteLeave } from 'vue-router';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import { useQuasar } from 'quasar'; import { useQuasar } from 'quasar';
@ -16,22 +16,12 @@ import VnSelect from 'components/common/VnSelect.vue';
import FetchData from 'components/FetchData.vue'; import FetchData from 'components/FetchData.vue';
import VnInput from 'components/common/VnInput.vue'; import VnInput from 'components/common/VnInput.vue';
const emit = defineEmits(['onFetch']);
const $attrs = useAttrs();
const isRequired = computed(() => {
return Object.keys($attrs).includes('required')
});
const $props = defineProps({ const $props = defineProps({
url: { type: String, default: null }, url: { type: String, default: null },
saveUrl: {type: String, default: null},
filter: { type: Object, default: () => {} }, filter: { type: Object, default: () => {} },
body: { type: Object, default: () => {} }, body: { type: Object, default: () => {} },
addNote: { type: Boolean, default: false }, addNote: { type: Boolean, default: false },
selectType: { type: Boolean, default: false }, selectType: { type: Boolean, default: false },
justInput: { type: Boolean, default: false },
}); });
const { t } = useI18n(); const { t } = useI18n();
@ -39,13 +29,6 @@ const quasar = useQuasar();
const newNote = reactive({ text: null, observationTypeFk: null }); const newNote = reactive({ text: null, observationTypeFk: null });
const observationTypes = ref([]); const observationTypes = ref([]);
const vnPaginateRef = ref(); const vnPaginateRef = ref();
let originalText;
function handleClick(e) {
if (e.shiftKey && e.key === 'Enter') return;
if ($props.justInput) confirmAndUpdate();
else insert();
}
async function insert() { async function insert() {
if (!newNote.text || ($props.selectType && !newNote.observationTypeFk)) return; if (!newNote.text || ($props.selectType && !newNote.observationTypeFk)) return;
@ -58,36 +41,8 @@ async function insert() {
await axios.post($props.url, newBody); await axios.post($props.url, newBody);
await vnPaginateRef.value.fetch(); await vnPaginateRef.value.fetch();
} }
function confirmAndUpdate() {
if(!newNote.text && originalText)
quasar
.dialog({
component: VnConfirm,
componentProps: {
title: t('New note is empty'),
message: t('Are you sure remove this note?'),
},
})
.onOk(update)
.onCancel(() => {
newNote.text = originalText;
});
else update();
}
async function update() {
originalText = newNote.text;
const body = $props.body;
const newBody = {
...body,
...{ notes: newNote.text },
};
await axios.patch(`${$props.saveUrl ?? `${$props.url}/${$props.body.workerFk}`}`, newBody);
}
onBeforeRouteLeave((to, from, next) => { onBeforeRouteLeave((to, from, next) => {
if ((newNote.text && !$props.justInput) || (newNote.text !== originalText) && $props.justInput) if (newNote.text)
quasar.dialog({ quasar.dialog({
component: VnConfirm, component: VnConfirm,
componentProps: { componentProps: {
@ -98,13 +53,6 @@ onBeforeRouteLeave((to, from, next) => {
}); });
else next(); else next();
}); });
function fetchData([ data ]) {
newNote.text = data?.notes;
originalText = data?.notes;
emit('onFetch', data);
}
</script> </script>
<template> <template>
<FetchData <FetchData
@ -114,19 +62,8 @@ function fetchData([ data ]) {
auto-load auto-load
@on-fetch="(data) => (observationTypes = data)" @on-fetch="(data) => (observationTypes = data)"
/> />
<FetchData <QCard class="q-pa-xs q-mb-lg full-width" v-if="$props.addNote">
v-if="justInput" <QCardSection horizontal>
:url="url"
:filter="filter"
@on-fetch="fetchData"
auto-load
/>
<QCard
class="q-pa-xs q-mb-lg full-width"
:class="{ 'just-input': $props.justInput }"
v-if="$props.addNote || $props.justInput"
>
<QCardSection horizontal v-if="!$props.justInput">
{{ t('New note') }} {{ t('New note') }}
</QCardSection> </QCardSection>
<QCardSection class="q-px-xs q-my-none q-py-none"> <QCardSection class="q-px-xs q-my-none q-py-none">
@ -138,19 +75,19 @@ function fetchData([ data ]) {
v-model="newNote.observationTypeFk" v-model="newNote.observationTypeFk"
option-label="description" option-label="description"
style="flex: 0.15" style="flex: 0.15"
:required="isRequired" :required="true"
@keyup.enter.stop="insert" @keyup.enter.stop="insert"
/> />
<VnInput <VnInput
v-model.trim="newNote.text" v-model.trim="newNote.text"
type="textarea" type="textarea"
:label="$props.justInput && newNote.text ? '' : t('Add note here...')" :label="t('Add note here...')"
filled filled
size="lg" size="lg"
autogrow autogrow
@keyup.enter.stop="handleClick" @keyup.enter.stop="insert"
:required="isRequired"
clearable clearable
:required="true"
> >
<template #append> <template #append>
<QBtn <QBtn
@ -158,7 +95,7 @@ function fetchData([ data ]) {
icon="save" icon="save"
color="primary" color="primary"
flat flat
@click="handleClick" @click="insert"
class="q-mb-xs" class="q-mb-xs"
dense dense
data-cy="saveNote" data-cy="saveNote"
@ -169,7 +106,6 @@ function fetchData([ data ]) {
</QCardSection> </QCardSection>
</QCard> </QCard>
<VnPaginate <VnPaginate
v-if="!$props.justInput"
:data-key="$props.url" :data-key="$props.url"
:url="$props.url" :url="$props.url"
order="created DESC" order="created DESC"
@ -262,11 +198,6 @@ function fetchData([ data ]) {
} }
} }
} }
.just-input {
padding-right: 18px;
margin-bottom: 2px;
box-shadow: none;
}
</style> </style>
<i18n> <i18n>
es: es:
@ -274,6 +205,4 @@ function fetchData([ data ]) {
New note: Nueva nota New note: Nueva nota
Save (Enter): Guardar (Intro) Save (Enter): Guardar (Intro)
Observation type: Tipo de observación Observation type: Tipo de observación
New note is empty: La nueva nota esta vacia
Are you sure remove this note?: Estas seguro de quitar esta nota?
</i18n> </i18n>

View File

@ -78,10 +78,6 @@ const props = defineProps({
type: String, type: String,
default: '', default: '',
}, },
keyData: {
type: String,
default: undefined,
},
}); });
const emit = defineEmits(['onFetch', 'onPaginate', 'onChange']); const emit = defineEmits(['onFetch', 'onPaginate', 'onChange']);
@ -123,7 +119,7 @@ watch(
() => props.data, () => props.data,
() => { () => {
store.data = props.data; store.data = props.data;
}, }
); );
watch( watch(
@ -132,12 +128,12 @@ watch(
if (!mounted.value) return; if (!mounted.value) return;
emit('onChange', data); emit('onChange', data);
}, },
{ immediate: true }, { immediate: true }
); );
watch( watch(
() => [props.url, props.filter], () => [props.url, props.filter],
([url, filter]) => mounted.value && fetch({ url, filter }), ([url, filter]) => mounted.value && fetch({ url, filter })
); );
const addFilter = async (filter, params) => { const addFilter = async (filter, params) => {
await arrayData.addFilter({ filter, params }); await arrayData.addFilter({ filter, params });
@ -170,7 +166,7 @@ function emitStoreData() {
async function paginate() { async function paginate() {
const { page, rowsPerPage, sortBy, descending } = pagination.value; const { page, rowsPerPage, sortBy, descending } = pagination.value;
if (!arrayData.store.url) return; if (!props.url) return;
isLoading.value = true; isLoading.value = true;
await arrayData.loadMore(); await arrayData.loadMore();
@ -198,7 +194,7 @@ function endPagination() {
async function onLoad(index, done) { async function onLoad(index, done) {
if (!store.data || !mounted.value) return done(); if (!store.data || !mounted.value) return done();
if (store.data.length === 0 || !arrayData.store.url) return done(false); if (store.data.length === 0 || !props.url) return done(false);
pagination.value.page = pagination.value.page + 1; pagination.value.page = pagination.value.page + 1;
@ -259,7 +255,7 @@ defineExpose({
:disable="disableInfiniteScroll || !store.hasMoreData" :disable="disableInfiniteScroll || !store.hasMoreData"
v-bind="$attrs" v-bind="$attrs"
> >
<slot name="body" :rows="keyData ? store.data[keyData] : store.data"></slot> <slot name="body" :rows="store.data"></slot>
<div v-if="isLoading" class="spinner info-row q-pa-md text-center"> <div v-if="isLoading" class="spinner info-row q-pa-md text-center">
<QSpinner color="primary" size="md" /> <QSpinner color="primary" size="md" />
</div> </div>

View File

@ -102,7 +102,7 @@ watch(
(val) => { (val) => {
arrayData = useArrayData(val, { ...props }); arrayData = useArrayData(val, { ...props });
store = arrayData.store; store = arrayData.store;
}, }
); );
onMounted(() => { onMounted(() => {
@ -113,20 +113,23 @@ onMounted(() => {
}); });
async function search() { async function search() {
const staticParams = Object.keys(store.userParams ?? {}).length
? store.userParams
: store.defaultParams;
arrayData.resetPagination(); arrayData.resetPagination();
let filter = { params: { search: searchText.value } }; const filter = {
if (!props.searchRemoveParams || !searchText.value) {
filter = {
params: { params: {
...store.userParams,
search: searchText.value, search: searchText.value,
}, },
filter: store.filter, filter: props.filter,
};
if (!props.searchRemoveParams || !searchText.value) {
filter.params = {
...staticParams,
search: searchText.value,
}; };
} else {
arrayData.reset(['currentFilter', 'userParams']);
} }
if (props.whereFilter) { if (props.whereFilter) {
@ -176,7 +179,6 @@ async function search() {
> >
<QTooltip>{{ t(props.info) }}</QTooltip> <QTooltip>{{ t(props.info) }}</QTooltip>
</QIcon> </QIcon>
<div id="searchbar-after"></div>
</template> </template>
</VnInput> </VnInput>
</QForm> </QForm>

View File

@ -49,7 +49,7 @@ function formatNumber(number) {
<VnPaginate <VnPaginate
:data-key="$props.url" :data-key="$props.url"
:url="$props.url" :url="$props.url"
:user-filter="filter" :filter="filter"
order="smsFk DESC" order="smsFk DESC"
:offset="100" :offset="100"
:limit="5" :limit="5"

View File

@ -19,26 +19,23 @@ onMounted(() => {
const observer = new MutationObserver( const observer = new MutationObserver(
() => () =>
(hasContent.value = (hasContent.value =
actions.value?.childNodes?.length + data.value?.childNodes?.length), actions.value?.childNodes?.length + data.value?.childNodes?.length)
); );
if (actions.value) observer.observe(actions.value, opts); if (actions.value) observer.observe(actions.value, opts);
if (data.value) observer.observe(data.value, opts); if (data.value) observer.observe(data.value, opts);
}); });
const actionsChildCount = () => !!actions.value?.childNodes?.length; onBeforeUnmount(() => stateStore.toggleSubToolbar());
onBeforeUnmount(() => stateStore.toggleSubToolbar() && hasSubToolbar);
</script> </script>
<template> <template>
<QToolbar <QToolbar
id="subToolbar" id="subToolbar"
v-show="hasContent || $slots['st-actions'] || $slots['st-data']"
class="justify-end sticky" class="justify-end sticky"
v-show="hasContent || $slots['st-actions'] || $slots['st-data']"
> >
<slot name="st-data"> <slot name="st-data">
<div id="st-data" :class="{ 'full-width': !actionsChildCount() }"> <div id="st-data"></div>
</div>
</slot> </slot>
<QSpace /> <QSpace />
<slot name="st-actions"> <slot name="st-actions">

View File

@ -1,5 +1,5 @@
<script setup> <script setup>
import { ref } from 'vue'; import { defineProps, ref } from 'vue';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
const { t } = useI18n(); const { t } = useI18n();

View File

@ -51,6 +51,16 @@ describe('CardSummary', () => {
expect(vm.store.filter).toEqual('cardFilter'); expect(vm.store.filter).toEqual('cardFilter');
}); });
it('should compute entity correctly from store data', () => {
vm.store.data = [{ id: 1, name: 'Entity 1' }];
expect(vm.entity).toEqual({ id: 1, name: 'Entity 1' });
});
it('should handle empty data gracefully', () => {
vm.store.data = [];
expect(vm.entity).toBeUndefined();
});
it('should respond to prop changes and refetch data', async () => { it('should respond to prop changes and refetch data', async () => {
const newUrl = 'CardSummary/35'; const newUrl = 'CardSummary/35';
const newKey = 'cardSummaryKey/35'; const newKey = 'cardSummaryKey/35';

View File

@ -1,89 +0,0 @@
import { vi, describe, expect, it, beforeEach, afterEach } from 'vitest';
import { createWrapper } from 'app/test/vitest/helper';
import VnImg from 'src/components/ui/VnImg.vue';
let wrapper;
let vm;
const isEmployeeMock = vi.fn();
function generateWrapper(storage = 'images') {
wrapper = createWrapper(VnImg, {
props: {
id: 123,
zoomResolution: '400x400',
storage,
}
});
wrapper = wrapper.wrapper;
vm = wrapper.vm;
vm.timeStamp = 'timestamp';
};
vi.mock('src/composables/useSession', () => ({
useSession: () => ({
getTokenMultimedia: () => 'token',
}),
}));
vi.mock('src/composables/useRole', () => ({
useRole: () => ({
isEmployee: isEmployeeMock,
}),
}));
describe('VnImg', () => {
beforeEach(() => {
isEmployeeMock.mockReset();
});
afterEach(() => {
vi.clearAllMocks();
});
describe('getUrl', () => {
it('should return /api/{storage}/{id}/downloadFile?access_token={token} when storage is dms', async () => {
isEmployeeMock.mockReturnValue(false);
generateWrapper('dms');
await vm.$nextTick();
const url = vm.getUrl();
expect(url).toBe('/api/dms/123/downloadFile?access_token=token');
});
it('should return /no-user.png when role is not employee and storage is not dms', async () => {
isEmployeeMock.mockReturnValue(false);
generateWrapper();
await vm.$nextTick();
const url = vm.getUrl();
expect(url).toBe('/no-user.png');
});
it('should return /api/{storage}/{collection}/{curResolution}/{id}/download?access_token={token}&{timeStamp} when zoom is false and role is employee and storage is not dms', async () => {
isEmployeeMock.mockReturnValue(true);
generateWrapper();
await vm.$nextTick();
const url = vm.getUrl();
expect(url).toBe('/api/images/catalog/200x200/123/download?access_token=token&timestamp');
});
it('should return /api/{storage}/{collection}/{curResolution}/{id}/download?access_token={token}&{timeStamp} when zoom is true and role is employee and storage is not dms', async () => {
isEmployeeMock.mockReturnValue(true);
generateWrapper();
await vm.$nextTick();
const url = vm.getUrl(true);
expect(url).toBe('/api/images/catalog/400x400/123/download?access_token=token&timestamp');
});
});
describe('reload', () => {
it('should update the timestamp', async () => {
generateWrapper();
const initialTimestamp = wrapper.vm.timeStamp;
wrapper.vm.reload();
const newTimestamp = wrapper.vm.timeStamp;
expect(initialTimestamp).not.toEqual(newTimestamp);
});
});
});

View File

@ -1,71 +0,0 @@
import { vi, describe, expect, it, beforeEach, afterEach } from 'vitest';
import { createWrapper } from 'app/test/vitest/helper';
import VnSearchbar from 'src/components/ui/VnSearchbar.vue';
describe('VnSearchbar', () => {
let vm;
let wrapper;
let applyFilterSpy;
const searchText = 'Bolas de madera';
const userParams = {staticKey: 'staticValue'};
beforeEach(async () => {
wrapper = createWrapper(VnSearchbar, {
propsData: {
dataKey: 'testKey',
filter: null,
whereFilter: null,
searchRemoveParams: true,
},
});
wrapper = wrapper.wrapper;
vm = wrapper.vm;
vm.searchText = searchText;
vm.arrayData.store.userParams = userParams;
applyFilterSpy = vi.spyOn(vm.arrayData, 'applyFilter').mockImplementation(() => {});
});
afterEach(() => {
vi.clearAllMocks();
});
it('search resets pagination and applies filter', async () => {
const resetPaginationSpy = vi.spyOn(vm.arrayData, 'resetPagination').mockImplementation(() => {});
await vm.search();
expect(resetPaginationSpy).toHaveBeenCalled();
expect(applyFilterSpy).toHaveBeenCalledWith({
params: { search: searchText },
});
});
it('search includes static params if searchRemoveParams is false', async () => {
wrapper.setProps({ searchRemoveParams: false });
await vm.$nextTick();
await vm.search();
expect(applyFilterSpy).toHaveBeenCalledWith({
params: { staticKey: 'staticValue', search: searchText },
filter: {skip: 0},
});
});
it('updates store when dataKey changes', async () => {
expect(vm.store.userParams).toEqual(userParams);
wrapper.setProps({ dataKey: 'newTestKey' });
await vm.$nextTick();
expect(vm.store.userParams).toEqual({});
});
it('computes the "to" property correctly for redirection', () => {
vm.arrayData.store.searchUrl = 'searchParam';
vm.arrayData.store.currentFilter = { category: 'plants' };
const expectedQuery = JSON.stringify({
...vm.arrayData.store.currentFilter,
search: searchText,
});
expect(vm.to.query.searchParam).toBe(expectedQuery);
});
});

View File

@ -16,7 +16,7 @@ describe('useArrayData', () => {
vi.clearAllMocks(); vi.clearAllMocks();
}); });
it('should fetch and replace url with new params', async () => { it('should fetch and repalce url with new params', async () => {
vi.spyOn(axios, 'get').mockReturnValueOnce({ data: [] }); vi.spyOn(axios, 'get').mockReturnValueOnce({ data: [] });
const arrayData = useArrayData('ArrayData', { url: 'mockUrl' }); const arrayData = useArrayData('ArrayData', { url: 'mockUrl' });
@ -33,11 +33,11 @@ describe('useArrayData', () => {
}); });
expect(routerReplace.path).toEqual('mockSection/list'); expect(routerReplace.path).toEqual('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 get data and send new URL without keeping parameters, if there is only one record', async () => {
vi.spyOn(axios, 'get').mockReturnValueOnce({ data: [{ id: 1 }] }); vi.spyOn(axios, 'get').mockReturnValueOnce({ data: [{ id: 1 }] });
const arrayData = useArrayData('ArrayData', { url: 'mockUrl', navigate: {} }); const arrayData = useArrayData('ArrayData', { url: 'mockUrl', navigate: {} });
@ -56,7 +56,7 @@ describe('useArrayData', () => {
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 get data and send new URL keeping parameters, if you have more than one record', async () => {
vi.spyOn(axios, 'get').mockReturnValueOnce({ data: [{ id: 1 }, { id: 2 }] }); vi.spyOn(axios, 'get').mockReturnValueOnce({ data: [{ id: 1 }, { id: 2 }] });
vi.spyOn(vueRouter, 'useRoute').mockReturnValue({ vi.spyOn(vueRouter, 'useRoute').mockReturnValue({
@ -95,25 +95,4 @@ describe('useArrayData', () => {
expect(routerPush.path).toEqual('mockName/'); expect(routerPush.path).toEqual('mockName/');
expect(routerPush.query.params).toBeDefined(); expect(routerPush.query.params).toBeDefined();
}); });
it('should return one record', async () => {
vi.spyOn(axios, 'get').mockReturnValueOnce({
data: [
{ id: 1, name: 'Entity 1' },
{ id: 2, name: 'Entity 2' },
],
});
const arrayData = useArrayData('ArrayData', { url: 'mockUrl', oneRecord: true });
await arrayData.fetch({});
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

@ -7,9 +7,7 @@ import { isDialogOpened } from 'src/filters';
const arrayDataStore = useArrayDataStore(); const arrayDataStore = useArrayDataStore();
export function useArrayData(key, userOptions) { export function useArrayData(key = useRoute().meta.moduleName, userOptions) {
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');
if (!arrayDataStore.get(key)) arrayDataStore.set(key); if (!arrayDataStore.get(key)) arrayDataStore.set(key);
@ -33,11 +31,10 @@ export function useArrayData(key, userOptions) {
: JSON.parse(params?.filter ?? '{}'); : JSON.parse(params?.filter ?? '{}');
delete params.filter; delete params.filter;
store.userParams = params; store.userParams = { ...store.userParams, ...params };
store.filter = { ...filter, ...store.userFilter }; store.filter = { ...filter, ...store.userFilter };
if (filter?.order) store.order = filter.order; if (filter?.order) store.order = filter.order;
} }
setCurrentFilter();
}); });
if (key && userOptions) setOptions(); if (key && userOptions) setOptions();
@ -57,7 +54,6 @@ export function useArrayData(key, userOptions) {
'navigate', 'navigate',
'mapKey', 'mapKey',
'keepData', 'keepData',
'oneRecord',
]; ];
if (typeof userOptions === 'object') { if (typeof userOptions === 'object') {
for (const option in userOptions) { for (const option in userOptions) {
@ -80,7 +76,11 @@ export function useArrayData(key, userOptions) {
cancelRequest(); cancelRequest();
canceller = new AbortController(); canceller = new AbortController();
const { params, limit } = setCurrentFilter(); const { params, limit } = getCurrentFilter();
store.currentFilter = JSON.parse(JSON.stringify(params));
delete store.currentFilter.filter.include;
store.currentFilter.filter = JSON.stringify(store.currentFilter.filter);
let exprFilter; let exprFilter;
if (store?.exprBuilder) { if (store?.exprBuilder) {
@ -94,9 +94,6 @@ export function useArrayData(key, userOptions) {
if (params.filter.where || exprFilter) if (params.filter.where || exprFilter)
params.filter.where = { ...params.filter.where, ...exprFilter }; params.filter.where = { ...params.filter.where, ...exprFilter };
if (!params?.filter?.order?.length) delete params?.filter?.order;
params.filter = JSON.stringify(params.filter); params.filter = JSON.stringify(params.filter);
store.isLoading = true; store.isLoading = true;
@ -108,16 +105,12 @@ export function useArrayData(key, userOptions) {
store.hasMoreData = limit && response.data.length >= limit; store.hasMoreData = limit && response.data.length >= limit;
if (!append && !isDialogOpened() && updateRouter) { if (!append && !isDialogOpened() && updateRouter) {
if (updateStateParams(response.data)?.redirect && !store.keepData) return; if (updateStateParams(response.data)?.redirect) return;
} }
store.isLoading = false; store.isLoading = false;
canceller = null; canceller = null;
processData(response.data, { processData(response.data, { map: !!store.mapKey, append });
map: !!store.mapKey,
append,
oneRecord: store.oneRecord,
});
return response; return response;
} }
@ -147,12 +140,12 @@ export function useArrayData(key, userOptions) {
} }
} }
async function applyFilter({ filter, params }, fetchOptions = {}) { async function applyFilter({ filter, params }) {
if (filter) store.userFilter = filter; if (filter) store.userFilter = filter;
store.filter = {}; store.filter = {};
if (params) store.userParams = { ...params }; if (params) store.userParams = { ...params };
const response = await fetch(fetchOptions); const response = await fetch({});
return response; return response;
} }
@ -178,9 +171,10 @@ export function useArrayData(key, userOptions) {
async function addOrder(field, direction = 'ASC') { async function addOrder(field, direction = 'ASC') {
const newOrder = field + ' ' + direction; const newOrder = field + ' ' + direction;
const order = toArray(store.order); let order = store.order || [];
if (typeof order == 'string') order = [order];
let index = getOrderIndex(order, field); let index = order.findIndex((o) => o.split(' ')[0] === field);
if (index > -1) { if (index > -1) {
order[index] = newOrder; order[index] = newOrder;
} else { } else {
@ -197,24 +191,16 @@ export function useArrayData(key, userOptions) {
} }
async function deleteOrder(field) { async function deleteOrder(field) {
const order = toArray(store.order); let order = store.order ?? [];
const index = getOrderIndex(order, field); if (typeof order == 'string') order = [order];
const index = order.findIndex((o) => o.split(' ')[0] === field);
if (index > -1) order.splice(index, 1); if (index > -1) order.splice(index, 1);
store.order = order; store.order = order;
fetch({}); fetch({});
} }
function getOrderIndex(order, field) {
return order.findIndex((o) => o.split(' ')[0] === field);
}
function toArray(str = []) {
if (!str) return [];
if (Array.isArray(str)) return str;
if (typeof str === 'string') return str.split(',').map((item) => item.trim());
}
function sanitizerParams(params, exprBuilder) { function sanitizerParams(params, exprBuilder) {
for (const param in params) { for (const param in params) {
if (params[param] === '' || params[param] === null) { if (params[param] === '' || params[param] === null) {
@ -288,14 +274,14 @@ export function useArrayData(key, userOptions) {
} }
function getCurrentFilter() { function getCurrentFilter() {
if (!Object.keys(store.userParams).length)
store.userParams = store.defaultParams ?? {};
const filter = { const filter = {
limit: store.limit, limit: store.limit,
...store.userFilter,
}; };
let userParams = { ...store.userParams };
Object.assign(filter, store.userFilter);
let where; let where;
if (filter?.where || store.filter?.where) if (filter?.where || store.filter?.where)
where = Object.assign(filter?.where ?? {}, store.filter?.where ?? {}); where = Object.assign(filter?.where ?? {}, store.filter?.where ?? {});
@ -303,27 +289,16 @@ export function useArrayData(key, userOptions) {
filter.where = where; filter.where = where;
const params = { filter }; const params = { filter };
Object.assign(params, store.userParams); Object.assign(params, userParams);
if (params.filter) params.filter.skip = store.skip; if (params.filter) params.filter.skip = store.skip;
if (store.order) params.filter.order = toArray(store.order); if (store?.order && typeof store?.order == 'string') store.order = [store.order];
if (store.order?.length) params.filter.order = [...store.order];
else delete params.filter.order; else delete params.filter.order;
return { filter, params, limit: filter.limit }; return { filter, params, limit: filter.limit };
} }
function setCurrentFilter() { function processData(data, { map = true, append = true }) {
const { params, limit } = getCurrentFilter();
store.currentFilter = JSON.parse(JSON.stringify(params));
delete store.currentFilter.filter.include;
store.currentFilter.filter = JSON.stringify(store.currentFilter.filter);
return { params, limit };
}
function processData(data, { map = true, append = true, oneRecord = false }) {
if (oneRecord) {
store.data = Array.isArray(data) ? data[0] : data;
return;
}
if (!append) { if (!append) {
store.data = []; store.data = [];
store.map = new Map(); store.map = new Map();
@ -356,7 +331,6 @@ export function useArrayData(key, userOptions) {
applyFilter, applyFilter,
addFilter, addFilter,
getCurrentFilter, getCurrentFilter,
setCurrentFilter,
addFilterWhere, addFilterWhere,
addOrder, addOrder,
deleteOrder, deleteOrder,

View File

@ -29,12 +29,8 @@ export function useFilterParams(key) {
orders.value = orderObject; orders.value = orderObject;
} }
function setUserParams(watchedParams = {}) { function setUserParams(watchedParams) {
if (Object.keys(watchedParams).length == 0) { if (!watchedParams || Object.keys(watchedParams).length == 0) return;
params.value = {};
orders.value = {};
return;
}
if (typeof watchedParams == 'string') watchedParams = JSON.parse(watchedParams); if (typeof watchedParams == 'string') watchedParams = JSON.parse(watchedParams);
if (typeof watchedParams?.filter == 'string') if (typeof watchedParams?.filter == 'string')

View File

@ -5,7 +5,7 @@ export function useHasContent(selector) {
const hasContent = ref(); const hasContent = ref();
onMounted(() => { onMounted(() => {
container.value = document?.querySelector(selector); container.value = document.querySelector(selector);
if (!container.value) return; if (!container.value) return;
const observer = new MutationObserver(() => { const observer = new MutationObserver(() => {

View File

@ -6,7 +6,6 @@ import axios from 'axios';
import { useRouter } from 'vue-router'; import { useRouter } from 'vue-router';
import useNotify from './useNotify'; import useNotify from './useNotify';
import { useTokenConfig } from './useTokenConfig'; import { useTokenConfig } from './useTokenConfig';
import { getToken, getTokenMultimedia } from 'src/utils/session';
const TOKEN_MULTIMEDIA = 'tokenMultimedia'; const TOKEN_MULTIMEDIA = 'tokenMultimedia';
const TOKEN = 'token'; const TOKEN = 'token';
@ -16,6 +15,19 @@ export function useSession() {
let isCheckingToken = false; let isCheckingToken = false;
let intervalId = null; let intervalId = null;
function getToken() {
const localToken = localStorage.getItem(TOKEN);
const sessionToken = sessionStorage.getItem(TOKEN);
return localToken || sessionToken || '';
}
function getTokenMultimedia() {
const localTokenMultimedia = localStorage.getItem(TOKEN_MULTIMEDIA);
const sessionTokenMultimedia = sessionStorage.getItem(TOKEN_MULTIMEDIA);
return localTokenMultimedia || sessionTokenMultimedia || '';
}
function setSession(data) { function setSession(data) {
let keepLogin = data.keepLogin; let keepLogin = data.keepLogin;
const storage = keepLogin ? localStorage : sessionStorage; const storage = keepLogin ? localStorage : sessionStorage;

View File

@ -4,10 +4,10 @@ import { useQuasar } from 'quasar';
export function useSummaryDialog() { export function useSummaryDialog() {
const quasar = useQuasar(); const quasar = useQuasar();
function viewSummary(id, summary, width) { function viewSummary(id, summary) {
quasar.dialog({ quasar.dialog({
component: VnSummaryDialog, component: VnSummaryDialog,
componentProps: { id, summary, width }, componentProps: { id, summary },
}); });
} }

View File

@ -1,6 +1,6 @@
// app global css in SCSS form // app global css in SCSS form
@import './icons.scss'; @import './icons.scss';
@import '@quasar/quasar-ui-qcalendar/src/QCalendarMonth.scss'; @import '@quasar/quasar-ui-qcalendar/src/QCalendarMonth.sass';
body.body--light { body.body--light {
--vn-header-color: #cecece; --vn-header-color: #cecece;
@ -212,10 +212,6 @@ select:-webkit-autofill {
justify-content: center; justify-content: center;
} }
.q-card__section[dense] {
padding: 0;
}
input[type='number'] { input[type='number'] {
-moz-appearance: textfield; -moz-appearance: textfield;
} }
@ -314,14 +310,6 @@ input::-webkit-inner-spin-button {
.no-visible { .no-visible {
visibility: hidden; visibility: hidden;
} }
.q-item > .q-item__section:has(.q-checkbox) {
max-width: fit-content;
}
.row > .column:has(.q-checkbox) {
max-width: fit-content;
}
.q-field__inner { .q-field__inner {
.q-field__control { .q-field__control {
min-height: auto !important; min-height: auto !important;

Binary file not shown.

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 186 KiB

After

Width:  |  Height:  |  Size: 180 KiB

Binary file not shown.

Binary file not shown.

File diff suppressed because one or more lines are too long

View File

@ -1,10 +1,10 @@
@font-face { @font-face {
font-family: 'icon'; font-family: 'icon';
src: url('fonts/icon.eot?uocffs'); src: url('fonts/icon.eot?y0x93o');
src: url('fonts/icon.eot?uocffs#iefix') format('embedded-opentype'), src: url('fonts/icon.eot?y0x93o#iefix') format('embedded-opentype'),
url('fonts/icon.ttf?uocffs') format('truetype'), url('fonts/icon.ttf?y0x93o') format('truetype'),
url('fonts/icon.woff?uocffs') format('woff'), url('fonts/icon.woff?y0x93o') format('woff'),
url('fonts/icon.svg?uocffs#icon') format('svg'); url('fonts/icon.svg?y0x93o#icon') format('svg');
font-weight: normal; font-weight: normal;
font-style: normal; font-style: normal;
font-display: block; font-display: block;
@ -25,17 +25,8 @@
-moz-osx-font-smoothing: grayscale; -moz-osx-font-smoothing: grayscale;
} }
.icon-inactive-car:before { .icon-entry_lastbuys:before {
content: "\e978"; content: "\e91a";
}
.icon-hasItemLost:before {
content: "\e957";
}
.icon-hasItemDelay:before {
content: "\e96d";
}
.icon-add_entries:before {
content: "\e953";
} }
.icon-100:before { .icon-100:before {
content: "\e901"; content: "\e901";
@ -61,9 +52,6 @@
.icon-addperson:before { .icon-addperson:before {
content: "\e908"; content: "\e908";
} }
.icon-agencia_tributaria:before {
content: "\e948";
}
.icon-agency:before { .icon-agency:before {
content: "\e92a"; content: "\e92a";
} }
@ -201,9 +189,6 @@
.icon-entry:before { .icon-entry:before {
content: "\e937"; content: "\e937";
} }
.icon-entry_lastbuys:before {
content: "\e91a";
}
.icon-exit:before { .icon-exit:before {
content: "\e938"; content: "\e938";
} }

View File

@ -33,11 +33,6 @@ $dark-shadow-color: black;
$layout-shadow-dark: 0 0 10px 2px #00000033, 0 0px 10px #0000003d; $layout-shadow-dark: 0 0 10px 2px #00000033, 0 0px 10px #0000003d;
$spacing-md: 16px; $spacing-md: 16px;
$color-font-secondary: #777; $color-font-secondary: #777;
$width-xs: 400px;
$width-sm: 544px;
$width-md: 800px;
$width-lg: 1280px;
$width-xl: 1600px;
.bg-success { .bg-success {
background-color: $positive; background-color: $positive;
} }

View File

@ -16,7 +16,6 @@ import getUpdatedValues from './getUpdatedValues';
import getParamWhere from './getParamWhere'; import getParamWhere from './getParamWhere';
import parsePhone from './parsePhone'; import parsePhone from './parsePhone';
import isDialogOpened from './isDialogOpened'; import isDialogOpened from './isDialogOpened';
import toCelsius from './toCelsius';
export { export {
getUpdatedValues, getUpdatedValues,
@ -37,5 +36,4 @@ export {
dashIfEmpty, dashIfEmpty,
dateRange, dateRange,
getParamWhere, getParamWhere,
toCelsius,
}; };

View File

@ -1,3 +0,0 @@
export default function toCelsius(value) {
return value ? `${value}°C` : '';
}

View File

@ -2,14 +2,12 @@ globals:
lang: lang:
es: Spanish es: Spanish
en: English en: English
language: Language
quantity: Quantity quantity: Quantity
language: Language
entity: Entity entity: Entity
preview: Preview
user: User user: User
details: Details details: Details
collapseMenu: Collapse lateral menu collapseMenu: Collapse left menu
advancedMenu: Advanced menu
backToDashboard: Return to dashboard backToDashboard: Return to dashboard
notifications: Notifications notifications: Notifications
userPanel: User panel userPanel: User panel
@ -37,6 +35,7 @@ globals:
confirm: Confirm confirm: Confirm
assign: Assign assign: Assign
back: Back back: Back
downloadPdf: Download PDF
yes: 'Yes' yes: 'Yes'
no: 'No' no: 'No'
noChanges: No changes to save noChanges: No changes to save
@ -60,7 +59,6 @@ globals:
downloadCSVSuccess: CSV downloaded successfully downloadCSVSuccess: CSV downloaded successfully
reference: Reference reference: Reference
agency: Agency agency: Agency
entry: Entry
warehouseOut: Warehouse Out warehouseOut: Warehouse Out
warehouseIn: Warehouse In warehouseIn: Warehouse In
landed: Landed landed: Landed
@ -69,11 +67,11 @@ globals:
amount: Amount amount: Amount
packages: Packages packages: Packages
download: Download download: Download
downloadPdf: Download PDF
selectRows: 'Select all { numberRows } row(s)' selectRows: 'Select all { numberRows } row(s)'
allRows: 'All { numberRows } row(s)' allRows: 'All { numberRows } row(s)'
markAll: Mark all markAll: Mark all
requiredField: Required field requiredField: Required field
valueCantBeEmpty: Value cannot be empty
class: clase class: clase
type: Type type: Type
reason: reason reason: reason
@ -83,9 +81,6 @@ globals:
warehouse: Warehouse warehouse: Warehouse
company: Company company: Company
fieldRequired: Field required fieldRequired: Field required
valueCantBeEmpty: Value cannot be empty
Value can't be blank: Value cannot be blank
Value can't be null: Value cannot be null
allowedFilesText: 'Allowed file types: { allowedContentTypes }' allowedFilesText: 'Allowed file types: { allowedContentTypes }'
smsSent: SMS sent smsSent: SMS sent
confirmDeletion: Confirm deletion confirmDeletion: Confirm deletion
@ -135,26 +130,6 @@ globals:
medium: Medium medium: Medium
big: Big big: Big
email: Email email: Email
supplier: Supplier
ticketList: Ticket List
created: Created
worker: Worker
now: Now
name: Name
new: New
comment: Comment
observations: Observations
goToModuleIndex: Go to module index
createInvoiceIn: Create invoice in
myAccount: My account
noOne: No one
maxTemperature: Max
minTemperature: Min
changePass: Change password
deleteConfirmTitle: Delete selected elements
changeState: Change state
raid: 'Raid {daysInForward} days'
isVies: Vies
pageTitles: pageTitles:
logIn: Login logIn: Login
addressEdit: Update address addressEdit: Update address
@ -176,14 +151,13 @@ globals:
subRoles: Subroles subRoles: Subroles
inheritedRoles: Inherited Roles inheritedRoles: Inherited Roles
customers: Customers customers: Customers
customerCreate: New customer
createCustomer: Create customer
createOrder: New order
list: List list: List
webPayments: Web Payments webPayments: Web Payments
extendedList: Extended list extendedList: Extended list
notifications: Notifications notifications: Notifications
defaulter: Defaulter defaulter: Defaulter
customerCreate: New customer
createOrder: New order
fiscalData: Fiscal data fiscalData: Fiscal data
billingData: Billing data billingData: Billing data
consignees: Consignees consignees: Consignees
@ -219,28 +193,27 @@ globals:
claims: Claims claims: Claims
claimCreate: New claim claimCreate: New claim
lines: Lines lines: Lines
development: Development
photos: Photos photos: Photos
development: Development
action: Action action: Action
invoiceOuts: Invoice out invoiceOuts: Invoice out
negativeBases: Negative Bases negativeBases: Negative Bases
globalInvoicing: Global invoicing globalInvoicing: Global invoicing
invoiceOutCreate: Create invoice out invoiceOutCreate: Create invoice out
order: Orders
orderList: List
orderCreate: New order
catalog: Catalog
volume: Volume
shelving: Shelving shelving: Shelving
shelvingList: Shelving List shelvingList: Shelving List
shelvingCreate: New shelving shelvingCreate: New shelving
invoiceIns: Invoices In invoiceIns: Invoices In
invoiceInCreate: Create invoice in invoiceInCreate: Create invoice in
vat: VAT vat: VAT
labeler: Labeler
dueDay: Due day dueDay: Due day
intrastat: Intrastat intrastat: Intrastat
corrective: Corrective corrective: Corrective
order: Orders
orderList: List
orderCreate: New order
catalog: Catalog
volume: Volume
workers: Workers workers: Workers
workerCreate: New worker workerCreate: New worker
department: Department department: Department
@ -253,10 +226,10 @@ globals:
wagonsList: Wagons List wagonsList: Wagons List
wagonCreate: Create wagon wagonCreate: Create wagon
wagonEdit: Edit wagon wagonEdit: Edit wagon
wagonCounter: Trolley counter
typesList: Types List typesList: Types List
typeCreate: Create type typeCreate: Create type
typeEdit: Edit type typeEdit: Edit type
wagonCounter: Trolley counter
roadmap: Roadmap roadmap: Roadmap
stops: Stops stops: Stops
routes: Routes routes: Routes
@ -265,16 +238,21 @@ globals:
routeCreate: New route routeCreate: New route
RouteRoadmap: Roadmaps RouteRoadmap: Roadmaps
RouteRoadmapCreate: Create roadmap RouteRoadmapCreate: Create roadmap
RouteExtendedList: Router
autonomous: Autonomous autonomous: Autonomous
suppliers: Suppliers suppliers: Suppliers
supplier: Supplier supplier: Supplier
expedition: Expedition
services: Service
components: Components
pictures: Pictures
packages: Packages
tracking: Tracking
labeler: Labeler
supplierCreate: New supplier supplierCreate: New supplier
accounts: Accounts accounts: Accounts
addresses: Addresses addresses: Addresses
agencyTerm: Agency agreement agencyTerm: Agency agreement
travel: Travels travel: Travels
create: Create
extraCommunity: Extra community extraCommunity: Extra community
travelCreate: New travel travelCreate: New travel
history: Log history: Log
@ -282,13 +260,14 @@ globals:
items: Items items: Items
diary: Diary diary: Diary
tags: Tags tags: Tags
fixedPrice: Fixed prices create: Create
buyRequest: Buy requests buyRequest: Buy requests
fixedPrice: Fixed prices
wasteBreakdown: Waste breakdown wasteBreakdown: Waste breakdown
itemCreate: New item itemCreate: New item
barcode: Barcodes
tax: Tax tax: Tax
botanical: Botanical botanical: Botanical
barcode: Barcodes
itemTypeCreate: New item type itemTypeCreate: New item type
family: Item Type family: Item Type
lastEntries: Last entries lastEntries: Last entries
@ -304,20 +283,13 @@ globals:
formation: Formation formation: Formation
locations: Locations locations: Locations
warehouses: Warehouses warehouses: Warehouses
saleTracking: Sale tracking
roles: Roles roles: Roles
connections: Connections connections: Connections
acls: ACLs acls: ACLs
mailForwarding: Mail forwarding mailForwarding: Mail forwarding
mailAlias: Mail alias mailAlias: Mail alias
privileges: Privileges privileges: Privileges
observation: Notes
expedition: Expedition
saleTracking: Sale tracking
services: Service
tracking: Tracking
components: Components
pictures: Pictures
packages: Packages
ldap: LDAP ldap: LDAP
samba: Samba samba: Samba
twoFactor: Two factor twoFactor: Two factor
@ -326,19 +298,30 @@ globals:
ticketsMonitor: Tickets monitor ticketsMonitor: Tickets monitor
clientsActionsMonitor: Clients and actions clientsActionsMonitor: Clients and actions
serial: Serial serial: Serial
business: Business
medical: Mutual medical: Mutual
pit: IRPF pit: IRPF
RouteExtendedList: Router
wasteRecalc: Waste recaclulate wasteRecalc: Waste recaclulate
operator: Operator operator: Operator
parking: Parking parking: Parking
vehicleList: Vehicles supplier: Supplier
vehicle: Vehicle created: Created
worker: Worker
now: Now
name: Name
new: New
comment: Comment
observations: Observations
goToModuleIndex: Go to module index
unsavedPopup: unsavedPopup:
title: Unsaved changes will be lost title: Unsaved changes will be lost
subtitle: Are you sure exit without saving? subtitle: Are you sure exit without saving?
createInvoiceIn: Create invoice in
myAccount: My account
noOne: No one
maxTemperature: Max
minTemperature: Min
params: params:
description: Description
clientFk: Client id clientFk: Client id
salesPersonFk: Sales person salesPersonFk: Sales person
warehouseFk: Warehouse warehouseFk: Warehouse
@ -355,19 +338,19 @@ globals:
supplierFk: Supplier supplierFk: Supplier
supplierRef: Supplier ref supplierRef: Supplier ref
serial: Serial serial: Serial
amount: Amount amount: Importe
awbCode: AWB awbCode: AWB
correctedFk: Rectified correctedFk: Rectified
correctingFk: Rectificative correctingFk: Rectificative
daysOnward: Days onward daysOnward: Days onward
countryFk: Country countryFk: Country
countryCodeFk: Country
companyFk: Company companyFk: Company
model: Model changePass: Change password
fuel: Fuel setPass: Set password
active: Active deleteConfirmTitle: Delete selected elements
inactive: Inactive changeState: Change state
deliveryPoint: Delivery point raid: 'Raid {daysInForward} days'
isVies: Vies
errors: errors:
statusUnauthorized: Access denied statusUnauthorized: Access denied
statusInternalServerError: An internal server error has ocurred statusInternalServerError: An internal server error has ocurred
@ -387,7 +370,7 @@ login:
loginError: Invalid username or password loginError: Invalid username or password
fieldRequired: This field is required fieldRequired: This field is required
twoFactorRequired: Two-factor verification required twoFactorRequired: Two-factor verification required
twoFactor: twoFactorRequired:
validate: Validate validate: Validate
insert: Enter the verification code insert: Enter the verification code
explanation: >- explanation: >-
@ -406,6 +389,80 @@ cau:
subtitle: By sending this ticket, all the data related to the error, the section, the user, etc., are already sent. subtitle: By sending this ticket, all the data related to the error, the section, the user, etc., are already sent.
inputLabel: Explain why this error should not appear inputLabel: Explain why this error should not appear
askPrivileges: Ask for privileges askPrivileges: Ask for privileges
entry:
list:
newEntry: New entry
tableVisibleColumns:
created: Creation
supplierFk: Supplier
isBooked: Booked
isConfirmed: Confirmed
isOrdered: Ordered
companyFk: Company
travelFk: Travel
isExcludedFromAvailable: Inventory
invoiceAmount: Import
summary:
commission: Commission
currency: Currency
invoiceNumber: Invoice number
ordered: Ordered
booked: Booked
excludedFromAvailable: Inventory
travelReference: Reference
travelAgency: Agency
travelShipped: Shipped
travelDelivered: Delivered
travelLanded: Landed
travelReceived: Received
buys: Buys
stickers: Stickers
package: Package
packing: Pack.
grouping: Group.
buyingValue: Buying value
import: Import
pvp: PVP
basicData:
travel: Travel
currency: Currency
commission: Commission
observation: Observation
booked: Booked
excludedFromAvailable: Inventory
buys:
observations: Observations
packagingFk: Box
color: Color
printedStickers: Printed stickers
notes:
observationType: Observation type
latestBuys:
tableVisibleColumns:
image: Picture
itemFk: Item ID
weightByPiece: Weight/Piece
isActive: Active
family: Family
entryFk: Entry
freightValue: Freight value
comissionValue: Commission value
packageValue: Package value
isIgnored: Is ignored
price2: Grouping
price3: Packing
minPrice: Min
ektFk: Ekt
packingOut: Package out
landing: Landing
isExcludedFromAvailable: Es inventory
params:
toShipped: To
fromShipped: From
warehouseiNFk: Warehouse
daysOnward: Days onward
daysAgo: Days ago
warehouseInFk: Warehouse in
ticket: ticket:
params: params:
ticketFk: Ticket ID ticketFk: Ticket ID
@ -463,9 +520,65 @@ ticket:
service: Service service: Service
attender: Attender attender: Attender
ok: Ok ok: Ok
consigneeStreet: Street
create: create:
address: Address address: Address
invoiceOut:
card:
issued: Issued
customerCard: Customer card
ticketList: Ticket List
summary:
issued: Issued
dued: Due
booked: Booked
taxBreakdown: Tax breakdown
taxableBase: Taxable base
rate: Rate
fee: Fee
tickets: Tickets
totalWithVat: Amount
globalInvoices:
errors:
chooseValidClient: Choose a valid client
chooseValidCompany: Choose a valid company
chooseValidPrinter: Choose a valid printer
chooseValidSerialType: Choose a serial type
fillDates: Invoice date and the max date should be filled
invoiceDateLessThanMaxDate: Invoice date can not be less than max date
invoiceWithFutureDate: Exists an invoice with a future date
noTicketsToInvoice: There are not tickets to invoice
criticalInvoiceError: 'Critical invoicing error, process stopped'
invalidSerialTypeForAll: The serial type must be global when invoicing all clients
table:
addressId: Address id
streetAddress: Street
statusCard:
percentageText: '{getPercentage}% {getAddressNumber} of {getNAddresses}'
pdfsNumberText: '{nPdfs} of {totalPdfs} PDFs'
negativeBases:
clientId: Client Id
base: Base
active: Active
hasToInvoice: Has to Invoice
verifiedData: Verified Data
comercial: Comercial
errors:
downloadCsvFailed: CSV download failed
shelving:
list:
parking: Parking
priority: Priority
newShelving: New Shelving
summary:
recyclable: Recyclable
parking:
pickingOrder: Picking order
sector: Sector
row: Row
column: Column
searchBar:
info: You can search by parking code
label: Search parking...
department: department:
chat: Chat chat: Chat
bossDepartment: Boss Department bossDepartment: Boss Department
@ -477,24 +590,6 @@ department:
hasToSendMail: Send check-ins by email hasToSendMail: Send check-ins by email
departmentRemoved: Department removed departmentRemoved: Department removed
worker: worker:
pageTitles:
workers: Workers
list: List
basicData: Basic data
summary: Summary
notifications: Notifications
workerCreate: New worker
department: Department
pda: PDA
notes: Notas
dms: My documentation
pbx: Private Branch Exchange
log: Log
calendar: Calendar
timeControl: Time control
locker: Locker
balance: Balance
medical: Medical
list: list:
department: Department department: Department
schedule: Schedule schedule: Schedule
@ -510,24 +605,15 @@ worker:
role: Role role: Role
sipExtension: Extension sipExtension: Extension
locker: Locker locker: Locker
fiDueDate: DNI expiration date fiDueDate: FI due date
sex: Sex sex: Sex
seniority: Antiquity seniority: Seniority
fi: DNI/NIE/NIF fi: DNI/NIE/NIF
birth: Birth birth: Birth
isFreelance: Freelance isFreelance: Freelance
isSsDiscounted: SS Bonification isSsDiscounted: SS Bonification
hasMachineryAuthorized: Machinery authorized hasMachineryAuthorized: Machinery authorized
isDisable: Disable isDisable: Disable
business: Business
started: Started
ended: Ended
reasonEnd: Reason End
department: Departament
workerBusinessCategory: Worker Business Category
notes: Notes
workCenter: Center
professionalCategory: Professional Category
notificationsManager: notificationsManager:
activeNotifications: Active notifications activeNotifications: Active notifications
availableNotifications: Available notifications availableNotifications: Available notifications
@ -586,23 +672,6 @@ worker:
sizeLimit: Size limit sizeLimit: Size limit
isOnReservationMode: Reservation mode isOnReservationMode: Reservation mode
machine: Machine machine: Machine
business:
tableVisibleColumns:
started: Start Date
ended: End Date
company: Company
reasonEnd: Reason for Termination
department: Department
professionalCategory: Professional Category
calendarType: Work Calendar
workCenter: Work Center
payrollCategories: Contract Category
occupationCode: Contribution Code
rate: Rate
businessType: Contract Type
amount: Salary
basicSalary: Transport Workers Salary
notes: Notes
wagon: wagon:
type: type:
submit: Submit submit: Submit
@ -635,8 +704,6 @@ wagon:
name: Name name: Name
supplier: supplier:
search: Search supplier
searchInfo: Search supplier by id or name
list: list:
payMethod: Pay method payMethod: Pay method
account: Account account: Account
@ -703,9 +770,6 @@ supplier:
consumption: consumption:
entry: Entry entry: Entry
travel: travel:
search: Search travel
searchInfo: You can search by travel id or name
id: Id
travelList: travelList:
tableVisibleColumns: tableVisibleColumns:
ref: Reference ref: Reference
@ -714,7 +778,6 @@ travel:
totalEntries: Total entries totalEntries: Total entries
totalEntriesTooltip: Total entries totalEntriesTooltip: Total entries
daysOnward: Landed days onwards daysOnward: Landed days onwards
awb: AWB
summary: summary:
entryId: Entry Id entryId: Entry Id
freight: Freight freight: Freight
@ -736,7 +799,62 @@ travel:
destination: Destination destination: Destination
thermograph: Thermograph thermograph: Thermograph
travelFileDescription: 'Travel id { travelId }' travelFileDescription: 'Travel id { travelId }'
carrier: Carrier item:
descriptor:
buyer: Buyer
color: Color
category: Category
available: Available
warehouseText: 'Calculated on the warehouse of { warehouseName }'
itemDiary: Item diary
list:
id: Identifier
stems: Stems
category: Category
typeName: Type
isActive: Active
userName: Buyer
weightByPiece: Weight/Piece
stemMultiplier: Multiplier
fixedPrice:
itemFk: Item ID
groupingPrice: Grouping price
packingPrice: Packing price
hasMinPrice: Has min price
minPrice: Min price
started: Started
ended: Ended
create:
priority: Priority
buyRequest:
requester: Requester
requested: Requested
attender: Atender
achieved: Achieved
concept: Concept
summary:
otherData: Other data
tax: Tax
botanical: Botanical
barcode: Barcode
completeName: Complete name
family: Familiy
stems: Stems
multiplier: Multiplier
buyer: Buyer
doPhoto: Do photo
intrastatCode: Intrastat code
ref: Reference
relevance: Relevance
weight: Weight (gram)/stem
units: Units/box
expense: Expense
generic: Generic
recycledPlastic: Recycled plastic
nonRecycledPlastic: Non recycled plastic
minSalesQuantity: Min sales quantity
genus: Genus
specie: Specie
components: components:
topbar: {} topbar: {}
itemsFilterPanel: itemsFilterPanel:
@ -751,10 +869,7 @@ components:
hasMinPrice: Minimum price hasMinPrice: Minimum price
# LatestBuysFilter # LatestBuysFilter
salesPersonFk: Buyer salesPersonFk: Buyer
supplierFk: Supplier
from: From from: From
to: To
visible: Is visible
active: Is active active: Is active
floramondo: Is floramondo floramondo: Is floramondo
showBadDates: Show future items showBadDates: Show future items

View File

@ -5,11 +5,9 @@ globals:
language: Idioma language: Idioma
quantity: Cantidad quantity: Cantidad
entity: Entidad entity: Entidad
preview: Vista previa
user: Usuario user: Usuario
details: Detalles details: Detalles
collapseMenu: Contraer menú lateral collapseMenu: Contraer menú lateral
advancedMenu: Menú avanzado
backToDashboard: Volver al tablón backToDashboard: Volver al tablón
notifications: Notificaciones notifications: Notificaciones
userPanel: Panel de usuario userPanel: Panel de usuario
@ -55,12 +53,11 @@ globals:
today: Hoy today: Hoy
yesterday: Ayer yesterday: Ayer
dateFormat: es-ES dateFormat: es-ES
microsip: Abrir en MicroSIP
noSelectedRows: No tienes ninguna línea seleccionada noSelectedRows: No tienes ninguna línea seleccionada
microsip: Abrir en MicroSIP
downloadCSVSuccess: Descarga de CSV exitosa downloadCSVSuccess: Descarga de CSV exitosa
reference: Referencia reference: Referencia
agency: Agencia agency: Agencia
entry: Entrada
warehouseOut: Alm. salida warehouseOut: Alm. salida
warehouseIn: Alm. entrada warehouseIn: Alm. entrada
landed: F. entrega landed: F. entrega
@ -135,26 +132,6 @@ globals:
medium: Mediano/a medium: Mediano/a
big: Grande big: Grande
email: Correo email: Correo
supplier: Proveedor
ticketList: Listado de tickets
created: Fecha creación
worker: Trabajador
now: Ahora
name: Nombre
new: Nuevo
comment: Comentario
observations: Observaciones
goToModuleIndex: Ir al índice del módulo
createInvoiceIn: Crear factura recibida
myAccount: Mi cuenta
noOne: Nadie
maxTemperature: Máx
minTemperature: Mín
changePass: Cambiar contraseña
deleteConfirmTitle: Eliminar los elementos seleccionados
changeState: Cambiar estado
raid: 'Redada {daysInForward} días'
isVies: Vies
pageTitles: pageTitles:
logIn: Inicio de sesión logIn: Inicio de sesión
addressEdit: Modificar consignatario addressEdit: Modificar consignatario
@ -177,17 +154,17 @@ globals:
inheritedRoles: Roles heredados inheritedRoles: Roles heredados
customers: Clientes customers: Clientes
customerCreate: Nuevo cliente customerCreate: Nuevo cliente
createCustomer: Crear cliente
createOrder: Nuevo pedido createOrder: Nuevo pedido
list: Listado list: Listado
webPayments: Pagos Web webPayments: Pagos Web
extendedList: Listado extendido extendedList: Listado extendido
notifications: Notificaciones notifications: Notificaciones
defaulter: Morosos defaulter: Morosos
createCustomer: Crear cliente
fiscalData: Datos fiscales fiscalData: Datos fiscales
billingData: Forma de pago billingData: Forma de pago
consignees: Consignatarios consignees: Consignatarios
address-create: Nuevo consignatario 'address-create': Nuevo consignatario
notes: Notas notes: Notas
credits: Créditos credits: Créditos
greuges: Greuges greuges: Greuges
@ -253,10 +230,10 @@ globals:
wagonsList: Listado vagones wagonsList: Listado vagones
wagonCreate: Crear tipo wagonCreate: Crear tipo
wagonEdit: Editar tipo wagonEdit: Editar tipo
wagonCounter: Contador de carros
typesList: Listado tipos typesList: Listado tipos
typeCreate: Crear tipo typeCreate: Crear tipo
typeEdit: Editar tipo typeEdit: Editar tipo
wagonCounter: Contador de carros
roadmap: Troncales roadmap: Troncales
stops: Paradas stops: Paradas
routes: Rutas routes: Rutas
@ -265,8 +242,8 @@ globals:
routeCreate: Nueva ruta routeCreate: Nueva ruta
RouteRoadmap: Troncales RouteRoadmap: Troncales
RouteRoadmapCreate: Crear troncal RouteRoadmapCreate: Crear troncal
RouteExtendedList: Enrutador
autonomous: Autónomos autonomous: Autónomos
RouteExtendedList: Enrutador
suppliers: Proveedores suppliers: Proveedores
supplier: Proveedor supplier: Proveedor
supplierCreate: Nuevo proveedor supplierCreate: Nuevo proveedor
@ -326,19 +303,29 @@ globals:
ticketsMonitor: Monitor de tickets ticketsMonitor: Monitor de tickets
clientsActionsMonitor: Clientes y acciones clientsActionsMonitor: Clientes y acciones
serial: Facturas por serie serial: Facturas por serie
business: Contratos
medical: Mutua medical: Mutua
pit: IRPF pit: IRPF
wasteRecalc: Recalcular mermas wasteRecalc: Recalcular mermas
operator: Operario operator: Operario
parking: Parking parking: Parking
vehicleList: Vehículos supplier: Proveedor
vehicle: Vehículo created: Fecha creación
worker: Trabajador
now: Ahora
name: Nombre
new: Nuevo
comment: Comentario
observations: Observaciones
goToModuleIndex: Ir al índice del módulo
unsavedPopup: unsavedPopup:
title: Los cambios que no haya guardado se perderán title: Los cambios que no haya guardado se perderán
subtitle: ¿Seguro que quiere salir sin guardar? subtitle: ¿Seguro que quiere salir sin guardar?
createInvoiceIn: Crear factura recibida
myAccount: Mi cuenta
noOne: Nadie
maxTemperature: Máx
minTemperature: Mín
params: params:
description: Descripción
clientFk: Id cliente clientFk: Id cliente
salesPersonFk: Comercial salesPersonFk: Comercial
warehouseFk: Almacén warehouseFk: Almacén
@ -352,15 +339,20 @@ globals:
from: Desde from: Desde
to: Hasta to: Hasta
supplierFk: Proveedor supplierFk: Proveedor
supplierRef: Nº factura supplierRef: Ref. proveedor
serial: Serie serial: Serie
amount: Importe amount: Importe
awbCode: AWB awbCode: AWB
daysOnward: Días adelante daysOnward: Días adelante
packing: ITP packing: ITP
countryFk: País countryFk: País
countryCodeFk: País
companyFk: Empresa companyFk: Empresa
changePass: Cambiar contraseña
setPass: Establecer contraseña
deleteConfirmTitle: Eliminar los elementos seleccionados
changeState: Cambiar estado
raid: 'Redada {daysInForward} días'
isVies: Vies
errors: errors:
statusUnauthorized: Acceso denegado statusUnauthorized: Acceso denegado
statusInternalServerError: Ha ocurrido un error interno del servidor statusInternalServerError: Ha ocurrido un error interno del servidor
@ -397,6 +389,80 @@ cau:
subtitle: Al enviar este cau ya se envían todos los datos relacionados con el error, la sección, el usuario, etc subtitle: Al enviar este cau ya se envían todos los datos relacionados con el error, la sección, el usuario, etc
inputLabel: Explique el motivo por el que no deberia aparecer este fallo inputLabel: Explique el motivo por el que no deberia aparecer este fallo
askPrivileges: Solicitar permisos askPrivileges: Solicitar permisos
entry:
list:
newEntry: Nueva entrada
tableVisibleColumns:
created: Creación
supplierFk: Proveedor
isBooked: Asentado
isConfirmed: Confirmado
isOrdered: Pedida
companyFk: Empresa
travelFk: Envio
isExcludedFromAvailable: Inventario
invoiceAmount: Importe
summary:
commission: Comisión
currency: Moneda
invoiceNumber: Núm. factura
ordered: Pedida
booked: Contabilizada
excludedFromAvailable: Inventario
travelReference: Referencia
travelAgency: Agencia
travelShipped: F. envio
travelWarehouseOut: Alm. salida
travelDelivered: Enviada
travelLanded: F. entrega
travelReceived: Recibida
buys: Compras
stickers: Etiquetas
package: Embalaje
packing: Pack.
grouping: Group.
buyingValue: Coste
import: Importe
pvp: PVP
basicData:
travel: Envío
currency: Moneda
observation: Observación
commission: Comisión
booked: Asentado
excludedFromAvailable: Inventario
buys:
observations: Observaciónes
packagingFk: Embalaje
color: Color
printedStickers: Etiquetas impresas
notes:
observationType: Tipo de observación
latestBuys:
tableVisibleColumns:
image: Foto
itemFk: Id Artículo
weightByPiece: Peso (gramos)/tallo
isActive: Activo
family: Familia
entryFk: Entrada
freightValue: Porte
comissionValue: Comisión
packageValue: Embalaje
isIgnored: Ignorado
price2: Grouping
price3: Packing
minPrice: Min
ektFk: Ekt
packingOut: Embalaje envíos
landing: Llegada
isExcludedFromAvailable: Es inventario
params:
toShipped: Hasta
fromShipped: Desde
warehouseInFk: Alm. entrada
daysOnward: Días adelante
daysAgo: Días atras
ticket: ticket:
params: params:
ticketFk: ID de ticket ticketFk: ID de ticket
@ -453,18 +519,13 @@ ticket:
purchaseRequest: Petición de compra purchaseRequest: Petición de compra
service: Servicio service: Servicio
attender: Consignatario attender: Consignatario
consigneeStreet: Dirección
create: create:
address: Dirección address: Dirección
order: invoiceOut:
field: card:
salesPersonFk: Comercial issued: Fecha emisión
form: customerCard: Ficha del cliente
clientFk: Cliente ticketList: Listado de tickets
addressFk: Dirección
agencyModeFk: Agencia
list:
newOrder: Nuevo Pedido
summary: summary:
issued: Fecha issued: Fecha
dued: Fecha límite dued: Fecha límite
@ -475,6 +536,47 @@ order:
fee: Cuota fee: Cuota
tickets: Tickets tickets: Tickets
totalWithVat: Importe totalWithVat: Importe
globalInvoices:
errors:
chooseValidClient: Selecciona un cliente válido
chooseValidCompany: Selecciona una empresa válida
chooseValidPrinter: Selecciona una impresora válida
chooseValidSerialType: Selecciona una tipo de serie válida
fillDates: La fecha de la factura y la fecha máxima deben estar completas
invoiceDateLessThanMaxDate: La fecha de la factura no puede ser menor que la fecha máxima
invoiceWithFutureDate: Existe una factura con una fecha futura
noTicketsToInvoice: No existen tickets para facturar
criticalInvoiceError: Error crítico en la facturación proceso detenido
invalidSerialTypeForAll: El tipo de serie debe ser global cuando se facturan todos los clientes
table:
addressId: Id dirección
streetAddress: Dirección fiscal
statusCard:
percentageText: '{getPercentage}% {getAddressNumber} de {getNAddresses}'
pdfsNumberText: '{nPdfs} de {totalPdfs} PDFs'
negativeBases:
clientId: Id cliente
base: Base
active: Activo
hasToInvoice: Facturar
verifiedData: Datos comprobados
comercial: Comercial
errors:
downloadCsvFailed: Error al descargar CSV
shelving:
list:
parking: Parking
priority: Prioridad
newShelving: Nuevo Carro
summary:
recyclable: Reciclable
parking:
pickingOrder: Orden de recogida
row: Fila
column: Columna
searchBar:
info: Puedes buscar por código de parking
label: Buscar parking...
department: department:
chat: Chat chat: Chat
bossDepartment: Jefe de departamento bossDepartment: Jefe de departamento
@ -486,26 +588,6 @@ department:
hasToSendMail: Enviar fichadas por mail hasToSendMail: Enviar fichadas por mail
departmentRemoved: Departamento eliminado departmentRemoved: Departamento eliminado
worker: worker:
pageTitles:
workers: Trabajadores
list: Listado
basicData: Datos básicos
summary: Resumen
notifications: Notificaciones
workerCreate: Nuevo trabajador
department: Departamentos
pda: PDA
notes: Notas
dms: Mi documentación
pbx: Centralita
log: Historial
calendar: Calendario
timeControl: Control de horario
locker: Taquilla
balance: Balance
business: Contrato
formation: Formación
medical: Mutua
list: list:
department: Departamento department: Departamento
schedule: Horario schedule: Horario
@ -530,15 +612,6 @@ worker:
isSsDiscounted: Bonificación SS isSsDiscounted: Bonificación SS
hasMachineryAuthorized: Autorizado para maquinaria hasMachineryAuthorized: Autorizado para maquinaria
isDisable: Deshabilitado isDisable: Deshabilitado
business: Contrato
started: Antigüedad
ended: Fin
reasonEnd: Motivo finalización
department: Departamento
workerBusinessCategory: Categoria profesional
notes: Notas
workCenter: Centro
professionalCategory: Categoria profesional
notificationsManager: notificationsManager:
activeNotifications: Notificaciones activas activeNotifications: Notificaciones activas
availableNotifications: Notificaciones disponibles availableNotifications: Notificaciones disponibles
@ -585,23 +658,6 @@ worker:
debit: Debe debit: Debe
credit: Haber credit: Haber
concept: Concepto concept: Concepto
business:
tableVisibleColumns:
started: Fecha inicio
ended: Fecha fin
company: Empresa
reasonEnd: Motivo finalización
department: Departamento
professionalCategory: Categoria profesional
calendarType: Calendario laboral
workCenter: Centro
payrollCategories: Categoria contrato
occupationCode: Cotización
rate: Tarifa
businessType: Contrato
amount: Salario
basicSalary: Salario transportistas
notes: Notas
operator: operator:
numberOfWagons: Número de vagones numberOfWagons: Número de vagones
train: tren train: tren
@ -614,6 +670,7 @@ worker:
sizeLimit: Tamaño límite sizeLimit: Tamaño límite
isOnReservationMode: Modo de reserva isOnReservationMode: Modo de reserva
machine: Máquina machine: Máquina
wagon: wagon:
type: type:
submit: Guardar submit: Guardar
@ -644,8 +701,6 @@ wagon:
volume: Volumen volume: Volumen
name: Nombre name: Nombre
supplier: supplier:
search: Buscar proveedor
searchInfo: Buscar proveedor por id o nombre
list: list:
payMethod: Método de pago payMethod: Método de pago
account: Cuenta account: Cuenta
@ -653,7 +708,6 @@ supplier:
tableVisibleColumns: tableVisibleColumns:
nif: NIF/CIF nif: NIF/CIF
account: Cuenta account: Cuenta
summary: summary:
responsible: Responsable responsible: Responsable
verified: Verificado verified: Verificado
@ -712,9 +766,6 @@ supplier:
consumption: consumption:
entry: Entrada entry: Entrada
travel: travel:
search: Buscar envío
searchInfo: Buscar envío por id o nombre
id: Id
travelList: travelList:
tableVisibleColumns: tableVisibleColumns:
ref: Referencia ref: Referencia
@ -723,7 +774,6 @@ travel:
totalEntries: totalEntries:
totalEntriesTooltip: Entradas totales totalEntriesTooltip: Entradas totales
daysOnward: Días de llegada en adelante daysOnward: Días de llegada en adelante
awb: AWB
summary: summary:
entryId: Id entrada entryId: Id entrada
freight: Porte freight: Porte
@ -745,7 +795,62 @@ travel:
destination: Destino destination: Destino
thermograph: Termógrafo thermograph: Termógrafo
travelFileDescription: 'Id envío { travelId }' travelFileDescription: 'Id envío { travelId }'
carrier: Transportista item:
descriptor:
buyer: Comprador
color: Color
category: Categoría
available: Disponible
warehouseText: 'Calculado sobre el almacén de { warehouseName }'
itemDiary: Registro de compra-venta
list:
id: Identificador
stems: Tallos
category: Reino
typeName: Tipo
isActive: Activo
weightByPiece: Peso (gramos)/tallo
userName: Comprador
stemMultiplier: Multiplicador
fixedPrice:
itemFk: ID Artículo
groupingPrice: Precio grouping
packingPrice: Precio packing
hasMinPrice: Tiene precio mínimo
minPrice: Precio min
started: Inicio
ended: Fin
create:
priority: Prioridad
summary:
otherData: Otros datos
tax: IVA
botanical: Botánico
barcode: Código de barras
completeName: Nombre completo
family: Familia
stems: Tallos
multiplier: Multiplicador
buyer: Comprador
doPhoto: Hacer foto
intrastatCode: Código intrastat
ref: Referencia
relevance: Relevancia
weight: Peso (gramos)/tallo
units: Unidades/caja
expense: Gasto
generic: Genérico
recycledPlastic: Plástico reciclado
nonRecycledPlastic: Plástico no reciclado
minSalesQuantity: Cantidad mínima de venta
genus: Genus
specie: Specie
buyRequest:
requester: Solicitante
requested: Solicitado
attender: Comprador
achieved: Conseguido
concept: Concepto
components: components:
topbar: {} topbar: {}
itemsFilterPanel: itemsFilterPanel:
@ -761,11 +866,7 @@ components:
wareHouseFk: Almacén wareHouseFk: Almacén
# LatestBuysFilter # LatestBuysFilter
salesPersonFk: Comprador salesPersonFk: Comprador
supplierFk: Proveedor
visible: Visible
active: Activo active: Activo
from: Desde
to: Hasta
floramondo: Floramondo floramondo: Floramondo
showBadDates: Ver items a futuro showBadDates: Ver items a futuro
userPanel: userPanel:

View File

@ -2,7 +2,7 @@
import Navbar from 'src/components/NavBar.vue'; import Navbar from 'src/components/NavBar.vue';
</script> </script>
<template> <template>
<QLayout view="hHh LpR fFf"> <QLayout view="hHh LpR fFf" v-shortcut>
<Navbar /> <Navbar />
<RouterView></RouterView> <RouterView></RouterView>
<QFooter v-if="$q.platform.is.mobile"></QFooter> <QFooter v-if="$q.platform.is.mobile"></QFooter>

View File

@ -1,12 +1,10 @@
<script setup> <script setup>
import { Dark, Quasar } from 'quasar'; import { Dark, Quasar } from 'quasar';
import { computed, onMounted } from 'vue'; import { computed } from 'vue';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import { localeEquivalence } from 'src/i18n/index';
import quasarLang from 'src/utils/quasarLang';
import { langs } from 'src/boot/defaults/constants.js';
const { t, locale } = useI18n(); const { t, locale } = useI18n();
const userLocale = computed({ const userLocale = computed({
get() { get() {
return locale.value; return locale.value;
@ -14,9 +12,18 @@ const userLocale = computed({
set(value) { set(value) {
locale.value = value; locale.value = value;
value = localeEquivalence[value] ?? value; if (value === 'en') value = 'en-GB';
quasarLang(value); // FIXME: Dynamic imports from absolute paths are not compatible with vite:
// https://github.com/rollup/plugins/tree/master/packages/dynamic-import-vars#limitations
try {
const langList = import.meta.glob('../../node_modules/quasar/lang/*.mjs');
langList[`../../node_modules/quasar/lang/${value}.mjs`]().then((lang) => {
Quasar.lang.set(lang.default);
});
} catch (error) {
//
}
}, },
}); });
@ -28,6 +35,7 @@ const darkMode = computed({
Dark.set(value); Dark.set(value);
}, },
}); });
const langs = ['en', 'es'];
</script> </script>
<template> <template>

View File

@ -3,7 +3,6 @@ import { useI18n } from 'vue-i18n';
import { ref, computed } from 'vue'; import { ref, computed } from 'vue';
import VnTable from 'components/VnTable/VnTable.vue'; import VnTable from 'components/VnTable/VnTable.vue';
import VnSection from 'src/components/common/VnSection.vue'; import VnSection from 'src/components/common/VnSection.vue';
import exprBuilder from './Alias/AliasExprBuilder';
const tableRef = ref(); const tableRef = ref();
const { t } = useI18n(); const { t } = useI18n();
@ -32,6 +31,15 @@ const columns = computed(() => [
create: true, create: true,
}, },
]); ]);
const exprBuilder = (param, value) => {
switch (param) {
case 'search':
return /^\d+$/.test(value)
? { id: value }
: { alias: { like: `%${value}%` } };
}
};
</script> </script>
<template> <template>

View File

@ -46,7 +46,7 @@ const killSession = async ({ userId, created }) => {
<VnPaginate <VnPaginate
:data-key="urlPath" :data-key="urlPath"
ref="paginateRef" ref="paginateRef"
:user-filter="filter" :filter="filter"
:url="urlPath" :url="urlPath"
order="created DESC" order="created DESC"
auto-load auto-load

View File

@ -1,18 +0,0 @@
export default (param, value) => {
switch (param) {
case 'search':
return /^\d+$/.test(value)
? { id: value }
: {
or: [
{ name: { like: `%${value}%` } },
{ nickname: { like: `%${value}%` } },
],
};
case 'name':
case 'nickname':
return { [param]: { like: `%${value}%` } };
case 'roleFk':
return { [param]: value };
}
};

View File

@ -4,16 +4,15 @@ import { computed, ref } from 'vue';
import VnTable from 'components/VnTable/VnTable.vue'; import VnTable from 'components/VnTable/VnTable.vue';
import AccountSummary from './Card/AccountSummary.vue'; import AccountSummary from './Card/AccountSummary.vue';
import { useSummaryDialog } from 'src/composables/useSummaryDialog'; import { useSummaryDialog } from 'src/composables/useSummaryDialog';
import exprBuilder from './AccountExprBuilder.js';
import filter from './Card/AccountFilter.js';
import VnSection from 'src/components/common/VnSection.vue'; import VnSection from 'src/components/common/VnSection.vue';
import FetchData from 'src/components/FetchData.vue'; import FetchData from 'src/components/FetchData.vue';
import VnInputPassword from 'src/components/common/VnInputPassword.vue'; import VnInputPassword from 'src/components/common/VnInputPassword.vue';
const { t } = useI18n(); const { t } = useI18n();
const { viewSummary } = useSummaryDialog(); const { viewSummary } = useSummaryDialog();
const tableRef = ref(); const filter = {
include: { relation: 'role', scope: { fields: ['id', 'name'] } },
};
const dataKey = 'AccountList'; const dataKey = 'AccountList';
const roles = ref([]); const roles = ref([]);
const columns = computed(() => [ const columns = computed(() => [
@ -118,6 +117,25 @@ const columns = computed(() => [
], ],
}, },
]); ]);
function exprBuilder(param, value) {
switch (param) {
case 'search':
return /^\d+$/.test(value)
? { id: value }
: {
or: [
{ name: { like: `%${value}%` } },
{ nickname: { like: `%${value}%` } },
],
};
case 'name':
case 'nickname':
return { [param]: { like: `%${value}%` } };
case 'roleFk':
return { [param]: value };
}
}
</script> </script>
<template> <template>
<FetchData url="VnRoles" @on-fetch="(data) => (roles = data)" auto-load /> <FetchData url="VnRoles" @on-fetch="(data) => (roles = data)" auto-load />

View File

@ -1,8 +0,0 @@
export default (param, value) => {
switch (param) {
case 'search':
return /^\d+$/.test(value)
? { id: value }
: { alias: { like: `%${value}%` } };
}
};

View File

@ -1,13 +1,21 @@
<script setup> <script setup>
import { useI18n } from 'vue-i18n';
import VnCardBeta from 'components/common/VnCardBeta.vue'; import VnCardBeta from 'components/common/VnCardBeta.vue';
import AliasDescriptor from './AliasDescriptor.vue'; import AliasDescriptor from './AliasDescriptor.vue';
const { t } = useI18n();
</script> </script>
<template> <template>
<VnCardBeta <VnCardBeta
data-key="Alias" data-key="Alias"
url="MailAliases" base-url="MailAliases"
:descriptor="AliasDescriptor" :descriptor="AliasDescriptor"
search-data-key="AccountAliasList" search-data-key="AccountAliasList"
:searchbar-props="{
url: 'MailAliases',
info: t('mailAlias.searchInfo'),
label: t('mailAlias.search'),
searchUrl: 'table',
}"
/> />
</template> </template>

View File

@ -7,6 +7,7 @@ import { useQuasar } from 'quasar';
import CardDescriptor from 'components/ui/CardDescriptor.vue'; import CardDescriptor from 'components/ui/CardDescriptor.vue';
import VnLv from 'src/components/ui/VnLv.vue'; import VnLv from 'src/components/ui/VnLv.vue';
import useCardDescription from 'src/composables/useCardDescription';
import axios from 'axios'; import axios from 'axios';
import useNotify from 'src/composables/useNotify.js'; import useNotify from 'src/composables/useNotify.js';
@ -28,6 +29,9 @@ const entityId = computed(() => {
return $props.id || route.params.id; return $props.id || route.params.id;
}); });
const data = ref(useCardDescription());
const setData = (entity) => (data.value = useCardDescription(entity.alias, entity.id));
const removeAlias = () => { const removeAlias = () => {
quasar quasar
.dialog({ .dialog({
@ -52,8 +56,10 @@ const removeAlias = () => {
ref="descriptor" ref="descriptor"
:url="`MailAliases/${entityId}`" :url="`MailAliases/${entityId}`"
module="Alias" module="Alias"
data-key="Alias" @on-fetch="setData"
title="alias" data-key="aliasData"
:title="data.title"
:subtitle="data.subtitle"
> >
<template #menu> <template #menu>
<QItem v-ripple clickable @click="removeAlias()"> <QItem v-ripple clickable @click="removeAlias()">

View File

@ -1,11 +1,13 @@
<script setup> <script setup>
import { computed } from 'vue'; import { ref, computed } from 'vue';
import { useRoute } from 'vue-router'; import { useRoute } from 'vue-router';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import CardSummary from 'components/ui/CardSummary.vue'; import CardSummary from 'components/ui/CardSummary.vue';
import VnLv from 'src/components/ui/VnLv.vue'; import VnLv from 'src/components/ui/VnLv.vue';
import { useArrayData } from 'src/composables/useArrayData';
const route = useRoute(); const route = useRoute();
const { t } = useI18n(); const { t } = useI18n();
@ -16,15 +18,20 @@ const $props = defineProps({
}, },
}); });
const { store } = useArrayData('Alias');
const alias = ref(store.data);
const entityId = computed(() => $props.id || route.params.id); const entityId = computed(() => $props.id || route.params.id);
</script> </script>
<template> <template>
<CardSummary ref="summary" :url="`MailAliases/${entityId}`" data-key="Alias"> <CardSummary
<template #header="{ entity: alias }"> ref="summary"
{{ alias.id }} - {{ alias.alias }} :url="`MailAliases/${entityId}`"
</template> @on-fetch="(data) => (alias = data)"
<template #body="{ entity: alias }"> data-key="MailAliasesSummary"
>
<template #header> {{ alias.id }} - {{ alias.alias }} </template>
<template #body>
<QCard class="vn-one"> <QCard class="vn-one">
<QCardSection class="q-pa-none"> <QCardSection class="q-pa-none">
<router-link <router-link

View File

@ -69,7 +69,7 @@ const fetchAliases = () => paginateRef.value.fetch();
<VnPaginate <VnPaginate
ref="paginateRef" ref="paginateRef"
data-key="AliasUsers" data-key="AliasUsers"
:user-filter="filter" :filter="filter"
:url="urlPath" :url="urlPath"
:limit="0" :limit="0"
auto-load auto-load

View File

@ -1,20 +1,46 @@
<script setup> <script setup>
import { useRoute } from 'vue-router';
import { useI18n } from 'vue-i18n';
import VnSelect from 'src/components/common/VnSelect.vue'; import VnSelect from 'src/components/common/VnSelect.vue';
import VnSelectEnum from 'src/components/common/VnSelectEnum.vue'; import VnSelectEnum from 'src/components/common/VnSelectEnum.vue';
import FormModel from 'components/FormModel.vue'; import FormModel from 'components/FormModel.vue';
import VnInput from 'src/components/common/VnInput.vue'; import VnInput from 'src/components/common/VnInput.vue';
import { ref, watch } from 'vue';
const route = useRoute();
const { t } = useI18n();
const formModelRef = ref(null);
const accountFilter = {
where: { id: route.params.id },
fields: ['id', 'email', 'nickname', 'name', 'accountStateFk', 'packages', 'pickup'],
include: [],
};
watch(
() => route.params.id,
() => formModelRef.value.reset()
);
</script> </script>
<template> <template>
<FormModel :url-update="`VnUsers/${$route.params.id}/update-user`" model="Account"> <FormModel
ref="formModelRef"
url="VnUsers/preview"
:url-update="`VnUsers/${route.params.id}/update-user`"
:filter="accountFilter"
model="Accounts"
auto-load
@on-data-saved="formModelRef.fetch()"
>
<template #form="{ data }"> <template #form="{ data }">
<div class="q-gutter-y-sm"> <div class="q-gutter-y-sm">
<VnInput v-model="data.name" :label="$t('account.card.nickname')" /> <VnInput v-model="data.name" :label="t('account.card.nickname')" />
<VnInput v-model="data.nickname" :label="$t('account.card.alias')" /> <VnInput v-model="data.nickname" :label="t('account.card.alias')" />
<VnInput v-model="data.email" :label="$t('globals.params.email')" /> <VnInput v-model="data.email" :label="t('globals.params.email')" />
<VnSelect <VnSelect
url="Languages" url="Languages"
v-model="data.lang" v-model="data.lang"
:label="$t('account.card.lang')" :label="t('account.card.lang')"
option-value="code" option-value="code"
option-label="code" option-label="code"
/> />
@ -23,7 +49,7 @@ import VnInput from 'src/components/common/VnInput.vue';
table="user" table="user"
column="twoFactor" column="twoFactor"
v-model="data.twoFactor" v-model="data.twoFactor"
:label="$t('account.card.twoFactor')" :label="t('account.card.twoFactor')"
option-value="code" option-value="code"
option-label="code" option-label="code"
/> />

View File

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

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