Compare commits

..

No commits in common. "dev" and "hotfix_customer_salesPerson_Filter" have entirely different histories.

575 changed files with 12695 additions and 16551 deletions

View File

@ -1,516 +1,3 @@
# Version 25.00 - 2025-01-14
### Added 🆕
- chore: refs #7056 move test by:jorgep
- feat: refs #7050 7050 add object check by:Jtubau
- feat: refs #7050 7050 add test to isEmpty() by:Jtubau
- feat: refs #7056 add tests in FormModel by:jorgep
- feat: refs #7056 update route meta information and add FormModel tests by:jorgep
- feat: refs #7074 tests for fns setData(), parseDms() and showFormDialog() (7074-makeFrontTestToVnDmsList) by:Jtubau
- feat: refs #7079 created VnLocation front test by:provira
- feat: refs #7189 add Accept-Language header to axios requests by:jorgep
- feat: refs #7924 add custom inspection checkbox and localization support by:jgallego
- feat: refs #7924 update custom inspection label for clarity in English and Spanish locales by:jgallego
- feat: refs #8004 enhance FetchedTags component with column support and styling updates by:pablone
- feat: refs #8004 hide rightFilter by:pablone
- feat: refs #8246 added new field in list by:Jon
- feat: refs #8266 added descriptor to item name by:jtubau
- feat: refs #8293 add zone filter by:Jtubau
- feat: refs #8293 include zone data in each record by:Jtubau
- fix: refs #8004 more list style issues by:pablone
- fix: refs #8004 some style issues on all list by:pablone
- style: refs #8004 update layout and styling in FetchedTags and ItemList components by:pablone
- style: update CustomerBalance.vue to set label color by:jgallego
### Changed 📦
- perf: order by:alexm
- perf: redirect transition list to card by:alexm
- perf: refs #8201 onDataSaved fetch by:Jon
- perf: revert processData by:alexm
- perf: simplify if by:alexm
- perf: simplify if (perf_redirectTransition) by:alexm
- refactor: item fixedPrice by:Jon
- refactor: refs #7050 refactorize by:jtubau
- refactor: refs #7050 removed blank spaces by:jtubau
- refactor: refs #7052 move EditTableCellValueForm tests to a new location and enhance test coverage by:jgallego
- refactor: refs #7052 remove unnecessary console logs from EditTableCellValueForm tests by:jgallego
- refactor: refs #7074 move dms constant to global scope by:Jtubau
- refactor: refs #7079 removed useless code by:provira
- refactor: refs #7924 simplify custom inspection icon rendering in ExtraCommunity.vue by:jgallego
- refactor: refs #8004 remove console log from CardSummary component on mount by:pablone
- refactor: refs #8004 remove consoleLogs by:pablone
- refactor: refs #8004 remove unused stateStore import in InvoiceInList.vue by:pablone
- refactor: refs #8004 remove unused travelFilterRef and chip definition in TravelList.vue by:pablone
- refactor: refs #8004 replace VnSelect with VnSelectWorker in CustomerList component by:pablone
- refactor: refs #8201 added onMounted to stablish the value to show icons by:Jon
- refactor: refs #8201 deleted condition by:Jon
- refactor: refs #8201 deleted log by:Jon
- refactor: refs #8201 deleted logs by:Jon
- refactor: refs #8266 8266 change expedition item name by:Jtubau
- refactor: refs #8266 change expedition label by:Jtubau
- refactor: refs #8293 remove redundant attributes by:Jtubau
- refactor: refs #8320 changed folder names from "specs" to "**tests**" by:provira
- refactor: refs #8320 moved front tests to their respective sections by:provira
- refactor: refs #8813 removed unused class property by:provira
### Fixed 🛠️
- fix: discount class by:PAU ROVIRA ROSALENY
- fix: duplicate transalation after test to dev by:alexm
- fix: fix translations by:carlossa
- fix: redirect to sales when confirming lines by:Jon
- fix: refs #7050 delete import added by mistake by:Jtubau
- fix: refs #7133 handleSalesModelValue function to handle empty input by:jorgep
- fix: refs #7189 update user language on sessionStorage by:jorgep
- fix: refs #7935 remove unused 'companyFk' column from InvoiceInList component by:jorgep
- fix: refs #8004 more list style issues by:pablone
- fix: refs #8004 some style issues on all list by:pablone
- fix: refs #8004 update label for daysOnward in TravelFilter component and add translations by:pablone
- fix: refs #8004 vnTable card with and add permanent labels by:pablone
- fix: refs #8201 added onDataSaved emi to refetch when cahnges are made by:Jon
- fix: refs #8201 use arrayData to fix the error by:Jon
- fix: refs #8314 space between label and value by:jtubau
- fix: refs #8813 fixed ClaimLines format by:provira
- fix: update button sizes in ExtraCommunity.vue for better visibility by:jgallego
- perf: revert processData by:alexm
- refactor: item fixedPrice by:Jon
# Version 24.52 - 2024-01-07
### Added 🆕
- chore: refs #8197 remove console log by:alexm
- chore: refs #8197 replace name by:alexm
- chore: refs #8197 unnecessary file by:alexm
- feat: #8110 apply mixin in quasar components by:Javier Segarra
- feat(Account & AccountRole): refs #8197 add VnCardMain by:alexm
- feat: addDptoLink by:Jtubau
- feat: added restore ticket function in ticket descriptor menu by:Jon
- feat: add support service wip by:jorgep
- feat: focus menu searchbar by:jorgep
- feat: make additional data object by:jorgep
- feat: message to grant access by:jorgep
- feat: refs #6583 add default param by:jorgep
- feat: refs #6583 add destination opt filter by:jorgep
- feat: refs #6583 add icon by:jorgep
- feat: refs #6583 add locale by:jorgep
- feat: refs #7072 added test to computed fn total by:Jtubau
- feat: refs #7235 update invoice out global form to fetch config based on serial type by:jgallego
- feat: refs #7301 add exclude inventory supplier from list by:pablone
- feat: refs #7301 enhance VnDateBadge styling and improve ItemLastEntries component by:pablone
- feat: refs #7882 Added distribution point by:guillermo
- feat: refs #7882 Added longitude & latitude by:guillermo
- feat: refs #7936 add autocomplete on tab fn by:jorgep
- feat: refs #7936 add company filter by:jorgep
- feat: refs #7936 add currency check before fetching by:jorgep
- feat: refs #7936 add dueDated field by:jorgep
- feat: refs #7936 add number validation to VnInputNumber & new daysAgo filter in InvoiceInFilter by:jorgep
- feat: refs #7936 add optionCaption by:jorgep
- feat: refs #7936 add row click navigation to InvoiceInSerial by:jorgep
- feat: refs #7936 add unit tests by:jorgep
- feat: refs #7936 add useAccountShortToStandard composable by:jorgep
- feat: refs #7936 calculate exchange & update taxable base by:jorgep
- feat: refs #7936 enhance downloadFile function to support opening in a new tab by:jorgep
- feat: refs #7936 enhance getTotal fn & add unit tests by:jorgep
- feat: refs #7936 enhance vn-select by:jorgep
- feat: refs #7936 improve optionLabel logic in InvoiceInVat component for better handling of numeric values by:jorgep
- feat: refs #7936 limit decimal places by:jorgep
- feat: refs #7936 make fields required by:jorgep
- feat: refs #7936 show country code & isVies fields by:jorgep
- feat: refs #7936 show id & value by:jorgep
- feat: refs #7936 simplify optionLabel wip by:jorgep
- feat: refs #7936 update 'isVies' label to use global translation key by:jorgep
- feat: refs #7936 update option labels in InvoiceIn components for better clarity by:jorgep
- feat: refs #7936 use default invoice data by:jorgep
- feat: refs #8001 change request by:robert
- feat: refs #8001 ticketExpeditionGrafana by:robert
- feat: refs #8194 created VnSelectWorker component and use it in Lilium by:Jon
- feat: refs #8197 better leftMenu and VnCardMain improvements by:alexm
- feat: refs #8197 default leftMenu by:alexm
- feat: refs #8197 default sectionName by:alexm
- feat: refs #8197 keepData in VnSection by:alexm
- feat: refs #8197 vnTableFilter by:alexm
- feat: refs #8197 working rightMenu by:alexm
- feat: remove re-fetch when add element by:Javier Segarra
- feat: remove search after category by:Javier Segarra
- feat: requested changes in item module by:Jon
- feat: update quantity by:Javier Segarra
- feat(VnPaginate): refs #8197 hold data when change to Card by:alexm
### Changed 📦
- perf: #6896 REMOVE COMMENTS by:Javier Segarra
- perf: qFormMixin by:Javier Segarra
- perf: qFormMixin improvement by:Javier Segarra
- perf: refs #8194 select worker component by:Jon
- perf: refs #8197 perf by:alexm
- perf: remove comments by:Javier Segarra
- perf: remove unused variables (origin/warmfix_noUsedVars) by:Javier Segarra
- refactor: added again search emit by:Jon
- refactor: add useCau composable by:jorgep
- refactor: deleted log by:Jon
- refactor: deleted onUnmounted code by:Jon
- refactor: deleted useless hidden tag by:Jon
- refactor: deleted warnings and corrected itemTag by:Jon
- refactor: drop logic by:jorgep
- refactor: ignore params when searching by id on searchbar (origin/VnSearchbar-SearchRemoveParams) by:Jon
- refactor: log error by:Jon
- refactor: refs #7936 locale by:jorgep
- refactor: refs #7936 simplify getTotal fn by:jorgep
- refactor: refs #7936 update label capitalization and replace invoice type options by:jorgep
- refactor: refs #8194 deleted unnecessary label by:Jon
- refactor: refs #8194 modified select worker template by:Jon
- refactor: refs #8194 modified select worker to allow no one filter from monitor ticket by:Jon
- refactor: refs #8194 moved translation to the correct place by:Jon
- refactor: refs #8194 requested changes by:Jon
- refactor: refs #8194 structure changes in component and related files by:Jon
- refactor: refs #8197 adapt AccountAcls to VnCardMain by:alexm
- refactor: refs #8197 adapt AccountAlias by:alexm
- refactor: refs #8197 adapt Ticket to VnCardMain by:alexm
- refactor: refs #8197 backward compatible (8197-VnCardMain_backwardCompatibility) by:alexm
- refactor: refs #8197 rename VnSectionMain to VnModule and VnCardMain to VnSection by:alexm
- refactor: refs #8288 changed invoice out spanish translation by:provira
- refactor: use locale keys by:jorgep
- refactor: use teleport to avoid qdrawer overlapping by:Jon
- refactor: use VnSelectWorker by:Jon
### Fixed 🛠️
- fix: account by:carlossa
- fix: account create by:carlossa
- fix: accountList create by:carlossa
- fix(AccountList): use $refs by:alexm
- fix: add data-key by:alexm
- fix: addLocales by:Jtubau
- fix: dated field by:Jon
- fix: e2e by:jorgep
- fix: fix department filter by:carlossa
- fix: fixed translations by:Javier Segarra
- fix: fixed translations by:provira
- fix: get total from api by:Javier Segarra
- fix: handle non-object options by:jorgep
- fix: monitorPayMethodFilter by:carlossa
- fix: orderBy priority by:Javier Segarra
- fix: prevent null by:jorgep
- fix: redirection vnTable VnTableFilter by:alexm
- fix: refs #6389 fix filter trad by:carlossa
- fix: refs #6389 fix front, filters, itp by:carlossa
- fix: refs #6389 front add packing filter by:carlossa
- fix: refs #6389 front by:carlossa
- fix: refs #6389 front filters by:carlossa
- fix: refs #6389 ipt by:carlossa
- fix: refs #6389 packing by:carlossa
- fix: refs #6583 update checkbox for filtering by destination in TicketAdvanceFilter by:jorgep
- fix: refs #7031 add test e2e by:carlossa
- fix: refs #7031 fix zoneTest by:carlossa
- fix: refs #7301 unnecessary console logs from ItemLastEntries.vue by:pablone
- fix: refs #7936 changes by:jorgep
- fix: refs #7936 decimal places & locale by:jorgep
- fix: refs #7936 descriptor & dueday by:jorgep
- fix: refs #7936 exclude disabled els on tab by:jorgep
- fix: refs #7936 format tax calculation to two decimal places by:jorgep
- fix: refs #7936 improve error handling by:jorgep
- fix: refs #7936 redirection by:jorgep
- fix: refs #7936 rollback by:jorgep
- fix: refs #7936 serial by:jorgep
- fix: refs #7936 tabulation wip by:jorgep
- fix: refs #7936 test by:jorgep
- fix: refs #8114 clean by:carlossa
- fix: refs #8114 fix agencyList by:carlossa
- fix: refs #8114 fix lifeCycle hooks by:carlossa
- fix: refs #8114 fix pr by:carlossa
- fix: refs #8114 fix removeAddress by:carlossa
- fix: refs #8114 orderList by:carlossa
- fix: refs #8114 remove logs by:carlossa
- fix: refs #8197 mapKey (origin/8197-perf_vnTableInside, 8197-perf_vnTableInside) by:alexm
- fix: refs #8197 redirection (8197-perf_redirection) by:alexm
- fix: refs #8197 staticParams and redirect by:alexm
- fix: refs #8197 vnPaginate onFetch emit by:alexm
- fix: refs #8197 vnPaginate when change :id by:alexm
- fix: refs #8197 vnTableFilter in vnTable by:alexm
- fix: refs #8315 ticketBoxing test by:alexm
- fix: remove url by:carlossa
- fix: rollback by:jorgep
- fix: test by:jorgep
- fix(VnDmsList): refs #8197 add mapKey by:alexm
- revert: refs #8197 arrayData changes by:alexm
- test: refs #8197 fix e2e by:alexm
- test: refs #8315 fix claimDevelopment fixtures by:alexm
- test: refs #8315 fix clientList by:alexm
- test: refs #8315 fix VnSelect in e2e by:alexm
# Version 24.50 - 2024-12-10
### Added 🆕
- feat: add reportFileName option by:Javier Segarra
- feat: all clients just with global series by:jgallego
- feat: improve Merge branch 'test' into dev by:Javier Segarra
- feat: manual invoice in two lines by:jgallego
- feat: manualInvoice with address by:jgallego
- feat: randomize functions and example by:Javier Segarra
- feat: refs #6999 added search when user tabs on a filter with value by:Jon
- feat: refs #6999 added tab to search in VnTable filter by:Jon
- feat: refs #7346 #7346 improve form by:Javier Segarra
- feat: refs #7346 address ordered by:jgallego
- feat: refs #7346 radioButton by:jgallego
- feat: refs #7346 style radioButton by:jgallego
- feat: refs #7346 traducciones en cammelCase (7346-manualInvoice) by:jgallego
- feat: refs #8038 added new functionality in VnSelect and refactor styles by:Jon
- feat: refs #8061 #8061 updates by:Javier Segarra
- feat: refs #8087 reactive data by:jorgep
- feat: refs #8087 refs#8087 Redadas en travel by:Carlos Andrés
- feat: refs #8138 add component ticket problems by:pablone
- feat: refs #8163 add max length and more tests by:wbuezas
- feat: refs #8163 add prop by:wbuezas
- feat: refs #8163 add VnInput insert functionality and e2e test by:wbuezas
- feat: refs #8163 limit with maxLength by:Javier Segarra
- feat: refs #8163 maxLength SupplierFD account by:Javier Segarra
- feat: refs #8163 maxLengthVnInput by:Javier Segarra
- feat: refs #8163 use VnAccountNumber in VnAccountNumber by:Javier Segarra
- feat: refs #8166 show notification by:jorgep
### Changed 📦
- feat: refs #8038 added new functionality in VnSelect and refactor styles by:Jon
- perf: add dataCy by:Javier Segarra
- perf: refs #7346 #7346 Imrpove interface dialog by:Javier Segarra
- perf: refs #7346 #7346 use v-show instead v-if by:Javier Segarra
- perf: refs #8036 currentFilter by:alexm
- perf: refs #8061 filter autonomy by:Javier Segarra
- perf: refs #8061 solve conflicts and random posCode it by:Javier Segarra
- perf: refs #8061 use opts from VnSelect by:Javier Segarra
- perf: refs #8163 #8061 createNewPostCodeForm by:Javier Segarra
- perf: remove console by:Javier Segarra
- perf: remove timeout by:Javier Segarra
- perf: test command fillInForm by:Javier Segarra
- refactor: refs #8162 remove comment by:wbuezas
- refactor: remove unnecesary things by:wbuezas
### Fixed 🛠️
- fix: #8016 fetching data by:Javier Segarra
- fix: icons by:jgallego
- fix: refs #7229 download file by:jorgep
- fix: refs #7229 remove catch by:jorgep
- fix: refs #7229 set url by:jorgep
- fix: refs #7229 test by:jorgep
- fix: refs #7229 url by:jorgep
- fix: refs #7229 url + test by:jorgep
- fix: refs #7304 7304 clean warning by:carlossa
- fix: refs #7304 fix list by:carlossa
- fix: refs #7304 fix warning by:carlossa
- fix: refs #7346 traslations by:jgallego
- fix: refs #7529 add save by:carlossa
- fix: refs #7529 fix e2e by:carlossa
- fix: refs #7529 fix front by:carlossa
- fix: refs #7529 fix scss by:carlossa
- fix: refs #7529 fix te2e by:carlossa
- fix: refs #7529 fix workerPit e2e by:carlossa
- fix: refs #7529 front by:carlossa
- fix: refs #8036 apply exprBuilder after save filters by:alexm
- fix: refs #8036 only add where when required by:alexm
- fix: refs #8038 solve conflicts by:Jon
- fix: refs #8061 improve code dependencies (origin/8061_improve_newCP) by:Javier Segarra
- fix: refs #8138 move component from ui folder by:pablone
- fix: refs #8138 sme minor issues by:pablone
- fix: refs #8163 #8061 createNewPostCodeForm by:Javier Segarra
- fix: refs #8163 minor problem when keypress by:Javier Segarra
- fix: refs #8166 show zone error by:jorgep
- fix: removed selectedClient by:jgallego
- refs #7529 fix workerPit by:carlossa
- revert: refs #8061 test #8061 updates by:Javier Segarra
- test: fix own test by:Javier Segarra
- test: refs #8162 #8162 fix TicketList spec by:Javier Segarra
# Version 24.48 - 2024-11-25
### Added 🆕
- chore: correct checkNotification (fix_customer_issues) by:alexm
- chore: perf (warmFix_order_equalSalix) by:alexm
- chore: refs #6818 add spaces by:jorgep
- chore: refs #6818 drop useless code & comment by:jorgep
- chore: refs #7273 sticky add btn & refactor by:jorgep
- chore: refs #7524 fix test by:jorgep
- chore: refs #8039 not required by:alexm
- chore: refs #8078 fiz tests by:jorgep
- chore: refs #8078 rollback ref by:jorgep
- chore: remove console.log (warmFix_invoiceOut_Global) by:alexm
- chore: typo (fix_itemType-redirection) by:alexm
- feat: #6943 use openURL quasar by:Javier Segarra
- feat: #7782 add cypress report by:Javier Segarra
- feat: #7782 cypress.config watchForFileChanges by:Javier Segarra
- feat: #7782 npm run resetDatabase by:Javier Segarra
- feat: #7782 waitUntil domContentLoad by:Javier Segarra
- feat: added composable to confirm orders by:Jon
- feat: add /reports in gitignore (warmFix_reports_in_gitignore) by:alexm
- feat: apply changes for customerModule by:Javier Segarra
- feat: disabled buttons by:Javier Segarra
- feat: move buttons to DescriptorMenu by:Javier Segarra
- feat: refs #6818 add icon by:jorgep
- feat: refs #6818 fetch url & default channel by:jorgep
- feat: refs #6818 saysimple integration by:jorgep
- feat: refs #6839 module searching (6839-addSearchMenu) by:jorgep
- feat: refs #6839 normalize search by:jorgep
- feat: refs #6919 sync entry data by:jorgep
- feat: refs #7006 itemType basic data new inputs by:guillermo
- feat: refs #7006 itemTypeLog added by:guillermo
- feat: refs #7193 modified parking to use the scope and corrected small errors by:Jon
- feat: refs #7206 added inactive label and corrected minor errors by:Jon
- feat: refs #7308 #7308 remove warnings related to useSession by:Javier Segarra
- feat: refs #7349 usa back con permisos by:jgallego
- feat: refs #7524 add front test by:jorgep
- feat: refs #7874 improve vn-notes ui by:jorgep
- feat: refs #7970 notify changes by:Jon
- feat(): refs #8039 canceledError not notify by:alexm
- feat: refs #8039 notify error unify by:alexm
- feat: refs #8039 show duplicate request in local by:alexm
- feat: refs #8078 add shortcut multi selection by:jorgep
- feat: refs #8078 add tests by:jorgep
- feat: refs#8087 Redadas en travel by:Carlos Andrés
- feat: refs #8087 Traspasar redadas a travels by:Carlos Andrés
- feat: remove comments by:Javier Segarra
- feat(Supplier): add companySize by:alexm
- feat: use composable to unify logic by:Javier Segarra
- feat(VnInput): empty to null by:alexm
- feat(VnSelect): order data equal salix by:alexm
- feat(VnSelect): refs #7136 add scroll (7136-vnSelect_paginate_simplify_2) by:alexm
### Changed 📦
- chore: perf (warmFix_order_equalSalix) by:alexm
- chore: refs #7273 sticky add btn & refactor by:jorgep
- fix: better performance (warmFix_accountAcls) by:alexm
- perf: minor bugs detected by:Javier Segarra
- perf: refs #6943 #6943 merge command by:Javier Segarra
- perf: refs #7283 #7283 declare composable inst4ead code duplicated by:Javier Segarra
- perf: refs #7283 #7283 handle composable i18n by:Javier Segarra
- perf: refs #7283 #7283 handle i18n by:Javier Segarra
- perf: refs #7283 #7283 i18n params by:Javier Segarra
- perf: refs #7308 #7308 remove comments by:Javier Segarra
- perf: remove appendParams by:Javier Segarra
- perf: use const in VnLocation by:Javier Segarra
- perf: use required instead :required="true" by:Javier Segarra
- refactor: apply QPopupProxy by:wbuezas
- refactor: changed confirmOrder directory by:Jon
- refactor: change keyup.enter for update:model-value by:wbuezas
- refactor(InvoiceInBasicData): use VnDms by:alexm
- refactor: modified composable by:Jon
- refactor: refs #6818 change channel source by:jorgep
- refactor: refs #6818 channel logic by:jorgep
- refactor: refs #6919 export filter by:jorgep
- refactor: refs #7132 1st wave of changes in global translations files by:Jon
- refactor: refs #7132 account's module translations by:Jon
- refactor: refs #7132 customer's module translations by:Jon
- refactor: refs #7132 deleted pageTitles repeated by:Jon
- refactor: refs #7132 delete duplicate translations' keys by:Jon
- refactor: refs #7132 deleted useless code by:Jon
- refactor: refs #7132 global translations files changed by:Jon
- refactor: refs #7266 Changed method name by:guillermo
- refactor: refs #7950 Created cmr model by:guillermo
- refactor: refs #7970 added emit by:Jon
- refactor: refs #7970 refactored VnConfirm to emit events by:Jon
- refactor: refs #8185 modified LeftMenu to avoid duplicates by:Jon
- refactor: remove unused variable by:wbuezas
- refactor: revert catalog changes by:Jon
- refactor: small change by:wbuezas
- test: refactor e2e by:alexm
- test: refs #8039 add hasNotify and, refactor: agencyWorkCenter test by:alexm
### Fixed 🛠️
- chore: refs #7524 fix test by:jorgep
- fix: better performance (warmFix_accountAcls) by:alexm
- fix: catalog view category and type filter by:wbuezas
- fix: category and tags filters by:Jon
- fix: changed route.query by:Jon
- fix: change type vnput by:Javier Segarra
- fix(ClaimList): stateCode orderBy priority by:alexm
- fix: entryFilters by:carlossa
- fix: filter panel by:Jon
- fix(InvoiceOutGlobal): parallelism by:alexm
- fix: itemBotanical by:Javier Segarra
- fix: itemType redirection and fix filters by:alexm
- fix: logout spec (warmFix_logout.spec) by:alexm
- fix: merge errors by:alexm
- fix: order catalog by:wbuezas
- fix: order catalog fixes by:wbuezas
- fix: refs #6818 use right icon by:jorgep
- fix: refs #6896 fixed module problems by:Jon
- fix: refs #7193 fixed e2e test by:Jon
- fix: refs #7206 deleted duplicate code by:Jon
- fix: refs #7273 use same filter by:jorgep
- fix: refs #7283 #7283 bugs by:Javier Segarra
- fix: refs #7283 #7283 ItemDiary subToolbar by:Javier Segarra
- fix: refs #7283 #7283 ItemSummary bugs by:Javier Segarra
- fix: refs #7283 Account image resolution by:guillermo
- fix: refs #7283 css by:jorgep
- fix: refs #7283 filter by:carlossa
- fix: refs #7283 fix image by:carlossa
- fix: refs #7283 fix pr by:carlossa
- fix: refs #7283 fix preview by:carlossa
- fix: refs #7283 fix required by:carlossa
- fix: refs #7283 item filters by:carlossa
- fix: refs #7283 itemtype fix by:carlossa
- fix: refs #7283 order translation by:carlossa
- fix: refs #7283 preview by:carlossa
- fix: refs #7283 tooltips !Item by:Javier Segarra
- fix: refs #7306 clean warning by:carlossa
- fix: refs #7310 clean warning by:carlossa
- fix: refs #7323 locale #7396 by:jorgep
- fix: refs #7323 show advanced fields by:jorgep
- fix: refs #7349 dependencia no usada by:jgallego
- fix: refs #7524 e2e & worker module by:jorgep
- fix: refs #7874 add title by:jorgep
- fix: refs #7874 show name by:jorgep
- fix: refs #7943 use correct data-key by:jorgep
- fix: refs #7943 use summary by:jorgep
- fix: refs #8039 bad tests by:alexm
- fix: refs #8039 o not handle unnecessary errors by:alexm
- fix: refs #8078 e2e #7970 by:jorgep
- fix: refs #8078 handleSelection by:jorgep
- fix: refs #8078 improve cy command (8078-enableMultiSelection) by:jorgep
- fix: refs #8078 improve handleSelection by:jorgep
- fix: reset category by:wbuezas
- fix: tag chips by:Jon
- fix: vnSearchbar spec (warmFix_vnSearchBar.spec) by:alexm
- fix(VnSelect): setOptions when applyFilter by:alexm
- fix: worker test e2e by:Jon
- Merge branch 'dev' into fix_customer_issues by:Javier Segarra
- refactor: revert catalog changes by:Jon
- refs #7283 fix conflicts by:carlossa
- refs #7283 fix descriptorproxy by:carlossa
- refs #7283 fixedPrice by:carlossa
- refs #7283 fixedPrices by:carlossa
- refs #7283 fix itemFixed by:carlossa
- refs #7283 fix itemFixedPrice by:carlossa
- refs #7283 fix itemMigration by:carlossa
- refs #7283 fix itemMigration list filters by:carlossa
- refs #7283 fix items by:carlossa
- refs #7283 fix items error get images by:carlossa
- refs #7283 fix items images by:carlossa
- refs #7283 fix request by:carlossa
- refs #7283 fix searchbar by:carlossa
- refs #7283 fix viewSummary by:carlossa
- refs #7283 fix yml list basicData by:carlossa
- refs #7283 itemRequest fix by:carlossa
- refs #7283 itemRequest fix deny by:carlossa
- refs #7283 itemRequest fix reload by:carlossa
- refs #72983 fix filters by:carlossa
- revert: commit by:Javier Segarra
- revert e57a253c6f649382da187d1129449d265fb26d3b by:Javier Segarra
- test: #8162 fix clientList spec by:Javier Segarra
- test: #8162 fix vnLocation spec by:Javier Segarra
- test: fix arrayData by:Javier Segarra
- test: fix e2e by:alexm
- test: fix e2e by:Javier Segarra
- test: refs #8039 fix WorkerNotification e2e by:alexm
- test: refs #8039 fix ZoneWarehouse e2e by:alexm
- warmfix: ItemLastEntries to date (origin/warmfix_itemLastEntriesFilter) by:Javier Segarra
# Version 24.40 - 2024-10-02
### Added 🆕

6
Jenkinsfile vendored
View File

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

View File

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

View File

@ -1,17 +1,16 @@
{
"name": "salix-front",
"version": "25.04.0",
"version": "24.44.0",
"description": "Salix frontend",
"productName": "Salix",
"author": "Verdnatura",
"private": true,
"packageManager": "pnpm@8.15.1",
"scripts": {
"resetDatabase": "cd ../salix && gulp docker",
"lint": "eslint --ext .js,.vue ./",
"format": "prettier --write \"**/*.{js,vue,scss,html,md,json}\" --ignore-path .gitignore",
"test:e2e": "cypress open",
"test:e2e:ci": "npm run resetDatabase && cd ../salix-front && cypress run",
"test:e2e:ci": "cd ../salix && gulp docker && cd ../salix-front && cypress run",
"test": "echo \"See package.json => scripts for available tests.\" && exit 0",
"test:unit": "vitest",
"test:unit:ci": "vitest run",
@ -25,7 +24,6 @@
"axios": "^1.4.0",
"chromium": "^3.0.3",
"croppie": "^2.6.5",
"moment": "^2.30.1",
"pinia": "^2.1.3",
"quasar": "^2.14.5",
"validator": "^13.9.0",
@ -44,7 +42,6 @@
"@vue/test-utils": "^2.4.4",
"autoprefixer": "^10.4.14",
"cypress": "^13.6.6",
"cypress-mochawesome-reporter": "^3.8.2",
"eslint": "^8.41.0",
"eslint-config-prettier": "^8.8.0",
"eslint-plugin-cypress": "^2.13.3",

View File

@ -20,9 +20,6 @@ dependencies:
croppie:
specifier: ^2.6.5
version: 2.6.5
moment:
specifier: ^2.30.1
version: 2.30.1
pinia:
specifier: ^2.1.3
version: 2.1.7(typescript@5.5.4)(vue@3.4.19)
@ -73,9 +70,6 @@ devDependencies:
cypress:
specifier: ^13.6.6
version: 13.6.6
cypress-mochawesome-reporter:
specifier: ^3.8.2
version: 3.8.2(cypress@13.6.6)(mocha@10.7.3)
eslint:
specifier: ^8.41.0
version: 8.56.0
@ -835,8 +829,8 @@ packages:
vue-i18n:
optional: true
dependencies:
'@intlify/message-compiler': 11.0.0-rc.1
'@intlify/shared': 11.0.0-rc.1
'@intlify/message-compiler': 10.0.0-beta.5
'@intlify/shared': 10.0.0-beta.5
jsonc-eslint-parser: 1.4.1
source-map: 0.6.1
vue-i18n: 9.9.1(vue@3.4.19)
@ -850,11 +844,11 @@ packages:
'@intlify/message-compiler': 9.9.1
'@intlify/shared': 9.9.1
/@intlify/message-compiler@11.0.0-rc.1:
resolution: {integrity: sha512-TGw2uBfuTFTegZf/BHtUQBEKxl7Q/dVGLoqRIdw8lFsp9g/53sYn5iD+0HxIzdYjbWL6BTJMXCPUHp9PxDTRPw==}
/@intlify/message-compiler@10.0.0-beta.5:
resolution: {integrity: sha512-hLLchnM1dmtSEruerkzvU9vePsLqBXz3RU85SCx/Vd12fFQiymP+/5Rn9MJ8MyfLmIOLDEx4PRh+/GkIQP6oog==}
engines: {node: '>= 16'}
dependencies:
'@intlify/shared': 11.0.0-rc.1
'@intlify/shared': 10.0.0-beta.5
source-map-js: 1.0.2
dev: true
@ -865,8 +859,8 @@ packages:
'@intlify/shared': 9.9.1
source-map-js: 1.0.2
/@intlify/shared@11.0.0-rc.1:
resolution: {integrity: sha512-8tR1xe7ZEbkabTuE/tNhzpolygUn9OaYp9yuYAF4MgDNZg06C3Qny80bes2/e9/Wm3aVkPUlCw6WgU7mQd0yEg==}
/@intlify/shared@10.0.0-beta.5:
resolution: {integrity: sha512-g9bq5Y1bOcC9qxtNk4UWtF3sXm6Wh0fGISb7vD5aLyF7yQv7ZFjxQjJzBP2GqG/9+PAGYutqjP1GGadNqFtyAQ==}
engines: {node: '>= 16'}
dev: true
@ -890,7 +884,7 @@ packages:
optional: true
dependencies:
'@intlify/bundle-utils': 4.0.0(vue-i18n@9.9.1)
'@intlify/shared': 11.0.0-rc.1
'@intlify/shared': 10.0.0-beta.5
'@rollup/pluginutils': 4.2.1
'@vue/compiler-sfc': 3.4.19
debug: 4.3.4(supports-color@8.1.1)
@ -2005,10 +1999,6 @@ packages:
dependencies:
fill-range: 7.0.1
/browser-stdout@1.3.1:
resolution: {integrity: sha512-qhAVI1+Av2X7qelOfAIYwXONood6XlZE/fXaBSmW/T5SzLAmCgzi+eiWE7fUvbHaeNBQH13UftjpXxsfLkMpgw==}
dev: true
/browserslist@4.23.0:
resolution: {integrity: sha512-QW8HiM1shhT2GuzkvklfjcKDiWFXHOeFCIA/huJPwHsslwcydgk7X+z2zXpEijP98UCY7HbubZt5J2Zgvf0CaQ==}
engines: {node: ^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7}
@ -2116,16 +2106,6 @@ packages:
upper-case: 1.1.3
dev: true
/camelcase@5.3.1:
resolution: {integrity: sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==}
engines: {node: '>=6'}
dev: true
/camelcase@6.3.0:
resolution: {integrity: sha512-Gmy6FhYlCY7uOElZUSbxo2UCDH8owEk996gkbrpsgGtrJLM3J7jGxl9Ic7Qwwj4ivOE5AWZWRMecDdF7hqGjFA==}
engines: {node: '>=10'}
dev: true
/camelcase@7.0.1:
resolution: {integrity: sha512-xlx1yCK2Oc1APsPXDL2LdlNP6+uu8OCDdhOBSVT279M/S+y75O30C2VuD8T2ogdePBBl7PfPF4504tnLgX3zfw==}
engines: {node: '>=14.16'}
@ -2275,22 +2255,6 @@ packages:
engines: {node: '>= 10'}
dev: true
/cliui@6.0.0:
resolution: {integrity: sha512-t6wbgtoCXvAzst7QgXxJYqPt0usEfbgQdftEPbLL/cvv6HPE5VgvqCuAIDR0NgU52ds6rFwqrgakNLrHEjCbrQ==}
dependencies:
string-width: 4.2.3
strip-ansi: 6.0.1
wrap-ansi: 6.2.0
dev: true
/cliui@7.0.4:
resolution: {integrity: sha512-OcRE68cOsVMXp1Yvonl/fzkQOyjLSu/8bhPDfQt0e0/Eb283TKP20Fs2MqoPsr9SwA595rRCA+QMzYc9nBP+JQ==}
dependencies:
string-width: 4.2.3
strip-ansi: 6.0.1
wrap-ansi: 7.0.0
dev: true
/cliui@8.0.1:
resolution: {integrity: sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==}
engines: {node: '>=12'}
@ -2594,23 +2558,6 @@ packages:
/csstype@3.1.3:
resolution: {integrity: sha512-M1uQkMl8rQK/szD0LNhtqxIPLpimGm8sOBwU7lLnCpSbTyY3yeU1Vc7l4KT5zT4s/yOxHH5O7tIuuLOCnLADRw==}
/cypress-mochawesome-reporter@3.8.2(cypress@13.6.6)(mocha@10.7.3):
resolution: {integrity: sha512-oJZkNzhNmN9ZD+LmZyFuPb8aWaIijyHyqYh52YOBvR6B6ckfJNCHP3A98a+/nG0H4t46CKTNwo+wNpMa4d2kjA==}
engines: {node: '>=14'}
hasBin: true
peerDependencies:
cypress: '>=6.2.0'
dependencies:
commander: 10.0.1
cypress: 13.6.6
fs-extra: 10.1.0
mochawesome: 7.1.3(mocha@10.7.3)
mochawesome-merge: 4.3.0
mochawesome-report-generator: 6.2.0
transitivePeerDependencies:
- mocha
dev: true
/cypress@13.6.6:
resolution: {integrity: sha512-S+2S9S94611hXimH9a3EAYt81QM913ZVA03pUmGDfLTFa5gyp85NJ8dJGSlEAEmyRsYkioS1TtnWtbv/Fzt11A==}
engines: {node: ^16.0.0 || ^18.0.0 || >=20.0.0}
@ -2680,10 +2627,6 @@ packages:
time-zone: 1.0.0
dev: true
/dateformat@4.6.3:
resolution: {integrity: sha512-2P0p0pFGzHS5EMnhdxQi7aJN+iMheud0UhG4dlE1DLAlvL8JHjJJTX/CSm4JXwV0Ka5nGk3zC5mcb5bUQUxxMA==}
dev: true
/dayjs@1.11.10:
resolution: {integrity: sha512-vjAczensTgRcqDERK0SR2XMwsF/tSvnvlv6VcF2GIhg6Sx4yOIt/irsr1RDJsKiIyBzJDpCoXiWWq28MqH2cnQ==}
dev: true
@ -2733,29 +2676,6 @@ packages:
ms: 2.1.2
supports-color: 8.1.1
/debug@4.3.7(supports-color@8.1.1):
resolution: {integrity: sha512-Er2nc/H7RrMXZBFCEim6TCmMk02Z8vLC2Rbi1KEBggpo0fS6l0S1nnapwmIi3yW/+GOJap1Krg4w0Hg80oCqgQ==}
engines: {node: '>=6.0'}
peerDependencies:
supports-color: '*'
peerDependenciesMeta:
supports-color:
optional: true
dependencies:
ms: 2.1.3
supports-color: 8.1.1
dev: true
/decamelize@1.2.0:
resolution: {integrity: sha512-z2S+W9X73hAUUki+N+9Za2lBlun89zigOyGrsax+KUQ6wKW4ZoWpEYBkGhQjwAjjDCkWxhY0VKEhk8wzY7F5cA==}
engines: {node: '>=0.10.0'}
dev: true
/decamelize@4.0.0:
resolution: {integrity: sha512-9iE1PgSik9HeIIw2JO94IidnE3eBoQrFJ3w7sFuzSX4DpmZ3v5sZpUiV5Swcf6mQEF+Y0ru8Neo+p+nyh2J+hQ==}
engines: {node: '>=10'}
dev: true
/decompress-response@6.0.0:
resolution: {integrity: sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ==}
engines: {node: '>=10'}
@ -2838,11 +2758,6 @@ packages:
resolution: {integrity: sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==}
engines: {node: '>= 0.8', npm: 1.2.8000 || >= 1.4.16}
/diff@5.2.0:
resolution: {integrity: sha512-uIFDxqpRZGZ6ThOk84hEfqWoHx2devRFvpTZcTHur85vImfaxUbTW9Ryh4CpCuDnToOP1CEtXKIgytHBPVff5A==}
engines: {node: '>=0.3.1'}
dev: true
/doctrine@3.0.0:
resolution: {integrity: sha512-yS+Q5i3hBf7GBkd4KG8a7eBNNWNGLTaEwwYWUijIYM7zrlYDM0BFXHjjPWlWZ1Rg7UaddZeIDmi9jF3HmqiQ2w==}
engines: {node: '>=6.0.0'}
@ -3635,14 +3550,6 @@ packages:
transitivePeerDependencies:
- supports-color
/find-up@4.1.0:
resolution: {integrity: sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==}
engines: {node: '>=8'}
dependencies:
locate-path: 5.0.0
path-exists: 4.0.0
dev: true
/find-up@5.0.0:
resolution: {integrity: sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==}
engines: {node: '>=10'}
@ -3739,15 +3646,6 @@ packages:
resolution: {integrity: sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==}
dev: true
/fs-extra@10.1.0:
resolution: {integrity: sha512-oRXApq54ETRj4eMiFzGnHWGy+zo5raudjuxN0b8H7s/RU2oW0Wvsx9O0ACRN/kRq9E8Vu/ReskGB5o3ji+FzHQ==}
engines: {node: '>=12'}
dependencies:
graceful-fs: 4.2.11
jsonfile: 6.1.0
universalify: 2.0.1
dev: true
/fs-extra@11.2.0:
resolution: {integrity: sha512-PmDi3uwK5nFuXh7XDTlVnS17xJS7vW36is2+w3xcv8SVxiB4NyATf4ctkVY5bkSjX0Y4nbvZCq1/EjtEyr9ktw==}
engines: {node: '>=14.14'}
@ -3756,15 +3654,6 @@ packages:
jsonfile: 6.1.0
universalify: 2.0.1
/fs-extra@7.0.1:
resolution: {integrity: sha512-YJDaCJZEnBmcbw13fvdAM9AwNOJwOzrE4pqMqBq5nFiEqXUqHwlK4B+3pUw6JNvfSPtX05xFHtYy/1ni01eGCw==}
engines: {node: '>=6 <7 || >=8'}
dependencies:
graceful-fs: 4.2.11
jsonfile: 4.0.0
universalify: 0.1.2
dev: true
/fs-extra@9.1.0:
resolution: {integrity: sha512-hcg3ZmepS30/7BSFqRvoo3DOMQu7IjqxO5nCDt+zM9XWjb33Wg7ziNT+Qvqbuc3+gWpzO02JubVyk2G4Zvo1OQ==}
engines: {node: '>=10'}
@ -3786,10 +3675,6 @@ packages:
dev: true
optional: true
/fsu@1.1.1:
resolution: {integrity: sha512-xQVsnjJ/5pQtcKh+KjUoZGzVWn4uNkchxTF6Lwjr4Gf7nQr8fmUfhKJ62zE77+xQg9xnxi5KUps7XGs+VC986A==}
dev: true
/function-bind@1.1.2:
resolution: {integrity: sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==}
@ -3890,18 +3775,6 @@ packages:
once: 1.4.0
path-is-absolute: 1.0.1
/glob@8.1.0:
resolution: {integrity: sha512-r8hpEjiQEYlF2QU0df3dS+nxxSIreXQS1qRhMJM0Q5NDdR386C7jb7Hwwod8Fgiuex+k0GFjgft18yvxm5XoCQ==}
engines: {node: '>=12'}
deprecated: Glob versions prior to v9 are no longer supported
dependencies:
fs.realpath: 1.0.0
inflight: 1.0.6
inherits: 2.0.4
minimatch: 5.1.6
once: 1.4.0
dev: true
/global-directory@4.0.1:
resolution: {integrity: sha512-wHTUcDUoZ1H5/0iVqEudYW4/kAlN5cZ3j/bXn0Dpbizl9iaUVeWSHqiOjsgk6OW2bkLclbBjzewBz6weQ1zA2Q==}
engines: {node: '>=18'}
@ -4316,11 +4189,6 @@ packages:
resolution: {integrity: sha512-Fd4gABb+ycGAmKou8eMftCupSir5lRxqf4aD/vd0cD2qc4HL07OjCeuHMr8Ro4CoMaeCKDB0/ECBOVWjTwUvPQ==}
engines: {node: '>=8'}
/is-plain-obj@2.1.0:
resolution: {integrity: sha512-YWnfyRwxL/+SsrWYfOpUtz5b3YD+nyfkHvjbcanzk8zgyO4ASD67uVMRt8k5bM4lLMDnXfriRhOpemw+NfT1eA==}
engines: {node: '>=8'}
dev: true
/is-plain-obj@3.0.0:
resolution: {integrity: sha512-gwsOE28k+23GP1B6vFl1oVh/WOzmawBrKwo5Ev6wMKzPkaXaCDIQKzLnvsA42DRlbVTWorkgTKIviAKCWkfUwA==}
engines: {node: '>=10'}
@ -4493,12 +4361,6 @@ packages:
resolution: {integrity: sha512-AilxAyFOAcK5wA1+LeaySVBrHsGQvUFCDWXKpZjzaL0PqW+xfBOttn8GNtWKFWqneyMZj41MWF9Kl6iPWLwgOA==}
dev: true
/jsonfile@4.0.0:
resolution: {integrity: sha512-m6F1R3z8jjlf2imQHS2Qez5sjKWQzbuuhuJ/FKYFRZvPE3PuHcSMVZzfsLhGVOkfd20obL5SWEBew5ShlquNxg==}
optionalDependencies:
graceful-fs: 4.2.11
dev: true
/jsonfile@6.1.0:
resolution: {integrity: sha512-5dgndWOriYSm5cnYaJNhalLNDKOqFwyDB/rr1E9ZsGciGvKPs8R2xYGCacuf3z6K1YKDz182fd+fY3cn3pMqXQ==}
dependencies:
@ -4590,13 +4452,6 @@ packages:
engines: {node: '>=14'}
dev: true
/locate-path@5.0.0:
resolution: {integrity: sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==}
engines: {node: '>=8'}
dependencies:
p-locate: 4.1.0
dev: true
/locate-path@6.0.0:
resolution: {integrity: sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==}
engines: {node: '>=10'}
@ -4631,26 +4486,10 @@ packages:
resolution: {integrity: sha512-C5N2Z3DgnnKr0LOpv/hKCgKdb7ZZwafIrsesve6lmzvZIRZRGaZ/l6Q8+2W7NaT+ZwO3fFlSCzCzrDCFdJfZ4g==}
dev: true
/lodash.isempty@4.4.0:
resolution: {integrity: sha512-oKMuF3xEeqDltrGMfDxAPGIVMSSRv8tbRSODbrs4KGsRRLEhrW8N8Rd4DRgB2+621hY8A8XwwrTVhXWpxFvMzg==}
dev: true
/lodash.isfunction@3.0.9:
resolution: {integrity: sha512-AirXNj15uRIMMPihnkInB4i3NHeb4iBtNg9WRWuK2o31S+ePwwNmDPaTL3o7dTJ+VXNZim7rFs4rxN4YU1oUJw==}
dev: true
/lodash.isobject@3.0.2:
resolution: {integrity: sha512-3/Qptq2vr7WeJbB4KHUSKlq8Pl7ASXi3UG6CMbBm8WRtXi8+GHm7mKaU3urfpSEzWe2wCIChs6/sdocUsTKJiA==}
dev: true
/lodash.isplainobject@4.0.6:
resolution: {integrity: sha512-oSXzaWypCMHkPC3NvBEaPHf0KsA5mvPrOPgQWDsbg8n7orZ290M0BmC/jgRZ4vcJ6DTAhjrsSYgdsW/F+MFOBA==}
dev: true
/lodash.isstring@4.0.1:
resolution: {integrity: sha512-0wJxfxH1wgO3GrbuP+dTTk7op+6L41QCXbGINEmD+ny/G/eCqGzxyCsh7159S+mgDDcoarnBw6PC1PS5+wUGgw==}
dev: true
/lodash.kebabcase@4.1.1:
resolution: {integrity: sha512-N8XRTIMMqqDgSy4VLKPnJ/+hpGZN+PHQiJnSenYqPaVV/NCqEogTnAdZLQiGKhxX+JCs8waWq2t1XHWKOmlY8g==}
dev: true
@ -4713,13 +4552,6 @@ packages:
wrap-ansi: 6.2.0
dev: true
/loose-envify@1.4.0:
resolution: {integrity: sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==}
hasBin: true
dependencies:
js-tokens: 4.0.0
dev: true
/loupe@2.3.7:
resolution: {integrity: sha512-zSMINGVYkdpYSOBmLi0D1Uo7JU9nVdQKrHxC8eYlV+9YKK9WePqAlL7lSlorG/U2Fw1w0hTBmaa/jrQ3UbPHtA==}
dependencies:
@ -4890,83 +4722,6 @@ packages:
ufo: 1.4.0
dev: true
/mocha@10.7.3:
resolution: {integrity: sha512-uQWxAu44wwiACGqjbPYmjo7Lg8sFrS3dQe7PP2FQI+woptP4vZXSMcfMyFL/e1yFEeEpV4RtyTpZROOKmxis+A==}
engines: {node: '>= 14.0.0'}
hasBin: true
dependencies:
ansi-colors: 4.1.3
browser-stdout: 1.3.1
chokidar: 3.6.0
debug: 4.3.7(supports-color@8.1.1)
diff: 5.2.0
escape-string-regexp: 4.0.0
find-up: 5.0.0
glob: 8.1.0
he: 1.2.0
js-yaml: 4.1.0
log-symbols: 4.1.0
minimatch: 5.1.6
ms: 2.1.3
serialize-javascript: 6.0.2
strip-json-comments: 3.1.1
supports-color: 8.1.1
workerpool: 6.5.1
yargs: 16.2.0
yargs-parser: 20.2.9
yargs-unparser: 2.0.0
dev: true
/mochawesome-merge@4.3.0:
resolution: {integrity: sha512-1roR6g+VUlfdaRmL8dCiVpKiaUhbPVm1ZQYUM6zHX46mWk+tpsKVZR6ba98k2zc8nlPvYd71yn5gyH970pKBSw==}
engines: {node: '>=10.0.0'}
hasBin: true
dependencies:
fs-extra: 7.0.1
glob: 7.2.3
yargs: 15.4.1
dev: true
/mochawesome-report-generator@6.2.0:
resolution: {integrity: sha512-Ghw8JhQFizF0Vjbtp9B0i//+BOkV5OWcQCPpbO0NGOoxV33o+gKDYU0Pr2pGxkIHnqZ+g5mYiXF7GMNgAcDpSg==}
hasBin: true
dependencies:
chalk: 4.1.2
dateformat: 4.6.3
escape-html: 1.0.3
fs-extra: 10.1.0
fsu: 1.1.1
lodash.isfunction: 3.0.9
opener: 1.5.2
prop-types: 15.8.1
tcomb: 3.2.29
tcomb-validation: 3.4.1
validator: 13.11.0
yargs: 17.7.2
dev: true
/mochawesome@7.1.3(mocha@10.7.3):
resolution: {integrity: sha512-Vkb3jR5GZ1cXohMQQ73H3cZz7RoxGjjUo0G5hu0jLaW+0FdUxUwg3Cj29bqQdh0rFcnyV06pWmqmi5eBPnEuNQ==}
peerDependencies:
mocha: '>=7'
dependencies:
chalk: 4.1.2
diff: 5.2.0
json-stringify-safe: 5.0.1
lodash.isempty: 4.4.0
lodash.isfunction: 3.0.9
lodash.isobject: 3.0.2
lodash.isstring: 4.0.1
mocha: 10.7.3
mochawesome-report-generator: 6.2.0
strip-ansi: 6.0.1
uuid: 8.3.2
dev: true
/moment@2.30.1:
resolution: {integrity: sha512-uEmtNhbDOrWPFS+hdjFCBfy9f2YoyzRpwcl+DqpC6taX21FzsTLQVbMV/W7PzNSX6x/bhC1zA3c2UQ5NzH6how==}
dev: false
/ms@2.0.0:
resolution: {integrity: sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==}
@ -5115,11 +4870,6 @@ packages:
is-wsl: 2.2.0
dev: false
/opener@1.5.2:
resolution: {integrity: sha512-ur5UIdyw5Y7yEj9wLzhqXiy6GZ3Mwx0yGI+5sMn2r0N0v3cKJvUmFH5yPP+WXh9e0xfyzyJX95D8l088DNFj7A==}
hasBin: true
dev: true
/optionator@0.9.3:
resolution: {integrity: sha512-JjCoypp+jKn1ttEFExxhetCKeJt9zhAgAve5FXHixTvFDW/5aEktX9bufBKLRRMdU7bNtpLfcGu94B3cdEJgjg==}
engines: {node: '>= 0.8.0'}
@ -5165,13 +4915,6 @@ packages:
engines: {node: '>=12.20'}
dev: false
/p-limit@2.3.0:
resolution: {integrity: sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==}
engines: {node: '>=6'}
dependencies:
p-try: 2.2.0
dev: true
/p-limit@3.1.0:
resolution: {integrity: sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==}
engines: {node: '>=10'}
@ -5186,13 +4929,6 @@ packages:
yocto-queue: 1.0.0
dev: true
/p-locate@4.1.0:
resolution: {integrity: sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==}
engines: {node: '>=8'}
dependencies:
p-limit: 2.3.0
dev: true
/p-locate@5.0.0:
resolution: {integrity: sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==}
engines: {node: '>=10'}
@ -5214,11 +4950,6 @@ packages:
aggregate-error: 3.1.0
dev: true
/p-try@2.2.0:
resolution: {integrity: sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==}
engines: {node: '>=6'}
dev: true
/package-json@8.1.1:
resolution: {integrity: sha512-cbH9IAIJHNj9uXi196JVsRlt7cHKak6u/e6AkL/bkRelZ7rlL3X1YKxsZwa36xipOEKAsdtmaG6aAJoM1fx2zA==}
engines: {node: '>=14.16'}
@ -5408,14 +5139,6 @@ packages:
engines: {node: '>=0.4.0'}
dev: false
/prop-types@15.8.1:
resolution: {integrity: sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg==}
dependencies:
loose-envify: 1.4.0
object-assign: 4.1.1
react-is: 16.13.1
dev: true
/proto-list@1.2.4:
resolution: {integrity: sha512-vtK/94akxsTMhe0/cbfpR+syPuszcuwhqVjJq26CuNDgFGj682oRBXOP5MJpv2r7JtE8MsiepGIqvvOTBwn2vA==}
@ -5519,10 +5242,6 @@ packages:
strip-json-comments: 2.0.1
dev: false
/react-is@16.13.1:
resolution: {integrity: sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==}
dev: true
/react-is@17.0.2:
resolution: {integrity: sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w==}
dev: true
@ -5609,10 +5328,6 @@ packages:
engines: {node: '>=0.10.0'}
dev: true
/require-main-filename@2.0.0:
resolution: {integrity: sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==}
dev: true
/requires-port@1.0.0:
resolution: {integrity: sha512-KigOCHcocU3XODJxsu8i/j8T9tzT4adHiecwORRQ0ZZFcp7ahwXuRU1m+yuO90C5ZUyGeGfocHDI14M3L3yDAQ==}
@ -5858,10 +5573,6 @@ packages:
transitivePeerDependencies:
- supports-color
/set-blocking@2.0.0:
resolution: {integrity: sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw==}
dev: true
/set-function-length@1.2.1:
resolution: {integrity: sha512-j4t6ccc+VsKwYHso+kElc5neZpjtq9EnRICFZtWyBsLojhmeF/ZBd/elqm22WJh/BziDe/SBiOeAt0m2mfLD0g==}
engines: {node: '>= 0.4'}
@ -6118,16 +5829,6 @@ packages:
readable-stream: 3.6.2
dev: true
/tcomb-validation@3.4.1:
resolution: {integrity: sha512-urVVMQOma4RXwiVCa2nM2eqrAomHROHvWPuj6UkDGz/eb5kcy0x6P0dVt6kzpUZtYMNoAqJLWmz1BPtxrtjtrA==}
dependencies:
tcomb: 3.2.29
dev: true
/tcomb@3.2.29:
resolution: {integrity: sha512-di2Hd1DB2Zfw6StGv861JoAF5h/uQVu/QJp2g8KVbtfKnoHdBQl5M32YWq6mnSYBQ1vFFrns5B1haWJL7rKaOQ==}
dev: true
/text-extensions@2.4.0:
resolution: {integrity: sha512-te/NtwBwfiNRLf9Ijqx3T0nlqZiQ2XrrtBvu+cLL8ZRrGkO0NHTug8MYFKyoSrv/sHTaSKfilUkizV6XhxMJ3g==}
engines: {node: '>=8'}
@ -6347,11 +6048,6 @@ packages:
crypto-random-string: 4.0.0
dev: false
/universalify@0.1.2:
resolution: {integrity: sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg==}
engines: {node: '>= 4.0.0'}
dev: true
/universalify@0.2.0:
resolution: {integrity: sha512-CJ1QgKmNg3CwvAv/kOFmtnEN05f0D/cn9QntgNOQlQF9dgvVTHj3t+8JPdjqawCHk7V/KA+fbUqzZ9XWhcqPUg==}
engines: {node: '>= 4.0.0'}
@ -6441,6 +6137,7 @@ packages:
/validator@13.11.0:
resolution: {integrity: sha512-Ii+sehpSfZy+At5nPdnyMhx78fEoPDkR2XW/zimHEL3MyGJQOCQ7WeP20jPYRz7ZCpcKLB21NxuXHF3bxjStBQ==}
engines: {node: '>= 0.10'}
dev: false
/vary@1.1.2:
resolution: {integrity: sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==}
@ -6787,10 +6484,6 @@ packages:
engines: {node: '>=12'}
dev: true
/which-module@2.0.1:
resolution: {integrity: sha512-iBdZ57RDvnOR9AGBhML2vFZf7h8vmBjhoaZqODJBFWHVtKkDmKuHai3cx5PgVMrX5YDNp27AofYbAwctSS+vhQ==}
dev: true
/which@2.0.2:
resolution: {integrity: sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==}
engines: {node: '>= 8'}
@ -6818,10 +6511,6 @@ packages:
resolution: {integrity: sha512-CC1bOL87PIWSBhDcTrdeLo6eGT7mCFtrg0uIJtqJUFyK+eJnzl8A1niH56uu7KMa5XFrtiV+AQuHO3n7DsHnLQ==}
dev: true
/workerpool@6.5.1:
resolution: {integrity: sha512-Fs4dNYcsdpYSAfVxhnl1L5zTksjvOJxtC5hzMNl+1t9B8hTJTdKDyZ5ju7ztgPy+ft9tBFXoOlDNiOT9WUXZlA==}
dev: true
/wrap-ansi@6.2.0:
resolution: {integrity: sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA==}
engines: {node: '>=8'}
@ -6870,10 +6559,6 @@ packages:
engines: {node: '>=12'}
dev: true
/y18n@4.0.3:
resolution: {integrity: sha512-JKhqTOwSrqNA1NY5lSztJ1GrBiUodLMmIZuLiDaMRJ+itFd+ABVE8XBjOvIWL+rSqNDC74LCSFmlb/U4UZ4hJQ==}
dev: true
/y18n@5.0.8:
resolution: {integrity: sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==}
engines: {node: '>=10'}
@ -6899,64 +6584,11 @@ packages:
engines: {node: '>= 6'}
dev: true
/yargs-parser@18.1.3:
resolution: {integrity: sha512-o50j0JeToy/4K6OZcaQmW6lyXXKhq7csREXcDwk2omFPJEwUNOVtJKvmDr9EI1fAJZUyZcRF7kxGBWmRXudrCQ==}
engines: {node: '>=6'}
dependencies:
camelcase: 5.3.1
decamelize: 1.2.0
dev: true
/yargs-parser@20.2.9:
resolution: {integrity: sha512-y11nGElTIV+CT3Zv9t7VKl+Q3hTQoT9a1Qzezhhl6Rp21gJ/IVTW7Z3y9EWXhuUBC2Shnf+DX0antecpAwSP8w==}
engines: {node: '>=10'}
dev: true
/yargs-parser@21.1.1:
resolution: {integrity: sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==}
engines: {node: '>=12'}
dev: true
/yargs-unparser@2.0.0:
resolution: {integrity: sha512-7pRTIA9Qc1caZ0bZ6RYRGbHJthJWuakf+WmHK0rVeLkNrrGhfoabBNdue6kdINI6r4if7ocq9aD/n7xwKOdzOA==}
engines: {node: '>=10'}
dependencies:
camelcase: 6.3.0
decamelize: 4.0.0
flat: 5.0.2
is-plain-obj: 2.1.0
dev: true
/yargs@15.4.1:
resolution: {integrity: sha512-aePbxDmcYW++PaqBsJ+HYUFwCdv4LVvdnhBy78E57PIor8/OVvhMrADFFEDh8DHDFRv/O9i3lPhsENjO7QX0+A==}
engines: {node: '>=8'}
dependencies:
cliui: 6.0.0
decamelize: 1.2.0
find-up: 4.1.0
get-caller-file: 2.0.5
require-directory: 2.1.1
require-main-filename: 2.0.0
set-blocking: 2.0.0
string-width: 4.2.3
which-module: 2.0.1
y18n: 4.0.3
yargs-parser: 18.1.3
dev: true
/yargs@16.2.0:
resolution: {integrity: sha512-D1mvvtDG0L5ft/jGWkLpG1+m0eQxOfaBvTNELraWj22wSVUMWxZUvYgJYcKh6jGGIkJFhH4IZPQhR4TKpc8mBw==}
engines: {node: '>=10'}
dependencies:
cliui: 7.0.4
escalade: 3.1.2
get-caller-file: 2.0.5
require-directory: 2.1.1
string-width: 4.2.3
y18n: 5.0.8
yargs-parser: 20.2.9
dev: true
/yargs@17.7.2:
resolution: {integrity: sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w==}
engines: {node: '>=12'}

View File

@ -3,12 +3,12 @@ import { useSession } from 'src/composables/useSession';
import { Router } from 'src/router';
import useNotify from 'src/composables/useNotify.js';
import { useStateQueryStore } from 'src/stores/useStateQueryStore';
import { i18n } from 'src/boot/i18n';
const session = useSession();
const { notify } = useNotify();
const stateQuery = useStateQueryStore();
const baseUrl = '/api/';
axios.defaults.baseURL = baseUrl;
const axiosNoError = axios.create({ baseURL: baseUrl });
@ -16,7 +16,6 @@ const onRequest = (config) => {
const token = session.getToken();
if (token.length && !config.headers.Authorization) {
config.headers.Authorization = token;
config.headers['Accept-Language'] = i18n.global.locale.value;
}
stateQuery.add(config);
return config;
@ -40,7 +39,37 @@ const onResponse = (response) => {
const onResponseError = (error) => {
stateQuery.remove(error.config);
if (session.isLoggedIn() && error.response?.status === 401) {
let message = '';
const response = error.response;
const responseData = response && response.data;
const responseError = responseData && response.data.error;
if (responseError) {
message = responseError.message;
}
switch (response?.status) {
case 422:
if (error.name == 'ValidationError')
message +=
' "' +
responseError.details.context +
'.' +
Object.keys(responseError.details.codes).join(',') +
'"';
break;
case 500:
message = 'errors.statusInternalServerError';
break;
case 502:
message = 'errors.statusBadGateway';
break;
case 504:
message = 'errors.statusGatewayTimeout';
break;
}
if (session.isLoggedIn() && response?.status === 401) {
session.destroy(false);
const hash = window.location.hash;
const url = hash.slice(1);
@ -49,6 +78,8 @@ const onResponseError = (error) => {
return Promise.reject(error);
}
notify(message, 'negative');
return Promise.reject(error);
};

View File

@ -1,11 +1,9 @@
import { boot } from 'quasar/wrappers';
import { createI18n } from 'vue-i18n';
import messages from 'src/i18n';
import { useState } from 'src/composables/useState';
const user = useState().getUser();
const i18n = createI18n({
locale: user.value.lang || navigator.language || navigator.userLanguage,
locale: navigator.language || navigator.userLanguage,
fallbackLocale: 'en',
globalInjection: true,
messages,

View File

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

View File

@ -1,51 +1,30 @@
function focusFirstInput(input) {
input.focus();
}
import { getCurrentInstance } from 'vue';
export default {
mounted: function () {
const that = this;
const form = document.querySelector('.q-form#formModel');
if (!form) return;
try {
const inputsFormCard = form.querySelectorAll(
`input:not([disabled]):not([type="checkbox"])`
);
if (inputsFormCard.length) {
focusFirstInput(inputsFormCard[0]);
const vm = getCurrentInstance();
if (vm.type.name === 'QForm') {
if (!['searchbarForm', 'filterPanelForm'].includes(this.$el?.id)) {
// TODO: AUTOFOCUS IS NOT FOCUSING
const that = this;
this.$el.addEventListener('keyup', function (evt) {
if (evt.key === 'Enter') {
const input = evt.target;
if (input.type == 'textarea' && evt.shiftKey) {
evt.preventDefault();
let { selectionStart, selectionEnd } = input;
input.value =
input.value.substring(0, selectionStart) +
'\n' +
input.value.substring(selectionEnd);
selectionStart = selectionEnd = selectionStart + 1;
return;
}
evt.preventDefault();
that.onSubmit();
}
});
}
const textareas = document.querySelectorAll(
'textarea:not([disabled]), [contenteditable]:not([disabled])'
);
if (textareas.length) {
focusFirstInput(textareas[textareas.length - 1]);
}
const inputs = document.querySelectorAll(
'form#formModel input:not([disabled]):not([type="checkbox"])'
);
const input = inputs[0];
if (!input) return;
focusFirstInput(input);
} catch (error) {
console.error(error);
}
form.addEventListener('keyup', function (evt) {
if (evt.key === 'Enter' && !that.$attrs['prevent-submit']) {
const input = evt.target;
if (input.type == 'textarea' && evt.shiftKey) {
evt.preventDefault();
let { selectionStart, selectionEnd } = input;
input.value =
input.value.substring(0, selectionStart) +
'\n' +
input.value.substring(selectionEnd);
selectionStart = selectionEnd = selectionStart + 1;
return;
}
evt.preventDefault();
that.onSubmit();
}
});
},
};

View File

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

View File

@ -9,6 +9,8 @@ import VnRow from 'components/ui/VnRow.vue';
import FormModelPopup from './FormModelPopup.vue';
import { useState } from 'src/composables/useState';
defineProps({ showEntityField: { type: Boolean, default: true } });
const emit = defineEmits(['onDataSaved']);
const { t } = useI18n();
const bicInputRef = ref(null);
@ -16,16 +18,17 @@ const state = useState();
const customer = computed(() => state.get('customer'));
const countriesFilter = {
fields: ['id', 'name', 'code'],
};
const bankEntityFormData = reactive({
name: null,
bic: null,
countryFk: customer.value?.countryFk,
id: null,
});
const countriesFilter = {
fields: ['id', 'name', 'code'],
};
const countriesOptions = ref([]);
const onDataSaved = (...args) => {
@ -41,6 +44,7 @@ onMounted(async () => {
<template>
<FetchData
url="Countries"
:filter="countriesFilter"
auto-load
@on-fetch="(data) => (countriesOptions = data)"
/>
@ -50,7 +54,6 @@ onMounted(async () => {
:title="t('title')"
:subtitle="t('subtitle')"
:form-initial-data="bankEntityFormData"
:filter="countriesFilter"
@on-data-saved="onDataSaved"
>
<template #form-inputs="{ data, validate }">
@ -82,13 +85,7 @@ onMounted(async () => {
:rules="validate('bankEntity.countryFk')"
/>
</div>
<div
v-if="
countriesOptions.find((c) => c.id === data.countryFk)?.code ==
'ES'
"
class="col"
>
<div v-if="showEntityField" class="col">
<VnInput
:label="t('id')"
v-model="data.id"

View File

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

View File

@ -17,6 +17,10 @@ const $props = defineProps({
type: Number,
default: null,
},
provinces: {
type: Array,
default: () => [],
},
});
const { t } = useI18n();
@ -40,23 +44,19 @@ const onDataSaved = (...args) => {
url-create="towns"
model="city"
@on-data-saved="onDataSaved"
data-cy="newCityForm"
>
<template #form-inputs="{ data, validate }">
<VnRow>
<VnInput
:label="t('Name')"
:label="t('Names')"
v-model="data.name"
:rules="validate('city.name')"
required
data-cy="cityName"
/>
<VnSelectProvince
:province-selected="$props.provinceSelected"
:country-fk="$props.countryFk"
v-model="data.provinceFk"
required
data-cy="provinceCity"
:provinces="$props.provinces"
/>
</VnRow>
</template>

View File

@ -1,5 +1,5 @@
<script setup>
import { reactive, ref } from 'vue';
import { reactive, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import FetchData from 'components/FetchData.vue';
@ -21,14 +21,13 @@ const postcodeFormData = reactive({
provinceFk: null,
townFk: null,
});
const townsFetchDataRef = ref(false);
const townFilter = ref({});
const countriesRef = ref(false);
const townsFetchDataRef = ref(null);
const provincesFetchDataRef = ref(null);
const countriesOptions = ref([]);
const provincesOptions = ref([]);
const townsOptions = ref([]);
const town = ref({});
const countryFilter = ref({});
function onDataSaved(formData) {
const newPostcode = {
@ -40,85 +39,110 @@ function onDataSaved(formData) {
({ id }) => id === formData.provinceFk
);
newPostcode.province = provinceObject?.name;
const countryObject = countriesRef.value.opts.find(
const countryObject = countriesOptions.value.find(
({ id }) => id === formData.countryFk
);
newPostcode.country = countryObject?.name;
emit('onDataSaved', newPostcode);
}
async function setCountry(countryFk, data) {
data.townFk = null;
data.provinceFk = null;
data.countryFk = countryFk;
await fetchTowns();
}
// Province
async function setProvince(id, data) {
if (data.provinceFk === id) return;
const newProvince = provincesOptions.value.find((province) => province.id == id);
if (newProvince) data.countryFk = newProvince.countryFk;
postcodeFormData.provinceFk = id;
await fetchTowns();
}
async function onProvinceCreated(data) {
postcodeFormData.provinceFk = data.id;
}
function provinceByCountry(countryFk = postcodeFormData.countryFk) {
return provincesOptions.value
.filter((province) => province.countryFk === countryFk)
.map(({ id }) => id);
}
// Town
async function handleTowns(data) {
townsOptions.value = data;
}
function setTown(newTown, data) {
town.value = newTown;
data.provinceFk = newTown?.provinceFk ?? newTown;
data.countryFk = newTown?.province?.countryFk ?? newTown;
}
async function onCityCreated(newTown, formData) {
await provincesFetchDataRef.value.fetch();
newTown.province = provincesOptions.value.find(
(province) => province.id === newTown.provinceFk
);
formData.townFk = newTown;
setTown(newTown, formData);
}
async function fetchTowns(countryFk = postcodeFormData.countryFk) {
if (!countryFk) return;
const provinces = postcodeFormData.provinceFk
? [postcodeFormData.provinceFk]
: provinceByCountry();
townFilter.value.where = {
provinceFk: {
inq: provinces,
},
};
await townsFetchDataRef.value?.fetch();
function setTown(newTown, data) {
if (!newTown) return;
town.value = newTown;
data.provinceFk = newTown.provinceFk;
data.countryFk = newTown.province.countryFk;
}
async function filterTowns(name) {
if (name !== '') {
townFilter.value.where = {
name: {
like: `%${name}%`,
},
};
await townsFetchDataRef.value?.fetch();
async function setProvince(id, data) {
const newProvince = provincesOptions.value.find((province) => province.id == id);
if (!newProvince) return;
data.countryFk = newProvince.countryFk;
}
async function onProvinceCreated(data) {
await provincesFetchDataRef.value.fetch({
where: { countryFk: postcodeFormData.countryFk },
});
postcodeFormData.provinceFk.value = data.id;
}
watch(
() => [postcodeFormData.countryFk],
async (newCountryFk, oldValueFk) => {
if (Array.isArray(newCountryFk)) {
newCountryFk = newCountryFk[0];
}
if (Array.isArray(oldValueFk)) {
oldValueFk = oldValueFk[0];
}
if (!!oldValueFk && newCountryFk !== oldValueFk) {
postcodeFormData.provinceFk = null;
postcodeFormData.townFk = null;
}
if (oldValueFk !== newCountryFk) {
await provincesFetchDataRef.value.fetch({
where: {
countryFk: newCountryFk,
},
});
await townsFetchDataRef.value.fetch({
where: {
provinceFk: {
inq: provincesOptions.value.map(({ id }) => id),
},
},
});
}
}
);
watch(
() => postcodeFormData.provinceFk,
async (newProvinceFk, oldValueFk) => {
if (Array.isArray(newProvinceFk)) {
newProvinceFk = newProvinceFk[0];
}
if (newProvinceFk !== oldValueFk) {
await townsFetchDataRef.value.fetch({
where: { provinceFk: newProvinceFk },
});
}
}
);
async function handleProvinces(data) {
provincesOptions.value = data;
}
async function handleTowns(data) {
townsOptions.value = data;
}
async function handleCountries(data) {
countriesOptions.value = data;
}
</script>
<template>
<FetchData
ref="provincesFetchDataRef"
@on-fetch="handleProvinces"
:sort-by="['name ASC']"
:limit="30"
auto-load
url="Provinces/location"
/>
<FetchData
ref="townsFetchDataRef"
:sort-by="['name ASC']"
:limit="30"
:filter="townFilter"
@on-fetch="handleTowns"
auto-load
url="Towns/location"
@ -140,13 +164,10 @@ async function filterTowns(name) {
v-model="data.code"
:rules="validate('postcode.code')"
clearable
required
data-cy="locationPostcode"
/>
<VnSelectDialog
:label="t('City')"
@update:model-value="(value) => setTown(value, data)"
@filter="filterTowns"
:tooltip="t('Create city')"
v-model="data.townFk"
:options="townsOptions"
@ -155,8 +176,7 @@ async function filterTowns(name) {
:rules="validate('postcode.city')"
:acls="[{ model: 'Town', props: '*', accessType: 'WRITE' }]"
:emit-value="false"
required
data-cy="locationTown"
:clearable="true"
>
<template #option="{ itemProps, opt }">
<QItem v-bind="itemProps">
@ -173,6 +193,7 @@ async function filterTowns(name) {
<CreateNewCityForm
:country-fk="data.countryFk"
:province-selected="data.provinceFk"
:provinces="provincesOptions"
@on-data-saved="
(_, requestResponse) =>
onCityCreated(requestResponse, data)
@ -186,31 +207,21 @@ async function filterTowns(name) {
:country-fk="data.countryFk"
:province-selected="data.provinceFk"
@update:model-value="(value) => setProvince(value, data)"
@update:options="
(data) => {
provincesOptions = data;
}
"
v-model="data.provinceFk"
:clearable="true"
:provinces="provincesOptions"
@on-province-created="onProvinceCreated"
required
/>
<VnSelect
ref="countriesRef"
:limit="30"
:filter="countryFilter"
:sort-by="['name ASC']"
auto-load
url="Countries"
required
:sort-by="['name ASC']"
:label="t('Country')"
@update:options="handleCountries"
hide-selected
option-label="name"
option-value="id"
v-model="data.countryFk"
:rules="validate('postcode.countryFk')"
@update:model-value="(value) => setCountry(value, data)"
data-cy="locationCountry"
/>
</VnRow>
</template>

View File

@ -1,7 +1,8 @@
<script setup>
import { computed, reactive, ref } from 'vue';
import { reactive, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import FetchData from 'components/FetchData.vue';
import VnRow from 'components/ui/VnRow.vue';
import VnSelect from 'src/components/common/VnSelect.vue';
import VnInput from 'src/components/common/VnInput.vue';
@ -20,24 +21,34 @@ const $props = defineProps({
type: Number,
default: null,
},
provinces: {
type: Array,
default: () => [],
},
});
const autonomiesRef = ref([]);
const autonomiesOptions = ref([]);
const onDataSaved = (dataSaved, requestResponse) => {
requestResponse.autonomy = autonomiesRef.value.opts.find(
requestResponse.autonomy = autonomiesOptions.value.find(
(autonomy) => autonomy.id == requestResponse.autonomyFk
);
emit('onDataSaved', dataSaved, requestResponse);
};
const where = computed(() => {
if (!$props.countryFk) {
return {};
}
return { countryFk: $props.countryFk };
});
</script>
<template>
<FetchData
@on-fetch="(data) => (autonomiesOptions = data)"
auto-load
:filter="{
where: {
countryFk: $props.countryFk,
},
}"
url="Autonomies/location"
:sort-by="['name ASC']"
:limit="30"
/>
<FormModelPopup
:title="t('New province')"
:subtitle="t('Please, ensure you put the correct data!')"
@ -52,19 +63,10 @@ const where = computed(() => {
:label="t('Name')"
v-model="data.name"
:rules="validate('province.name')"
required
data-cy="provinceName"
/>
<VnSelect
data-cy="autonomyProvince"
required
ref="autonomiesRef"
auto-load
:where="where"
url="Autonomies/location"
:sort-by="['name ASC']"
:limit="30"
:label="t('Autonomy')"
:options="autonomiesOptions"
hide-selected
option-label="name"
option-value="id"

View File

@ -10,7 +10,6 @@ import VnPaginate from 'components/ui/VnPaginate.vue';
import VnConfirm from 'components/ui/VnConfirm.vue';
import SkeletonTable from 'components/ui/SkeletonTable.vue';
import { tMobile } from 'src/composables/tMobile';
import getDifferences from 'src/filters/getDifferences';
const { push } = useRouter();
const quasar = useQuasar();
@ -78,7 +77,7 @@ const isLoading = ref(false);
const hasChanges = ref(false);
const originalData = ref();
const vnPaginateRef = ref();
const formData = ref([]);
const formData = ref();
const saveButtonRef = ref(null);
const watchChanges = ref();
const formUrl = computed(() => $props.url);
@ -95,7 +94,6 @@ defineExpose({
saveChanges,
getChanges,
formData,
originalData,
vnPaginateRef,
});
@ -127,7 +125,7 @@ function resetData(data) {
originalData.value = JSON.parse(JSON.stringify(data));
formData.value = JSON.parse(JSON.stringify(data));
if (watchChanges.value) watchChanges.value(); //destroy watcher
if (watchChanges.value) watchChanges.value(); //destoy watcher
watchChanges.value = watch(formData, () => (hasChanges.value = true), { deep: true });
}
@ -176,13 +174,14 @@ async function saveChanges(data) {
const changes = data || getChanges();
try {
await axios.post($props.saveUrl || $props.url + '/crud', changes);
} finally {
isLoading.value = false;
} catch (e) {
return (isLoading.value = false);
}
originalData.value = JSON.parse(JSON.stringify(formData.value));
if (changes.creates?.length) await vnPaginateRef.value.fetch();
hasChanges.value = false;
isLoading.value = false;
emit('saveChanges', data);
quasar.notify({
type: 'positive',
@ -249,7 +248,7 @@ function getChanges() {
for (const [i, row] of formData.value.entries()) {
if (!row[pk]) {
creates.push(row);
} else if (originalData.value[i]) {
} else if (originalData.value) {
const data = getDifferences(originalData.value[i], row);
if (!isEmpty(data)) {
updates.push({
@ -268,10 +267,34 @@ function getChanges() {
return changes;
}
function getDifferences(obj1, obj2) {
let diff = {};
delete obj1.$index;
delete obj2.$index;
for (let key in obj1) {
if (obj2[key] && JSON.stringify(obj1[key]) !== JSON.stringify(obj2[key])) {
diff[key] = obj2[key];
}
}
for (let key in obj2) {
if (
obj1[key] === undefined ||
JSON.stringify(obj1[key]) !== JSON.stringify(obj2[key])
) {
diff[key] = obj2[key];
}
}
return diff;
}
function isEmpty(obj) {
if (obj == null) return true;
if (Array.isArray(obj)) return !obj.length;
return !Object.keys(obj).length;
if (obj === undefined) return true;
if (Object.keys(obj).length === 0) return true;
if (obj.length > 0) return false;
}
async function reload(params) {
@ -371,7 +394,6 @@ watch(formUrl, async () => {
@click="onSubmit"
:disable="!hasChanges"
:title="t('globals.save')"
data-cy="crudModelDefaultSaveBtn"
/>
<slot name="moreAfterActions" />
</QBtnGroup>

View File

@ -156,22 +156,26 @@ const rotateRight = () => {
};
const onSubmit = () => {
if (!newPhoto.files && !newPhoto.url) {
notify(t('Select an image'), 'negative');
return;
try {
if (!newPhoto.files && !newPhoto.url) {
notify(t('Select an image'), 'negative');
return;
}
const options = {
type: 'blob',
};
editor.value
.result(options)
.then((result) => {
const file = new File([result], newPhoto.files?.name || '');
newPhoto.blob = file;
})
.then(() => makeRequest());
} catch (err) {
console.error('Error uploading image');
}
const options = {
type: 'blob',
};
editor.value
.result(options)
.then((result) => {
const file = new File([result], newPhoto.files?.name || '');
newPhoto.blob = file;
})
.then(() => makeRequest());
};
const makeRequest = async () => {

View File

@ -51,17 +51,21 @@ const onDataSaved = () => {
};
const onSubmit = async () => {
isLoading.value = true;
const rowsToEdit = $props.rows.map((row) => ({ id: row.id, itemFk: row.itemFk }));
const payload = {
field: selectedField.value.field,
newValue: newValue.value,
lines: rowsToEdit,
};
try {
isLoading.value = true;
const rowsToEdit = $props.rows.map((row) => ({ id: row.id, itemFk: row.itemFk }));
const payload = {
field: selectedField.value.field,
newValue: newValue.value,
lines: rowsToEdit,
};
await axios.post($props.editUrl, payload);
onDataSaved();
isLoading.value = false;
await axios.post($props.editUrl, payload);
onDataSaved();
isLoading.value = false;
} catch (err) {
console.error('Error submitting table cell edit');
}
};
const closeForm = () => {
@ -85,14 +89,12 @@ const closeForm = () => {
hide-selected
option-label="label"
v-model="selectedField"
data-cy="field-to-edit"
/>
<component
:is="inputs[selectedField?.component || 'input']"
v-bind="selectedField?.attrs || {}"
v-model="newValue"
:label="t('Value')"
data-cy="value-to-edit"
style="width: 200px"
/>
</VnRow>

View File

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

View File

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

View File

@ -1,7 +1,7 @@
<script setup>
import axios from 'axios';
import { onMounted, onUnmounted, computed, ref, watch, nextTick } from 'vue';
import { onBeforeRouteLeave, useRouter, useRoute } from 'vue-router';
import { onBeforeRouteLeave, useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { useQuasar } from 'quasar';
import { useState } from 'src/composables/useState';
@ -12,6 +12,7 @@ import SkeletonForm from 'components/ui/SkeletonForm.vue';
import VnConfirm from './ui/VnConfirm.vue';
import { tMobile } from 'src/composables/tMobile';
import { useArrayData } from 'src/composables/useArrayData';
import { useRoute } from 'vue-router';
const { push } = useRouter();
const quasar = useQuasar();
@ -90,10 +91,6 @@ const $props = defineProps({
type: Boolean,
default: true,
},
maxWidth: {
type: [String, Boolean],
default: '800px',
},
});
const emit = defineEmits(['onFetch', 'onDataSaved']);
const modelValue = computed(
@ -109,7 +106,6 @@ const originalData = ref({});
const formData = computed(() => state.get(modelValue));
const defaultButtons = computed(() => ({
save: {
dataCy: 'saveDefaultBtn',
color: 'primary',
icon: 'save',
label: 'globals.save',
@ -117,7 +113,6 @@ const defaultButtons = computed(() => ({
type: 'submit',
},
reset: {
dataCy: 'resetDefaultBtn',
color: 'primary',
icon: 'restart_alt',
label: 'globals.reset',
@ -198,7 +193,6 @@ async function fetch() {
} catch (e) {
state.set(modelValue, {});
originalData.value = {};
throw e;
}
}
@ -209,9 +203,7 @@ async function save() {
isLoading.value = true;
try {
formData.value = trimData(formData.value);
const body = $props.mapper
? $props.mapper(formData.value, originalData.value)
: formData.value;
const body = $props.mapper ? $props.mapper(formData.value) : formData.value;
const method = $props.urlCreate ? 'post' : 'patch';
const url =
$props.urlCreate || $props.urlUpdate || $props.url || arrayData.store.url;
@ -225,6 +217,9 @@ async function save() {
updateAndEmit('onDataSaved', formData.value, response?.data);
if ($props.reload) await arrayData.fetch({});
hasChanges.value = false;
} catch (err) {
console.error(err);
notify('errors.writeRequest', 'negative');
} finally {
isLoading.value = false;
}
@ -280,7 +275,6 @@ defineExpose({
hasChanges,
reset,
fetch,
formData,
});
</script>
<template>
@ -291,9 +285,7 @@ defineExpose({
@submit="save"
@reset="reset"
class="q-pa-md"
:style="maxWidth ? 'max-width: ' + maxWidth : ''"
id="formModel"
:prevent-submit="$attrs['prevent-submit']"
>
<QCard>
<slot
@ -327,7 +319,6 @@ defineExpose({
:title="t(defaultButtons.reset.label)"
/>
<QBtnDropdown
data-cy="saveAndContinueDefaultBtn"
v-if="$props.goTo"
@click="saveAndGo"
:label="tMobile('globals.saveAndContinue')"
@ -382,6 +373,7 @@ defineExpose({
color: black;
}
#formModel {
max-width: 800px;
width: 100%;
}

View File

@ -61,8 +61,6 @@ defineExpose({
:loading="isLoading"
@click="emit('onDataCanceled')"
v-close-popup
data-cy="FormModelPopup_cancel"
z-max
/>
<QBtn
:label="t('globals.save')"
@ -72,8 +70,6 @@ defineExpose({
class="q-ml-sm"
:disabled="isLoading"
:loading="isLoading"
data-cy="FormModelPopup_save"
z-max
/>
</div>
</template>

View File

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

View File

@ -9,8 +9,6 @@ import VnSelect from 'components/common/VnSelect.vue';
import VnFilterPanelChip from 'components/ui/VnFilterPanelChip.vue';
import axios from 'axios';
import { getParamWhere } from 'src/filters';
import { useRoute } from 'vue-router';
const { t } = useI18n();
const props = defineProps({
@ -28,22 +26,29 @@ const props = defineProps({
},
});
const route = useRoute();
const itemCategories = ref([]);
const selectedCategoryFk = ref(null);
const selectedTypeFk = ref(null);
const itemTypesOptions = ref([]);
const suppliersOptions = ref([]);
const tagOptions = ref([]);
const tagValues = ref([]);
const categoryList = ref(null);
const selectedCategoryFk = ref(getParamWhere(route.query.table, 'categoryFk', false));
const selectedTypeFk = ref(getParamWhere(route.query.table, 'typeFk', false));
const selectedCategory = computed(() => {
return (categoryList.value || []).find(
(category) => category?.id === selectedCategoryFk.value
);
const categoryList = computed(() => {
return (itemCategories.value || [])
.filter((category) => category.display)
.map((category) => ({
...category,
icon: `vn:${(category.icon || '').split('-')[1]}`,
}));
});
const selectedCategory = computed(() =>
(itemCategories.value || []).find(
(category) => category?.id === selectedCategoryFk.value
)
);
const selectedType = computed(() => {
return (itemTypesOptions.value || []).find(
(type) => type?.id === selectedTypeFk.value
@ -82,17 +87,21 @@ const applyTags = (params, search) => {
search();
};
const fetchItemTypes = async (id = selectedCategoryFk.value) => {
const filter = {
fields: ['id', 'name', 'categoryFk'],
where: { categoryFk: id },
include: 'category',
order: 'name ASC',
};
const { data } = await axios.get('ItemTypes', {
params: { filter: JSON.stringify(filter) },
});
itemTypesOptions.value = data;
const fetchItemTypes = async (id) => {
try {
const filter = {
fields: ['id', 'name', 'categoryFk'],
where: { categoryFk: id },
include: 'category',
order: 'name ASC',
};
const { data } = await axios.get('ItemTypes', {
params: { filter: JSON.stringify(filter) },
});
itemTypesOptions.value = data;
} catch (err) {
console.error('Error fetching item types', err);
}
};
const getCategoryClass = (category, params) => {
@ -102,38 +111,38 @@ const getCategoryClass = (category, params) => {
};
const getSelectedTagValues = async (tag) => {
if (!tag?.selectedTag?.id) return;
tag.value = null;
const filter = {
fields: ['value'],
order: 'value ASC',
limit: 30,
};
try {
if (!tag?.selectedTag?.id) return;
tag.value = null;
const filter = {
fields: ['value'],
order: 'value ASC',
limit: 30,
};
const params = { filter: JSON.stringify(filter) };
const { data } = await axios.get(`Tags/${tag.selectedTag.id}/filterValue`, {
params,
});
tag.valueOptions = data;
const params = { filter: JSON.stringify(filter) };
const { data } = await axios.get(`Tags/${tag.selectedTag.id}/filterValue`, {
params,
});
tag.valueOptions = data;
} catch (err) {
console.error('Error getting selected tag values');
}
};
const removeTag = (index, params, search) => {
(tagValues.value || []).splice(index, 1);
applyTags(params, search);
};
const setCategoryList = (data) => {
categoryList.value = (data || [])
.filter((category) => category.display)
.map((category) => ({
...category,
icon: `vn:${(category.icon || '').split('-')[1]}`,
}));
fetchItemTypes();
};
</script>
<template>
<FetchData url="ItemCategories" limit="30" auto-load @on-fetch="setCategoryList" />
<FetchData
url="ItemCategories"
limit="30"
auto-load
@on-fetch="(data) => (itemCategories = data)"
/>
<FetchData
url="Suppliers"
limit="30"
@ -239,7 +248,7 @@ const setCategoryList = (data) => {
>
<QItemSection class="col">
<VnSelect
:label="t('globals.tag')"
:label="t('components.itemsFilterPanel.tag')"
v-model="value.selectedTag"
:options="tagOptions"
option-label="name"

View File

@ -1,6 +1,6 @@
<script setup>
import axios from 'axios';
import { onMounted, watch, ref, reactive, computed } from 'vue';
import { onMounted, watch, ref, reactive } from 'vue';
import { useI18n } from 'vue-i18n';
import { QSeparator, useQuasar } from 'quasar';
import { useRoute } from 'vue-router';
@ -9,7 +9,6 @@ import { toLowerCamel } from 'src/filters';
import routes from 'src/router/modules';
import LeftMenuItem from './LeftMenuItem.vue';
import LeftMenuItemGroup from './LeftMenuItemGroup.vue';
import VnInput from './common/VnInput.vue';
const { t } = useI18n();
const route = useRoute();
@ -22,52 +21,17 @@ const props = defineProps({
default: 'main',
},
});
const initialized = ref(false);
const items = ref([]);
const expansionItemElements = reactive({});
const pinnedModules = computed(() => {
const map = new Map();
items.value.forEach((item) => item.isPinned && map.set(item.name, item));
return map;
});
const search = ref(null);
const filteredItems = computed(() => {
if (!search.value) return items.value;
const normalizedSearch = normalize(search.value);
return items.value.filter((item) => {
const locale = normalize(t(item.title));
return locale.includes(normalizedSearch);
});
});
const filteredPinnedModules = computed(() => {
if (!search.value) return pinnedModules.value;
const normalizedSearch = search.value
.normalize('NFD')
.replace(/[\u0300-\u036f]/g, '')
.toLowerCase();
const map = new Map();
for (const [key, pinnedModule] of pinnedModules.value) {
const locale = t(pinnedModule.title)
.normalize('NFD')
.replace(/[\u0300-\u036f]/g, '')
.toLowerCase();
if (locale.includes(normalizedSearch)) map.set(key, pinnedModule);
}
return map;
});
onMounted(async () => {
await navigation.fetchPinned();
getRoutes();
initialized.value = true;
});
watch(
() => route.matched,
() => {
if (!initialized.value) return;
items.value = [];
getRoutes();
},
@ -92,16 +56,18 @@ function findMatches(search, item) {
}
function addChildren(module, route, parent) {
const menus = route?.meta?.menu ?? route?.menus?.[props.source]; //backwards compatible
if (!menus) return;
if (route.menus) {
const mainMenus = route.menus[props.source];
const matches = findMatches(mainMenus, route);
const matches = findMatches(menus, route);
for (const child of matches) {
navigation.addMenuItem(module, child, parent);
for (const child of matches) {
navigation.addMenuItem(module, child, parent);
}
}
}
const items = ref([]);
function getRoutes() {
if (props.source === 'main') {
const modules = Object.assign([], navigation.getModules().value);
@ -122,26 +88,16 @@ function getRoutes() {
if (props.source === 'card') {
const currentRoute = route.matched[1];
const currentModule = toLowerCamel(currentRoute.name);
let moduleDef = routes.find(
const moduleDef = routes.find(
(route) => toLowerCamel(route.name) === currentModule
);
if (!moduleDef) return;
if (!moduleDef?.menus) moduleDef = betaGetRoutes();
addChildren(currentModule, moduleDef, items.value);
}
}
function betaGetRoutes() {
let menuRoute;
let index = route.matched.length - 1;
while (!menuRoute && index > 0) {
if (route.matched[index]?.meta?.menu) menuRoute = route.matched[index];
index--;
}
return menuRoute;
}
async function togglePinned(item, event) {
if (event.defaultPrevented) return;
event.preventDefault();
@ -167,58 +123,21 @@ async function togglePinned(item, event) {
const handleItemExpansion = (itemName) => {
expansionItemElements[itemName].scrollToLastElement();
};
function normalize(text) {
return text
.normalize('NFD')
.replace(/[\u0300-\u036f]/g, '')
.toLowerCase();
}
</script>
<template>
<QList padding class="column-max-width">
<template v-if="$props.source === 'main'">
<template v-if="$route?.matched[1]?.name === 'Dashboard'">
<QItem class="q-pb-md">
<VnInput
v-model="search"
:label="t('Search modules')"
class="full-width"
filled
dense
autofocus
/>
<QItem class="header">
<QItemSection avatar>
<QIcon name="view_module" />
</QItemSection>
<QItemSection> {{ t('globals.modules') }}</QItemSection>
</QItem>
<QSeparator />
<template v-if="filteredPinnedModules.size">
<LeftMenuItem
v-for="[key, pinnedModule] of filteredPinnedModules"
:key="key"
:item="pinnedModule"
group="modules"
>
<template #side>
<QBtn
v-if="pinnedModule.isPinned === true"
@click="togglePinned(pinnedModule, $event)"
icon="remove_circle"
size="xs"
flat
round
>
<QTooltip>
{{ t('components.leftMenu.removeFromPinned') }}
</QTooltip>
</QBtn>
</template>
</LeftMenuItem>
<QSeparator />
</template>
<template v-for="item in filteredItems" :key="item.name">
<template
v-if="item.children && !filteredPinnedModules.has(item.name)"
>
<template v-for="item in items" :key="item.name">
<template v-if="item.children">
<LeftMenuItem :item="item" group="modules">
<template #side>
<QBtn
@ -337,7 +256,3 @@ function normalize(text) {
color: var(--vn-label-color);
}
</style>
<i18n>
es:
Search modules: Buscar módulos
</i18n>

View File

@ -17,10 +17,12 @@ const stateQuery = useStateQueryStore();
const state = useState();
const user = state.getUser();
const appName = 'Lilium';
const pinnedModulesRef = ref();
onMounted(() => stateStore.setMounted());
const pinnedModulesRef = ref();
</script>
<template>
<QHeader color="white" elevated>
<QToolbar class="q-py-sm q-px-md">
@ -57,13 +59,22 @@ onMounted(() => stateStore.setMounted());
'no-visible': !stateQuery.isLoading().value,
}"
size="xs"
data-cy="loading-spinner"
/>
<QSpace />
<div id="searchbar" class="searchbar"></div>
<QSpace />
<div class="q-pl-sm q-gutter-sm row items-center no-wrap">
<div id="actions-prepend"></div>
<QBtn
flat
v-if="!quasar.platform.is.mobile"
@click="pinnedModulesRef.redirect($route.params.id)"
icon="more_up"
>
<QTooltip>
{{ t('Go to Salix') }}
</QTooltip>
</QBtn>
<QBtn
:class="{ 'q-pa-none': quasar.platform.is.mobile }"
id="pinnedModules"
@ -95,6 +106,7 @@ onMounted(() => stateStore.setMounted());
<VnBreadcrumbs v-if="$q.screen.lt.md" class="q-ml-md" />
</QHeader>
</template>
<style lang="scss" scoped>
.searchbar {
width: max-content;
@ -103,3 +115,9 @@ onMounted(() => stateStore.setMounted());
background-color: var(--vn-section-color);
}
</style>
<i18n>
en:
Go to Salix: Go to Salix
es:
Go to Salix: Ir a Salix
</i18n>

View File

@ -39,10 +39,14 @@ const refund = async () => {
invoiceCorrectionTypeFk: invoiceParams.invoiceCorrectionTypeFk,
};
const { data } = await axios.post('InvoiceOuts/refundAndInvoice', params);
notify(t('Refunded invoice'), 'positive');
const [id] = data?.refundId || [];
if (id) router.push({ name: 'InvoiceOutSummary', params: { id } });
try {
const { data } = await axios.post('InvoiceOuts/refundAndInvoice', params);
notify(t('Refunded invoice'), 'positive');
const [id] = data?.refundId || [];
if (id) router.push({ name: 'InvoiceOutSummary', params: { id } });
} catch (err) {
console.error('Error refunding invoice', err);
}
};
</script>

View File

@ -44,7 +44,7 @@ const onDataSaved = (data) => {
<FormModelPopup
url-create="Items/regularize"
model="Items"
:title="t('item.regularizeStock')"
:title="t('Regularize stock')"
:form-initial-data="regularizeFormData"
@on-data-saved="onDataSaved($event)"
>
@ -55,7 +55,6 @@ const onDataSaved = (data) => {
v-model.number="data.quantity"
type="number"
autofocus
data-cy="regularizeStockInput"
/>
</VnRow>
<VnRow>

View File

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

View File

@ -49,32 +49,36 @@ const makeInvoice = async () => {
makeInvoice: checked.value,
};
if (checked.value && hasToInvoiceByAddress) {
const response = await new Promise((resolve) => {
quasar
.dialog({
component: VnConfirm,
componentProps: {
title: t('Bill destination client'),
message: t('transferInvoiceInfo'),
},
})
.onOk(() => {
resolve(true);
})
.onCancel(() => {
resolve(false);
});
});
if (!response) {
return;
try {
if (checked.value && hasToInvoiceByAddress) {
const response = await new Promise((resolve) => {
quasar
.dialog({
component: VnConfirm,
componentProps: {
title: t('Bill destination client'),
message: t('transferInvoiceInfo'),
},
})
.onOk(() => {
resolve(true);
})
.onCancel(() => {
resolve(false);
});
});
if (!response) {
return;
}
}
}
const { data } = await axios.post('InvoiceOuts/transfer', params);
notify(t('Transferred invoice'), 'positive');
const id = data?.[0];
if (id) router.push({ name: 'InvoiceOutSummary', params: { id } });
const { data } = await axios.post('InvoiceOuts/transfer', params);
notify(t('Transferred invoice'), 'positive');
const id = data?.[0];
if (id) router.push({ name: 'InvoiceOutSummary', params: { id } });
} catch (err) {
console.error('Error transfering invoice', err);
}
};
</script>

View File

@ -87,10 +87,10 @@ async function saveDarkMode(value) {
async function saveLanguage(value) {
const query = `/VnUsers/${user.value.id}`;
try {
await axios.patch(query, { lang: value });
await axios.patch(query, {
lang: value,
});
user.value.lang = value;
useState().setUser(user.value);
onDataSaved();
} catch (error) {
onDataError();

View File

@ -7,7 +7,7 @@ import VnSelectDialog from 'components/common/VnSelectDialog.vue';
import FetchData from 'components/FetchData.vue';
import CreateNewProvinceForm from './CreateNewProvinceForm.vue';
const emit = defineEmits(['onProvinceCreated', 'onProvinceFetched', 'update:options']);
const emit = defineEmits(['onProvinceCreated']);
const $props = defineProps({
countryFk: {
type: Number,
@ -17,23 +17,20 @@ const $props = defineProps({
type: Number,
default: null,
},
provinces: {
type: Array,
default: () => [],
},
});
const provinceFk = defineModel({ type: Number, default: null });
const { validate } = useValidator();
const { t } = useI18n();
const filter = ref({
include: { relation: 'country' },
where: {
countryFk: $props.countryFk,
},
});
const provincesOptions = ref($props.provinces);
const provincesFetchDataRef = ref();
provinceFk.value = $props.provinceSelected;
if (!$props.countryFk) {
filter.value.where = {};
}
const provincesFetchDataRef = ref();
async function onProvinceCreated(_, data) {
await provincesFetchDataRef.value.fetch({ where: { countryFk: $props.countryFk } });
provinceFk.value = data.id;
@ -41,33 +38,24 @@ async function onProvinceCreated(_, data) {
}
async function handleProvinces(data) {
provincesOptions.value = data;
emit('update:options', data);
}
watch(
() => $props.countryFk,
async () => {
if ($props.countryFk) {
filter.value.where.countryFk = $props.countryFk;
} else filter.value.where = {};
await provincesFetchDataRef.value.fetch({});
emit('onProvinceFetched', provincesOptions.value);
}
);
</script>
<template>
<FetchData
ref="provincesFetchDataRef"
:filter="filter"
:filter="{
include: { relation: 'country' },
where: {
countryFk: $props.countryFk,
},
}"
@on-fetch="handleProvinces"
url="Provinces"
auto-load
/>
<VnSelectDialog
data-cy="locationProvince"
:label="t('Province')"
:options="provincesOptions"
:options="$props.provinces"
:tooltip="t('Create province')"
hide-selected
v-model="provinceFk"

View File

@ -25,17 +25,14 @@ const $props = defineProps({
},
searchUrl: {
type: String,
default: 'table',
default: 'params',
},
});
defineExpose({ addFilter, props: $props });
const model = defineModel(undefined, { required: true });
const arrayData = useArrayData(
$props.dataKey,
$props.searchUrl ? { searchUrl: $props.searchUrl } : null
);
const arrayData = useArrayData($props.dataKey, { searchUrl: $props.searchUrl });
const columnFilter = computed(() => $props.column?.columnFilter);
const updateEvent = { 'update:modelValue': addFilter };
@ -146,10 +143,6 @@ function alignRow() {
const showFilter = computed(
() => $props.column?.columnFilter !== false && $props.column.name != 'tableActions'
);
const onTabPressed = async () => {
if (model.value) enterEvent['keyup.enter']();
};
</script>
<template>
<div
@ -164,7 +157,6 @@ const onTabPressed = async () => {
v-model="model"
:components="components"
component-prop="columnFilter"
@keydown.tab="onTabPressed"
/>
</div>
</template>

View File

@ -17,7 +17,7 @@ const $props = defineProps({
},
searchUrl: {
type: String,
default: 'table',
default: 'params',
},
vertical: {
type: Boolean,

View File

@ -1,21 +1,20 @@
<script setup>
import { ref, onBeforeMount, onMounted, computed, watch, useAttrs } from 'vue';
import { ref, onBeforeMount, onMounted, computed, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRoute, useRouter } from 'vue-router';
import { useQuasar } from 'quasar';
import { useStateStore } from 'stores/useStateStore';
import { useFilterParams } from 'src/composables/useFilterParams';
import CrudModel from 'src/components/CrudModel.vue';
import FormModelPopup from 'components/FormModelPopup.vue';
import VnFilterPanel from 'components/ui/VnFilterPanel.vue';
import VnTableColumn from 'components/VnTable/VnColumn.vue';
import VnFilter from 'components/VnTable/VnFilter.vue';
import VnTableChip from 'components/VnTable/VnChip.vue';
import VnVisibleColumn from 'src/components/VnTable/VnVisibleColumn.vue';
import VnLv from 'components/ui/VnLv.vue';
import VnTableOrder from 'src/components/VnTable/VnOrder.vue';
import VnTableFilter from './VnTableFilter.vue';
const $props = defineProps({
columns: {
@ -34,10 +33,6 @@ const $props = defineProps({
type: Boolean,
default: true,
},
rightSearchIcon: {
type: Boolean,
default: true,
},
rowClick: {
type: [Function, Boolean],
default: null,
@ -59,15 +54,15 @@ const $props = defineProps({
default: true,
},
bottom: {
type: Boolean,
default: false,
type: Object,
default: null,
},
cardClass: {
type: String,
default: 'flex-one',
},
searchUrl: {
type: [String, Boolean],
type: String,
default: 'table',
},
isEditable: {
@ -106,6 +101,10 @@ const $props = defineProps({
type: String,
default: '90vh',
},
chipLocale: {
type: String,
default: null,
},
footer: {
type: Boolean,
default: false,
@ -120,21 +119,22 @@ const stateStore = useStateStore();
const route = useRoute();
const router = useRouter();
const quasar = useQuasar();
const $attrs = useAttrs();
const CARD_MODE = 'card';
const TABLE_MODE = 'table';
const mode = ref(CARD_MODE);
const selected = ref([]);
const hasParams = ref(false);
const routeQuery = JSON.parse(route?.query[$props.searchUrl] ?? '{}');
const params = ref({ ...routeQuery, ...routeQuery.filter?.where });
const orders = ref(parseOrder(routeQuery.filter?.order));
const CrudModelRef = ref({});
const showForm = ref(false);
const splittedColumns = ref({ columns: [] });
const columnsVisibilitySkipped = ref();
const createForm = ref();
const tableFilterRef = ref([]);
const tableRef = ref();
const params = ref(useFilterParams($attrs['data-key']).params);
const orders = ref(useFilterParams($attrs['data-key']).orders);
const tableModes = [
{
@ -150,10 +150,9 @@ const tableModes = [
disable: $props.disableOption?.card,
},
];
onBeforeMount(() => {
const urlParams = route.query[$props.searchUrl];
hasParams.value = urlParams && Object.keys(urlParams).length !== 0;
setUserParams(route.query[$props.searchUrl]);
hasParams.value = params.value && Object.keys(params.value).length !== 0;
});
onMounted(() => {
@ -164,7 +163,7 @@ onMounted(() => {
stateStore.rightDrawer = quasar.screen.gt.xs;
columnsVisibilitySkipped.value = [
...splittedColumns.value.columns
.filter((c) => c.visible === false)
.filter((c) => c.visible == false)
.map((c) => c.name),
...['tableActions'],
];
@ -184,8 +183,40 @@ watch(
{ immediate: true }
);
watch(
() => route.query[$props.searchUrl],
(val) => setUserParams(val)
);
const isTableMode = computed(() => mode.value == TABLE_MODE);
const showRightIcon = computed(() => $props.rightSearch || $props.rightSearchIcon);
function setUserParams(watchedParams, watchedOrder) {
if (!watchedParams) return;
if (typeof watchedParams == 'string') watchedParams = JSON.parse(watchedParams);
const filter =
typeof watchedParams?.filter == 'string'
? JSON.parse(watchedParams?.filter ?? '{}')
: watchedParams?.filter;
const where = filter?.where;
const order = watchedOrder ?? filter?.order;
watchedParams = { ...watchedParams, ...where };
delete watchedParams.filter;
delete params.value?.filter;
params.value = { ...params.value, ...sanitizer(watchedParams) };
orders.value = parseOrder(order);
}
function sanitizer(params) {
for (const [key, value] of Object.entries(params)) {
if (value && typeof value == 'object') {
const param = Object.values(value)[0];
if (typeof param == 'string') params[key] = param.replaceAll('%', '');
}
}
return params;
}
function splitColumns(columns) {
splittedColumns.value = {
@ -205,7 +236,7 @@ function splitColumns(columns) {
if (col.create) splittedColumns.value.create.push(col);
if (col.cardVisible) splittedColumns.value.cardVisible.push(col);
if ($props.isEditable && col.disable == null) col.disable = false;
if ($props.useModel && col.columnFilter !== false)
if ($props.useModel && col.columnFilter != false)
col.columnFilter = { inWhere: true, ...col.columnFilter };
splittedColumns.value.columns.push(col);
}
@ -266,6 +297,17 @@ function getColAlign(col) {
return 'text-' + (col.align ?? 'left');
}
function parseOrder(urlOrders) {
const orderObject = {};
if (!urlOrders) return orderObject;
if (typeof urlOrders == 'string') urlOrders = [urlOrders];
for (const [index, orders] of urlOrders.entries()) {
const [name, direction] = orders.split(' ');
orderObject[name] = { direction, index: index + 1 };
}
return orderObject;
}
const emit = defineEmits(['onFetch', 'update:selected', 'saveChanges']);
defineExpose({
create: createForm,
@ -283,27 +325,11 @@ function handleOnDataSaved(_) {
}
function handleScroll() {
if ($props.crudModel.disableInfiniteScroll) return;
const tMiddle = tableRef.value.$el.querySelector('.q-table__middle');
const { scrollHeight, scrollTop, clientHeight } = tMiddle;
const isAtBottom = Math.abs(scrollHeight - scrollTop - clientHeight) <= 40;
if (isAtBottom) CrudModelRef.value.vnPaginateRef.paginate();
}
function handleSelection({ evt, added, rows: selectedRows }, rows) {
if (evt?.shiftKey && added) {
const rowIndex = selectedRows[0].$index;
const selectedIndexes = new Set(selected.value.map((row) => row.$index));
for (const row of rows) {
if (row.$index == rowIndex) break;
if (!selectedIndexes.has(row.$index)) {
selected.value.push(row);
selectedIndexes.add(row.$index);
}
}
}
}
</script>
<template>
<QDrawer
@ -314,7 +340,61 @@ function handleSelection({ evt, added, rows: selectedRows }, rows) {
show-if-above
>
<QScrollArea class="fit">
<VnTableFilter :data-key="$attrs['data-key']" :columns="columns" :redirect="redirect" />
<VnFilterPanel
:data-key="$attrs['data-key']"
:search-button="true"
v-model="params"
:search-url="searchUrl"
:redirect="!!redirect"
@set-user-params="setUserParams"
:disable-submit-event="true"
@remove="
(key) =>
tableFilterRef
.find((f) => f.props?.column.name == key)
?.addFilter()
"
>
<template #body>
<div
class="row no-wrap flex-center"
v-for="col of splittedColumns.columns.filter(
(c) => c.columnFilter ?? true
)"
:key="col.id"
>
<VnFilter
ref="tableFilterRef"
:column="col"
:data-key="$attrs['data-key']"
v-model="params[columnName(col)]"
:search-url="searchUrl"
/>
<VnTableOrder
v-if="
col?.columnFilter !== false &&
col?.name !== 'tableActions'
"
v-model="orders[col.orderBy ?? col.name]"
:name="col.orderBy ?? col.name"
:data-key="$attrs['data-key']"
:search-url="searchUrl"
:vertical="true"
/>
</div>
<slot
name="moreFilterPanel"
:params="params"
:columns="splittedColumns.columns"
/>
</template>
<template #tags="{ tag, formatFn }" v-if="chipLocale">
<div class="q-gutter-x-xs">
<strong>{{ t(`${chipLocale}.${tag.label}`) }}: </strong>
<span>{{ formatFn(tag.value) }}</span>
</div>
</template>
</VnFilterPanel>
</QScrollArea>
</QDrawer>
<CrudModel
@ -350,7 +430,6 @@ function handleSelection({ evt, added, rows: selectedRows }, rows) {
@virtual-scroll="handleScroll"
@row-click="(_, row) => rowClickFunction && rowClickFunction(row)"
@update:selected="emit('update:selected', $event)"
@selection="(details) => handleSelection(details, rows)"
>
<template #top-left v-if="!$props.withoutHeader">
<slot name="top-left"></slot>
@ -370,7 +449,7 @@ function handleSelection({ evt, added, rows: selectedRows }, rows) {
:options="tableModes.filter((mode) => !mode.disable)"
/>
<QBtn
v-if="showRightIcon"
v-if="$props.rightSearch"
icon="filter_alt"
class="bg-vn-section-color q-ml-sm"
dense
@ -384,7 +463,7 @@ function handleSelection({ evt, added, rows: selectedRows }, rows) {
:class="col.headerClass"
>
<div
class="column ellipsis"
class="column self-start q-ml-xs ellipsis"
:class="`text-${col?.align ?? 'left'}`"
:style="$props.columnSearch ? 'height: 75px' : ''"
>
@ -426,7 +505,7 @@ function handleSelection({ evt, added, rows: selectedRows }, rows) {
<!-- Columns -->
<QTd
auto-width
class="no-margin"
class="no-margin q-px-xs"
:class="[getColAlign(col), col.columnClass]"
:style="col.style"
v-if="col.visible ?? true"
@ -478,6 +557,29 @@ function handleSelection({ evt, added, rows: selectedRows }, rows) {
/>
</QTd>
</template>
<template #bottom v-if="bottom">
<slot name="bottom-table">
<QBtn
@click="
() =>
createAsDialog
? (showForm = !showForm)
: handleOnDataSaved(create)
"
class="cursor-pointer fill-icon"
color="primary"
icon="add_circle"
size="md"
round
flat
shortcut="+"
:disabled="!disabledAttr"
/>
<QTooltip>
{{ createForm.title }}
</QTooltip>
</slot>
</template>
<template #item="{ row, colsMap }">
<component
:is="$props.redirect ? 'router-link' : 'span'"
@ -492,7 +594,6 @@ function handleSelection({ evt, added, rows: selectedRows }, rows) {
$props.rowClick && $props.rowClick(row);
}
"
style="height: 100%"
>
<QCardSection
vertical
@ -538,7 +639,13 @@ function handleSelection({ evt, added, rows: selectedRows }, rows) {
:key="col.name"
class="fields"
>
<VnLv :label="col.label + ':'">
<VnLv
:label="
!col.component && col.label
? `${col.label}:`
: ''
"
>
<template #value>
<span
@click="stopEventPropagation($event)"
@ -602,27 +709,6 @@ function handleSelection({ evt, added, rows: selectedRows }, rows) {
</QTr>
</template>
</QTable>
<div class="full-width bottomButton" v-if="bottom">
<QBtn
@click="
() =>
createAsDialog
? (showForm = !showForm)
: handleOnDataSaved(create)
"
class="cursor-pointer fill-icon"
color="primary"
icon="add_circle"
size="md"
round
flat
shortcut="+"
:disabled="!disabledAttr"
/>
<QTooltip>
{{ createForm.title }}
</QTooltip>
</div>
</template>
</CrudModel>
<QPageSticky v-if="$props.create" :offset="[20, 20]" style="z-index: 2">
@ -635,7 +721,6 @@ function handleSelection({ evt, added, rows: selectedRows }, rows) {
fab
icon="add"
shortcut="+"
data-cy="vnTableCreateBtn"
/>
<QTooltip self="top right">
{{ createForm?.title }}
@ -700,7 +785,7 @@ es:
.grid-three {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(350px, max-content));
grid-template-columns: repeat(auto-fit, minmax(400px, max-content));
max-width: 100%;
grid-gap: 20px;
margin: 0 auto;
@ -749,6 +834,21 @@ es:
top: 0;
padding: 12px 0;
}
tbody {
.q-checkbox {
display: flex;
margin-bottom: 9px;
& .q-checkbox__label {
margin-left: 31px;
color: var(--vn-text-color);
}
& .q-checkbox__inner {
position: absolute;
left: 0;
color: var(--vn-label-color);
}
}
}
.sticky {
position: sticky;
right: 0;

View File

@ -1,66 +0,0 @@
<script setup>
import { ref } from 'vue';
import VnFilterPanel from 'components/ui/VnFilterPanel.vue';
import VnFilter from 'components/VnTable/VnFilter.vue';
import VnTableOrder from 'src/components/VnTable/VnOrder.vue';
defineProps({
columns: {
type: Array,
required: true,
},
searchUrl: {
type: [String, Boolean],
default: 'table',
},
});
const tableFilterRef = ref([]);
function columnName(col) {
const column = { ...col, ...col.columnFilter };
let name = column.name;
if (column.alias) name = column.alias + '.' + name;
return name;
}
</script>
<template>
<VnFilterPanel v-bind="$attrs" :search-button="true" :disable-submit-event="true">
<template #body="{ params, orders }">
<div
class="row no-wrap flex-center"
v-for="col of columns.filter((c) => c.columnFilter ?? true)"
:key="col.id"
>
<VnFilter
ref="tableFilterRef"
:column="col"
:data-key="$attrs['data-key']"
v-model="params[columnName(col)]"
:search-url="searchUrl"
/>
<VnTableOrder
v-if="col?.columnFilter !== false && col?.name !== 'tableActions'"
v-model="orders[col.orderBy ?? col.name]"
:name="col.orderBy ?? col.name"
:data-key="$attrs['data-key']"
:search-url="searchUrl"
:vertical="true"
/>
</div>
<slot
name="moreFilterPanel"
:params="params"
:orders="orders"
:columns="columns"
/>
</template>
<template #tags="{ tag, formatFn, getLocale }">
<div class="q-gutter-x-xs">
<strong>{{ getLocale(`${tag.label}`) }}: </strong>
<span>{{ formatFn(tag.value) }}</span>
</div>
</template>
</VnFilterPanel>
</template>

View File

@ -152,7 +152,7 @@ onMounted(async () => {
<QCheckbox
v-for="col in localColumns"
:key="col.name"
:label="col.label ?? col.name"
:label="col.label"
v-model="col.visible"
/>
</div>

View File

@ -1,56 +0,0 @@
import { describe, expect, it, beforeAll, beforeEach, vi } from 'vitest';
import { createWrapper } from 'app/test/vitest/helper';
import VnTable from 'src/components/VnTable/VnTable.vue';
describe('VnTable', () => {
let wrapper;
let vm;
beforeAll(() => {
wrapper = createWrapper(VnTable, {
propsData: {
columns: [],
},
});
vm = wrapper.vm;
vi.mock('src/composables/useFilterParams', () => {
return {
useFilterParams: vi.fn(() => ({
params: {},
orders: {},
})),
};
});
});
beforeEach(() => (vm.selected = []));
describe('handleSelection()', () => {
const rows = [{ $index: 0 }, { $index: 1 }, { $index: 2 }];
const selectedRows = [{ $index: 1 }];
it('should add rows to selected when shift key is pressed and rows are added except last one', () => {
vm.handleSelection(
{ evt: { shiftKey: true }, added: true, rows: selectedRows },
rows
);
expect(vm.selected).toEqual([{ $index: 0 }]);
});
it('should not add rows to selected when shift key is not pressed', () => {
vm.handleSelection(
{ evt: { shiftKey: false }, added: true, rows: selectedRows },
rows
);
expect(vm.selected).toEqual([]);
});
it('should not add rows to selected when rows are not added', () => {
vm.handleSelection(
{ evt: { shiftKey: true }, added: false, rows: selectedRows },
rows
);
expect(vm.selected).toEqual([]);
});
});
});

View File

@ -1,248 +0,0 @@
import { createWrapper, axios } from 'app/test/vitest/helper';
import CrudModel from 'components/CrudModel.vue';
import { vi, afterEach, beforeEach, beforeAll, describe, expect, it } from 'vitest';
describe('CrudModel', () => {
let wrapper;
let vm;
let data;
beforeAll(() => {
wrapper = createWrapper(CrudModel, {
global: {
stubs: [
'vnPaginate',
'useState',
'arrayData',
'useStateStore',
'vue-i18n',
],
mocks: {
validate: vi.fn(),
},
},
propsData: {
dataRequired: {
fk: 1,
},
dataKey: 'crudModelKey',
model: 'crudModel',
url: 'crudModelUrl',
saveFn: '',
},
});
wrapper=wrapper.wrapper;
vm=wrapper.vm;
});
beforeEach(() => {
vm.fetch([]);
vm.watchChanges = null;
});
afterEach(() => {
vi.clearAllMocks();
});
describe('insert()', () => {
it('should new element in list with index 0 if formData not has data', () => {
vm.insert();
expect(vm.formData.length).toEqual(1);
expect(vm.formData[0].fk).toEqual(1);
expect(vm.formData[0].$index).toEqual(0);
});
});
describe('getChanges()', () => {
it('should return correct updates and creates', async () => {
vm.fetch([
{ id: 1, name: 'New name one' },
{ id: 2, name: 'New name two' },
{ id: 3, name: 'Bruce Wayne' },
]);
vm.originalData = [
{ id: 1, name: 'Tony Starks' },
{ id: 2, name: 'Jessica Jones' },
{ id: 3, name: 'Bruce Wayne' },
];
vm.insert();
const result = vm.getChanges();
const expected = {
creates: [
{
$index: 3,
fk: 1,
},
],
updates: [
{
data: {
name: 'New name one',
},
where: {
id: 1,
},
},
{
data: {
name: 'New name two',
},
where: {
id: 2,
},
},
],
};
expect(result).toEqual(expected);
});
});
describe('getDifferences()', () => {
it('should return the differences between two objects', async () => {
const obj1 = {
a: 1,
b: 2,
c: 3,
};
const obj2 = {
a: null,
b: 4,
d: 5,
};
const result = vm.getDifferences(obj1, obj2);
expect(result).toEqual({
a: null,
b: 4,
d: 5,
});
});
});
describe('isEmpty()', () => {
let dummyObj;
let dummyArray;
let result;
it('should return true if object si null', async () => {
dummyObj = null;
result = vm.isEmpty(dummyObj);
expect(result).toBe(true);
});
it('should return true if object si undefined', async () => {
dummyObj = undefined;
result = vm.isEmpty(dummyObj);
expect(result).toBe(true);
});
it('should return true if object is empty', async () => {
dummyObj ={};
result = vm.isEmpty(dummyObj);
expect(result).toBe(true);
});
it('should return false if object is not empty', async () => {
dummyObj = {a:1, b:2, c:3};
result = vm.isEmpty(dummyObj);
expect(result).toBe(false);
});
it('should return true if array is empty', async () => {
dummyArray = [];
result = vm.isEmpty(dummyArray);
expect(result).toBe(true);
});
it('should return false if array is not empty', async () => {
dummyArray = [1,2,3];
result = vm.isEmpty(dummyArray);
expect(result).toBe(false);
})
});
describe('resetData()', () => {
it('should add $index to elements in data[] and sets originalData and formData with data', async () => {
data = [{
name: 'Tony',
lastName: 'Stark',
age: 42,
}];
vm.resetData(data);
expect(vm.originalData).toEqual(data);
expect(vm.originalData[0].$index).toEqual(0);
expect(vm.formData).toEqual(data);
expect(vm.formData[0].$index).toEqual(0);
expect(vm.watchChanges).not.toBeNull();
});
it('should dont do nothing if data is null', async () => {
vm.resetData(null);
expect(vm.watchChanges).toBeNull();
});
it('should set originalData and formatData with data and generate watchChanges', async () => {
data = {
name: 'Tony',
lastName: 'Stark',
age: 42,
};
vm.resetData(data);
expect(vm.originalData).toEqual(data);
expect(vm.formData).toEqual(data);
expect(vm.watchChanges).not.toBeNull();
});
});
describe('saveChanges()', () => {
data = [{
name: 'Tony',
lastName: 'Stark',
age: 42,
}];
it('should call saveFn if exists', async () => {
await wrapper.setProps({ saveFn: vi.fn() });
vm.saveChanges(data);
expect(vm.saveFn).toHaveBeenCalledOnce();
expect(vm.isLoading).toBe(false);
expect(vm.hasChanges).toBe(false);
await wrapper.setProps({ saveFn: '' });
});
it("should use default url if there's not saveFn", async () => {
const postMock =vi.spyOn(axios, 'post');
vm.formData = [{
name: 'Bruce',
lastName: 'Wayne',
age: 45,
}]
await vm.saveChanges(data);
expect(postMock).toHaveBeenCalledWith(vm.url + '/crud', data);
expect(vm.isLoading).toBe(false);
expect(vm.hasChanges).toBe(false);
expect(vm.originalData).toEqual(JSON.parse(JSON.stringify(vm.formData)));
});
});
});

View File

@ -1,56 +0,0 @@
import { createWrapper, axios } from 'app/test/vitest/helper';
import EditForm from 'components/EditTableCellValueForm.vue';
import { vi, afterEach, beforeAll, describe, expect, it } from 'vitest';
const fieldA = 'fieldA';
const fieldB = 'fieldB';
describe('EditForm', () => {
let vm;
const mockRows = [
{ id: 1, itemFk: 101 },
{ id: 2, itemFk: 102 },
];
const mockFieldsOptions = [
{ label: 'Field A', field: fieldA, component: 'input', attrs: {} },
{ label: 'Field B', field: fieldB, component: 'date', attrs: {} },
];
const editUrl = '/api/edit';
beforeAll(() => {
vi.spyOn(axios, 'post').mockResolvedValue({ status: 200 });
vm = createWrapper(EditForm, {
props: {
rows: mockRows,
fieldsOptions: mockFieldsOptions,
editUrl,
},
}).vm;
});
afterEach(() => {
vi.clearAllMocks();
});
describe('onSubmit()', () => {
it('should call axios.post with the correct parameters in the payload', async () => {
const selectedField = { field: fieldA, component: 'input', attrs: {} };
const newValue = 'Test Value';
vm.selectedField = selectedField;
vm.newValue = newValue;
await vm.onSubmit();
const payload = axios.post.mock.calls[0][1];
expect(axios.post).toHaveBeenCalledWith(editUrl, expect.any(Object));
expect(payload.field).toEqual(fieldA);
expect(payload.newValue).toEqual(newValue);
expect(payload.lines).toEqual(expect.arrayContaining(mockRows));
expect(vm.isLoading).toEqual(false);
});
});
});

View File

@ -1,82 +0,0 @@
import { createWrapper, axios } from 'app/test/vitest/helper';
import FilterItemForm from 'src/components/FilterItemForm.vue';
import { vi, beforeAll, describe, expect, it } from 'vitest';
describe('FilterItemForm', () => {
let vm;
let wrapper;
beforeAll(() => {
wrapper = createWrapper(FilterItemForm, {
props: {
url: 'Items/withName',
},
});
vm = wrapper.vm;
wrapper = wrapper.wrapper;
vi.spyOn(axios, 'get').mockResolvedValue({
data: [
{
id: 999996,
name: 'bolas de madera',
size: 2,
inkFk: null,
producerFk: null,
},
],
});
});
it('should filter data and populate tableRows for table display', async () => {
vm.itemFilterParams.name = 'bolas de madera';
await vm.onSubmit();
const expectedFilter = {
include: [
{ relation: 'producer', scope: { fields: ['name'] } },
{ relation: 'ink', scope: { fields: ['name'] } },
],
where: {"name":{"like":"%bolas de madera%"}},
};
expect(axios.get).toHaveBeenCalledWith('Items/withName', {
params: { filter: JSON.stringify(expectedFilter) },
});
expect(vm.tableRows).toEqual([
{
id: 999996,
name: 'bolas de madera',
size: 2,
inkFk: null,
producerFk: null,
},
]);
});
it('should handle an empty itemFilterParams correctly', async () => {
vm.itemFilterParams.name = null;
vm.itemFilterParams = {};
await vm.onSubmit();
const expectedFilter = {
include: [
{ relation: 'producer', scope: { fields: ['name'] } },
{ relation: 'ink', scope: { fields: ['name'] } },
],
where: {},
};
expect(axios.get).toHaveBeenCalledWith('Items/withName', {
params: { filter: JSON.stringify(expectedFilter) },
});
});
it('should emit "itemSelected" with the correct id and close the form', () => {
vm.selectItem({ id: 12345 });
expect(wrapper.emitted('itemSelected')[0]).toEqual([12345]);
});
});

View File

@ -1,149 +0,0 @@
import { describe, expect, it, beforeAll, vi, afterAll } from 'vitest';
import { createWrapper, axios } from 'app/test/vitest/helper';
import FormModel from 'src/components/FormModel.vue';
describe('FormModel', () => {
const model = 'mockModel';
const url = 'mockUrl';
const formInitialData = { mockKey: 'mockVal' };
describe('modelValue', () => {
it('should use the provided model', () => {
const { vm } = mount({ propsData: { model } });
expect(vm.modelValue).toBe(model);
});
it('should use the route meta title when model is not provided', () => {
const { vm } = mount({});
expect(vm.modelValue).toBe('formModel_mockTitle');
});
});
describe('onMounted()', () => {
let mockGet;
beforeAll(() => {
mockGet = vi.spyOn(axios, 'get').mockResolvedValue({ data: {} });
});
afterAll(() => {
mockGet.mockRestore();
});
it('should not fetch when has formInitialData', () => {
mount({ propsData: { url, model, autoLoad: true, formInitialData } });
expect(mockGet).not.toHaveBeenCalled();
});
it('should fetch when there is url and auto-load', () => {
mount({ propsData: { url, model, autoLoad: true } });
expect(mockGet).toHaveBeenCalled();
});
it('should not observe changes', () => {
const { vm } = mount({
propsData: { url, model, observeFormChanges: false, formInitialData },
});
expect(vm.hasChanges).toBe(true);
vm.reset();
expect(vm.hasChanges).toBe(true);
});
it('should observe changes', async () => {
const { vm } = mount({
propsData: { url, model, formInitialData },
});
vm.state.set(model, formInitialData);
expect(vm.hasChanges).toBe(false);
vm.formData.mockKey = 'newVal';
await vm.$nextTick();
expect(vm.hasChanges).toBe(true);
vm.formData.mockKey = 'mockVal';
});
});
describe('trimData()', () => {
let vm;
beforeAll(() => {
vm = mount({}).vm;
});
it('should trim whitespace from string values', () => {
const data = { key1: ' value1 ', key2: ' value2 ' };
const trimmedData = vm.trimData(data);
expect(trimmedData).toEqual({ key1: 'value1', key2: 'value2' });
});
it('should not modify non-string values', () => {
const data = { key1: 123, key2: true, key3: null, key4: undefined };
const trimmedData = vm.trimData(data);
expect(trimmedData).toEqual(data);
});
});
describe('save()', async () => {
it('should not call if there are not changes', async () => {
const { vm } = mount({ propsData: { url, model } });
await vm.save();
expect(vm.hasChanges).toBe(false);
});
it('should call axios.patch with the right data', async () => {
const spy = vi.spyOn(axios, 'patch').mockResolvedValue({ data: {} });
const { vm } = mount({ propsData: { url, model, formInitialData } });
vm.formData.mockKey = 'newVal';
await vm.$nextTick();
await vm.save();
expect(spy).toHaveBeenCalled();
vm.formData.mockKey = 'mockVal';
});
it('should call axios.post with the right data', async () => {
const spy = vi.spyOn(axios, 'post').mockResolvedValue({ data: {} });
const { vm } = mount({
propsData: { url, model, formInitialData, urlCreate: 'mockUrlCreate' },
});
vm.formData.mockKey = 'newVal';
await vm.$nextTick();
await vm.save();
expect(spy).toHaveBeenCalled();
vm.formData.mockKey = 'mockVal';
});
it('should use the saveFn', async () => {
const { vm } = mount({
propsData: { url, model, formInitialData, saveFn: () => {} },
});
const spyPatch = vi.spyOn(axios, 'patch').mockResolvedValue({ data: {} });
const spySaveFn = vi.spyOn(vm.$props, 'saveFn');
vm.formData.mockKey = 'newVal';
await vm.$nextTick();
await vm.save();
expect(spyPatch).not.toHaveBeenCalled();
expect(spySaveFn).toHaveBeenCalled();
vm.formData.mockKey = 'mockVal';
});
it('should reload the data after save', async () => {
const { vm } = mount({
propsData: { url, model, formInitialData, reload: true },
});
vi.spyOn(axios, 'patch').mockResolvedValue({ data: {} });
vm.formData.mockKey = 'newVal';
await vm.$nextTick();
await vm.save();
vm.formData.mockKey = 'mockVal';
});
});
});
function mount({ propsData = {} }) {
return createWrapper(FormModel, {
propsData,
});
}

View File

@ -1,20 +1,32 @@
<script setup>
import { onMounted, useSlots } from 'vue';
import { ref, onMounted, useSlots } from 'vue';
import { useI18n } from 'vue-i18n';
import { useStateStore } from 'stores/useStateStore';
import { useQuasar } from 'quasar';
import { useHasContent } from 'src/composables/useHasContent';
const { t } = useI18n();
const quasar = useQuasar();
const stateStore = useStateStore();
const slots = useSlots();
const hasContent = useHasContent('#right-panel');
const hasContent = ref(false);
const rightPanel = ref(null);
onMounted(() => {
if ((!slots['right-panel'] && !hasContent.value) || quasar.platform.is.mobile)
stateStore.rightDrawer = false;
rightPanel.value = document.querySelector('#right-panel');
if (!rightPanel.value) return;
// Check if there's content to display
const observer = new MutationObserver(() => {
hasContent.value = rightPanel.value.childNodes.length;
});
observer.observe(rightPanel.value, {
subtree: true,
childList: true,
attributes: true,
});
if (!slots['right-panel'] && !hasContent.value) stateStore.rightDrawer = false;
});
const { t } = useI18n();
const stateStore = useStateStore();
</script>
<template>
<Teleport to="#actions-append" v-if="stateStore.isHeaderMounted()">
@ -33,7 +45,7 @@ onMounted(() => {
</QBtn>
</div>
</Teleport>
<QDrawer v-model="stateStore.rightDrawer" side="right" :width="256">
<QDrawer v-model="stateStore.rightDrawer" side="right" :width="256" show-if-above>
<QScrollArea class="fit">
<div id="right-panel"></div>
<slot v-if="!hasContent" name="right-panel" />

View File

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

View File

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

View File

@ -15,7 +15,7 @@ let root = ref(null);
watchEffect(() => {
matched.value = currentRoute.value.matched.filter(
(matched) => !!matched?.meta?.title || !!matched?.meta?.icon
(matched) => Object.keys(matched.meta).length
);
breadcrumbs.value.length = 0;
if (!matched.value[0]) return;

View File

@ -14,7 +14,6 @@ defineProps({
hide-dropdown-icon
focus-on-mount
@update:model-value="promise"
data-cy="vnBtnSelect_select"
/>
</QBtnDropdown>
</template>

View File

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

View File

@ -2,9 +2,9 @@
import { ref } from 'vue';
import { useI18n } from 'vue-i18n';
import VnRow from '../ui/VnRow.vue';
import VnInput from './VnInput.vue';
import FetchData from '../FetchData.vue';
import useNotify from 'src/composables/useNotify';
import VnInputPassword from 'src/components/common/VnInputPassword.vue';
const props = defineProps({
submitFn: { type: Function, default: () => {} },
@ -70,19 +70,19 @@ defineExpose({ show: () => changePassDialog.value.show() });
</QCardSection>
<QForm ref="form">
<QCardSection>
<VnInputPassword
<VnInput
v-if="props.askOldPass"
:label="t('Old password')"
v-model="passwords.oldPassword"
type="password"
:required="true"
:toggle-visibility="true"
autofocus
/>
<VnInputPassword
<VnInput
:label="t('New password')"
v-model="passwords.newPassword"
type="password"
:required="true"
:toggle-visibility="true"
:info="
t('passwordRequirements', {
length: requirements.length,
@ -95,10 +95,10 @@ defineExpose({ show: () => changePassDialog.value.show() });
autofocus
/>
<VnInputPassword
<VnInput
:label="t('Repeat password')"
v-model="passwords.repeatPassword"
:toggle-visibility="true"
type="password"
/>
</QCardSection>
</QForm>

View File

@ -1,5 +1,5 @@
<script setup>
import { computed } from 'vue';
import { computed, defineModel } from 'vue';
const model = defineModel(undefined, { required: true });
const $props = defineProps({

View File

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

View File

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

View File

@ -297,7 +297,7 @@ defineExpose({
ref="dmsRef"
:data-key="$props.model"
:url="$props.model"
:user-filter="dmsFilter"
:filter="dmsFilter"
:order="['dmsFk DESC']"
:auto-load="true"
@on-fetch="setData"

View File

@ -1,11 +1,8 @@
<script setup>
import { computed, ref, useAttrs, nextTick } from 'vue';
import { computed, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRequired } from 'src/composables/useRequired';
import { useValidator } from 'src/composables/useValidator';
const $attrs = useAttrs();
const { isRequired, requiredFieldRule } = useRequired($attrs);
const { t } = useI18n();
const emit = defineEmits([
'update:modelValue',
'update:options',
@ -30,28 +27,18 @@ const $props = defineProps({
type: Boolean,
default: true,
},
emptyToNull: {
type: Boolean,
default: true,
},
insertable: {
type: Boolean,
default: false,
},
maxlength: {
type: Number,
default: null,
},
});
const { validations } = useValidator();
const { t } = useI18n();
const requiredFieldRule = (val) => validations().required($attrs.required, val);
const vnInputRef = ref(null);
const showPassword = ref(false);
const value = computed({
get() {
return $props.modelValue;
},
set(value) {
if ($props.emptyToNull && value === '') value = null;
emit('update:modelValue', value);
},
});
@ -73,14 +60,13 @@ const focus = () => {
defineExpose({
focus,
});
import { useAttrs } from 'vue';
const $attrs = useAttrs();
const mixinRules = [
requiredFieldRule,
...($attrs.rules ?? []),
(val) => {
const { maxlength } = vnInputRef.value;
if (maxlength && +val.length > maxlength)
return t(`maxLength`, { value: maxlength });
const { min, max } = vnInputRef.value.$attrs;
if (!min) return null;
if (min >= 0) if (Math.floor(val) < min) return t('inputMin', { value: min });
@ -90,33 +76,6 @@ const mixinRules = [
}
},
];
const handleKeydown = (e) => {
if (e.key === 'Backspace') return;
if ($props.insertable && e.key.match(/[0-9]/)) {
handleInsertMode(e);
}
};
const handleInsertMode = (e) => {
e.preventDefault();
const input = e.target;
const cursorPos = input.selectionStart;
const { maxlength } = vnInputRef.value;
let currentValue = value.value;
if (!currentValue) currentValue = e.key;
const newValue = e.key;
if (newValue && !isNaN(newValue) && cursorPos < maxlength) {
value.value =
currentValue.substring(0, cursorPos) +
newValue +
currentValue.substring(cursorPos + 1);
}
nextTick(() => {
input.setSelectionRange(cursorPos + 1, cursorPos + 1);
});
};
</script>
<template>
@ -126,32 +85,21 @@ const handleInsertMode = (e) => {
v-model="value"
v-bind="{ ...$attrs, ...styleAttrs }"
:type="$attrs.type"
:class="{ required: isRequired }"
:class="{ required: $attrs.required }"
@keyup.enter="emit('keyup.enter')"
@keydown="handleKeydown"
:clearable="false"
:rules="mixinRules"
:lazy-rules="true"
hide-bottom-space
:data-cy="$attrs.dataCy ?? $attrs.label + '_input'"
>
<template #prepend>
<template v-if="$slots.prepend" #prepend>
<slot name="prepend" />
</template>
<template #append>
<QIcon
name="close"
size="xs"
:style="{
visibility:
hover &&
value &&
!$attrs.disabled &&
!$attrs.readonly &&
$props.clearable
? 'visible'
: 'hidden',
}"
v-if="hover && value && !$attrs.disabled && $props.clearable"
@click="
() => {
value = null;
@ -159,7 +107,7 @@ const handleInsertMode = (e) => {
emit('remove');
}
"
/>
></QIcon>
<slot name="append" v-if="$slots.append && !$attrs.disabled" />
<QIcon v-if="info" name="info">
<QTooltip max-width="350px">
@ -170,3 +118,16 @@ const handleInsertMode = (e) => {
</QInput>
</div>
</template>
<i18n>
en:
inputMin: Must be more than {value}
inputMax: Must be less than {value}
es:
inputMin: Debe ser mayor a {value}
inputMax: Debe ser menor a {value}
</i18n>
<style lang="scss">
.q-field__append {
padding-inline: 0;
}
</style>

View File

@ -1,13 +1,11 @@
<script setup>
import { onMounted, watch, computed, ref, useAttrs } from 'vue';
import { onMounted, watch, computed, ref } from 'vue';
import { date } from 'quasar';
import { useI18n } from 'vue-i18n';
import { useAttrs } from 'vue';
import VnDate from './VnDate.vue';
import { useRequired } from 'src/composables/useRequired';
const $attrs = useAttrs();
const { isRequired, requiredFieldRule } = useRequired($attrs);
const model = defineModel({ type: [String, Date] });
const $props = defineProps({
isOutlined: {
type: Boolean,
@ -18,13 +16,18 @@ const $props = defineProps({
default: true,
},
});
import { useValidator } from 'src/composables/useValidator';
const { validations } = useValidator();
const { t } = useI18n();
const requiredFieldRule = (val) => validations().required($attrs.required, val);
const vnInputDateRef = ref(null);
const dateFormat = 'DD/MM/YYYY';
const isPopupOpen = ref();
const hover = ref();
const mask = ref();
const $attrs = useAttrs();
const mixinRules = [requiredFieldRule, ...($attrs.rules ?? [])];
@ -101,10 +104,10 @@ const manageDate = (date) => {
:mask="mask"
placeholder="dd/mm/aaaa"
v-bind="{ ...$attrs, ...styleAttrs }"
:class="{ required: isRequired }"
:class="{ required: $attrs.required }"
:rules="mixinRules"
:clearable="false"
@click="isPopupOpen = !isPopupOpen"
@click="isPopupOpen = true"
hide-bottom-space
>
<template #append>
@ -123,6 +126,13 @@ const manageDate = (date) => {
isPopupOpen = false;
"
/>
<QIcon
v-if="showEvent"
name="event"
class="cursor-pointer"
@click="isPopupOpen = !isPopupOpen"
:title="t('Open date')"
/>
</template>
<QMenu
v-if="$q.screen.gt.xs"
@ -142,6 +152,15 @@ const manageDate = (date) => {
</QInput>
</div>
</template>
<style lang="scss">
.vn-input-date.q-field--standard.q-field--readonly .q-field__control:before {
border-bottom-style: solid;
}
.vn-input-date.q-field--outlined.q-field--readonly .q-field__control:before {
border-style: solid;
}
</style>
<i18n>
es:
Open date: Abrir fecha

View File

@ -1,28 +1,8 @@
<script setup>
import VnInput from 'src/components/common/VnInput.vue';
defineProps({
step: { type: Number, default: 0.01 },
decimalPlaces: { type: Number, default: 2 },
positive: { type: Boolean, default: true },
});
const model = defineModel({ type: [Number, String] });
</script>
<template>
<VnInput
v-bind="$attrs"
v-model.number="model"
type="number"
:step="step"
@input="
(evt) => {
const val = evt.target.value;
if (positive && val < 0) return (model = 0);
const [, decimal] = val.split('.');
if (val && decimal?.length > decimalPlaces)
model = parseFloat(val).toFixed(decimalPlaces);
}
"
/>
<VnInput v-bind="$attrs" v-model.number="model" type="number" />
</template>

View File

@ -1,31 +0,0 @@
<script setup>
import VnInput from 'src/components/common/VnInput.vue';
import { ref } from 'vue';
const model = defineModel({ type: [Number, String] });
const $props = defineProps({
toggleVisibility: {
type: Boolean,
default: false,
},
});
const showPassword = ref(false);
</script>
<template>
<VnInput
v-bind="{ ...$attrs }"
v-model="model"
:type="
$props.toggleVisibility ? (showPassword ? 'text' : 'password') : $attrs.type
"
>
<template #append v-if="toggleVisibility">
<QIcon
:name="showPassword ? 'visibility_off' : 'visibility'"
class="cursor-pointer"
@click="showPassword = !showPassword"
/>
</template>
</VnInput>
</template>

View File

@ -1,11 +1,12 @@
<script setup>
import { computed, ref, useAttrs } from 'vue';
import { useI18n } from 'vue-i18n';
import { date } from 'quasar';
import { useValidator } from 'src/composables/useValidator';
import VnTime from './VnTime.vue';
import { useRequired } from 'src/composables/useRequired';
const { validations } = useValidator();
const $attrs = useAttrs();
const { isRequired, requiredFieldRule } = useRequired($attrs);
const model = defineModel({ type: String });
const props = defineProps({
timeOnly: {
@ -19,6 +20,8 @@ const props = defineProps({
});
const vnInputTimeRef = ref(null);
const initialDate = ref(model.value ?? Date.vnNew());
const { t } = useI18n();
const requiredFieldRule = (val) => validations().required($attrs.required, val);
const mixinRules = [requiredFieldRule, ...($attrs.rules ?? [])];
const dateFormat = 'HH:mm';
const isPopupOpen = ref();
@ -75,10 +78,10 @@ function dateToTime(newDate) {
placeholder="--:--"
v-model="formattedTime"
v-bind="{ ...$attrs, ...styleAttrs }"
:class="{ required: isRequired }"
:class="{ required: $attrs.required }"
style="min-width: 100px"
:rules="mixinRules"
@click="isPopupOpen = !isPopupOpen"
@click="isPopupOpen = false"
type="time"
hide-bottom-space
>
@ -98,6 +101,12 @@ function dateToTime(newDate) {
isPopupOpen = false;
"
/>
<QIcon
name="Schedule"
class="cursor-pointer"
@click="isPopupOpen = !isPopupOpen"
:title="t('Open time')"
/>
</template>
<QMenu
v-if="$q.screen.gt.xs"

View File

@ -2,13 +2,10 @@
import CreateNewPostcode from 'src/components/CreateNewPostcodeForm.vue';
import VnSelectDialog from 'components/common/VnSelectDialog.vue';
import { useI18n } from 'vue-i18n';
import { ref, watch } from 'vue';
import { useAttrs } from 'vue';
import { useRequired } from 'src/composables/useRequired';
import { ref } from 'vue';
const { t } = useI18n();
const emit = defineEmits(['update:model-value', 'update:options']);
const $attrs = useAttrs();
const { isRequired, requiredFieldRule } = useRequired($attrs);
const props = defineProps({
location: {
type: Object,
@ -16,15 +13,6 @@ const props = defineProps({
},
});
watch(
() => props.location,
(newValue) => {
if (!modelValue.value) return;
modelValue.value = formatLocation(newValue) ?? null;
}
);
const mixinRules = [requiredFieldRule];
const locationProperties = [
'postcode',
(obj) =>
@ -34,7 +22,7 @@ const locationProperties = [
(obj) => obj.country?.name,
];
const formatLocation = (obj, properties = locationProperties) => {
const formatLocation = (obj, properties) => {
const parts = properties.map((prop) => {
if (typeof prop === 'string') {
return obj[prop];
@ -51,7 +39,9 @@ const formatLocation = (obj, properties = locationProperties) => {
return filteredParts.join(', ');
};
const modelValue = ref(props.location ? formatLocation(props.location) : null);
const modelValue = ref(
props.location ? formatLocation(props.location, locationProperties) : null
);
function showLabel(data) {
const dataProperties = [
@ -79,12 +69,11 @@ const handleModelValue = (data) => {
:label="t('Location')"
:placeholder="t('search_by_postalcode')"
:input-debounce="300"
:class="{ required: isRequired }"
:class="{ required: $attrs.required }"
v-bind="$attrs"
clearable
:emit-value="false"
:tooltip="t('Create new location')"
:rules="mixinRules"
:lazy-rules="true"
>
<template #form>
<CreateNewPostcode

View File

@ -238,7 +238,6 @@ async function openPointRecord(id, modelLog) {
pointRecord.value = parseProps(propNames, locale, data);
}
async function setLogTree(data) {
if (!data) return;
logTree.value = getLogTree(data);
}

View File

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

View File

@ -1,97 +0,0 @@
<script setup>
import RightMenu from './RightMenu.vue';
import VnSearchbar from 'components/ui/VnSearchbar.vue';
import VnTableFilter from '../VnTable/VnTableFilter.vue';
import { onBeforeMount, computed, ref } from 'vue';
import { useArrayData } from 'src/composables/useArrayData';
import { useRoute } from 'vue-router';
import { useHasContent } from 'src/composables/useHasContent';
const $props = defineProps({
section: {
type: String,
default: null,
},
dataKey: {
type: String,
default: null,
},
searchBar: {
type: Boolean,
default: true,
},
prefix: {
type: String,
default: null,
},
rightFilter: {
type: Boolean,
default: true,
},
columns: {
type: Array,
default: null,
},
arrayDataProps: {
type: Object,
default: null,
},
redirect: {
type: Boolean,
default: true,
},
keepData: {
type: Boolean,
default: true,
},
});
const route = useRoute();
let arrayData;
const sectionValue = computed(() => $props.section ?? $props.dataKey);
const isMainSection = computed(() => {
const isSame = sectionValue.value == route.name;
if (!isSame && arrayData) {
arrayData.reset(['userParams', 'userFilter']);
}
return isSame;
});
const searchbarId = 'section-searchbar';
const hasContent = useHasContent(`#${searchbarId}`);
onBeforeMount(() => {
if ($props.dataKey)
arrayData = useArrayData($props.dataKey, {
searchUrl: 'table',
keepData: $props.keepData,
...$props.arrayDataProps,
navigate: $props.redirect,
});
});
</script>
<template>
<slot name="searchbar">
<VnSearchbar
v-if="searchBar && !hasContent"
v-bind="arrayDataProps"
:data-key="dataKey"
:label="$t(`${prefix}.search`)"
:info="$t(`${prefix}.searchInfo`)"
/>
<div :id="searchbarId"></div>
</slot>
<RightMenu>
<template #right-panel v-if="$slots['rightMenu'] || rightFilter">
<slot name="rightMenu">
<VnTableFilter
v-if="rightFilter && columns"
:data-key="dataKey"
:array-data="arrayData"
:columns="columns"
/>
</slot>
</template>
</RightMenu>
<slot name="body" v-if="isMainSection" />
<RouterView v-else />
</template>

View File

@ -1,8 +1,8 @@
<script setup>
import { useStateStore } from 'stores/useStateStore';
import { onMounted, ref } from 'vue';
import LeftMenu from 'components/LeftMenu.vue';
import { onMounted } from 'vue';
import { useQuasar } from 'quasar';
import LeftMenu from '../LeftMenu.vue';
const stateStore = useStateStore();
const $props = defineProps({
@ -14,29 +14,12 @@ const $props = defineProps({
onMounted(
() => (stateStore.leftDrawer = useQuasar().screen.gt.xs ? $props.leftDrawer : false)
);
const teleportRef = ref({});
const hasContent = ref();
let observer;
onMounted(() => {
if (!teleportRef.value) return;
const checkContent = () => {
hasContent.value = teleportRef.value?.innerHTML?.trim() !== '';
};
observer = new MutationObserver(checkContent);
observer.observe(teleportRef.value, { childList: true, subtree: true });
checkContent();
});
</script>
<template>
<QDrawer v-model="stateStore.leftDrawer" show-if-above :width="256">
<QScrollArea class="fit text-grey-8">
<div id="left-panel" ref="teleportRef"></div>
<LeftMenu v-if="!hasContent" />
<LeftMenu />
</QScrollArea>
</QDrawer>
<QPageContainer>

View File

@ -1,21 +1,9 @@
<script setup>
import { ref, toRefs, computed, watch, onMounted, useAttrs } from 'vue';
import { useI18n } from 'vue-i18n';
import { useArrayData } from 'src/composables/useArrayData';
import { useRequired } from 'src/composables/useRequired';
import dataByOrder from 'src/utils/dataByOrder';
import { QItemLabel } from 'quasar';
import FetchData from 'src/components/FetchData.vue';
import { useValidator } from 'src/composables/useValidator';
const emit = defineEmits(['update:modelValue', 'update:options', 'remove']);
const $attrs = useAttrs();
const { t } = useI18n();
const isRequired = computed(() => {
return useRequired($attrs).isRequired;
});
const requiredFieldRule = computed(() => {
return useRequired($attrs).requiredFieldRule;
});
const $props = defineProps({
modelValue: {
@ -34,10 +22,6 @@ const $props = defineProps({
type: String,
default: 'id',
},
optionCaption: {
type: String,
default: null,
},
optionFilter: {
type: String,
default: null,
@ -102,46 +86,25 @@ const $props = defineProps({
type: Boolean,
default: false,
},
dataKey: {
type: String,
default: null,
},
isOutlined: {
type: Boolean,
default: false,
},
});
const { validations } = useValidator();
const requiredFieldRule = (val) => validations().required($attrs.required, val);
const $attrs = useAttrs();
const { t } = useI18n();
const mixinRules = [requiredFieldRule, ...($attrs.rules ?? [])];
const {
optionLabel,
optionValue,
optionCaption,
optionFilter,
optionFilterValue,
options,
modelValue,
} = toRefs($props);
const { optionLabel, optionValue, optionFilter, optionFilterValue, options, modelValue } =
toRefs($props);
const myOptions = ref([]);
const myOptionsOriginal = ref([]);
const vnSelectRef = ref();
const dataRef = ref();
const lastVal = ref();
const noOneText = t('globals.noOne');
const noOneOpt = ref({
[optionValue.value]: false,
[optionLabel.value]: noOneText,
});
const styleAttrs = computed(() => {
return $props.isOutlined
? {
dense: true,
outlined: true,
rounded: true,
}
: {};
});
const isLoading = ref(false);
const useURL = computed(() => $props.url);
const value = computed({
get() {
return $props.modelValue;
@ -157,7 +120,7 @@ watch(options, (newValue) => {
});
watch(modelValue, async (newValue) => {
if (!myOptions?.value?.some((option) => option[optionValue.value] == newValue))
if (!myOptions.value.some((option) => option[optionValue.value] == newValue))
await fetchFilter(newValue);
if ($props.noOne) myOptions.value.unshift(noOneOpt.value);
@ -165,27 +128,17 @@ watch(modelValue, async (newValue) => {
onMounted(() => {
setOptions(options.value);
if (useURL.value && $props.modelValue && !findKeyInOptions())
if ($props.url && $props.modelValue && !findKeyInOptions())
fetchFilter($props.modelValue);
if ($props.focusOnMount) setTimeout(() => vnSelectRef.value.showPopup(), 300);
});
const arrayDataKey =
$props.dataKey ?? ($props.url?.length > 0 ? $props.url : $attrs.name ?? $attrs.label);
const arrayData = useArrayData(arrayDataKey, {
url: $props.url,
searchUrl: false,
mapKey: $attrs['map-key'],
});
function findKeyInOptions() {
if (!$props.options) return;
return filter($props.modelValue, $props.options)?.length;
}
function setOptions(data) {
data = dataByOrder(data, $props.sortBy);
myOptions.value = JSON.parse(JSON.stringify(data));
myOptionsOriginal.value = JSON.parse(JSON.stringify(data));
emit('update:options', data);
@ -205,15 +158,15 @@ function filter(val, options) {
}
if (!row) return;
const id = String(row[$props.optionValue]);
const id = row[$props.optionValue];
const optionLabel = String(row[$props.optionLabel]).toLowerCase();
return id.includes(search) || optionLabel.includes(search);
return id == search || optionLabel.includes(search);
});
}
async function fetchFilter(val) {
if (!$props.url) return;
if (!$props.url || !dataRef.value) return;
const { fields, include, sortBy, limit } = $props;
const key =
@ -235,11 +188,8 @@ async function fetchFilter(val) {
const fetchOptions = { where, include, limit };
if (fields) fetchOptions.fields = fields;
if (sortBy) fetchOptions.order = sortBy;
arrayData.resetPagination();
const { data } = await arrayData.applyFilter({ filter: fetchOptions });
setOptions(data);
return data;
return dataRef.value.fetch(fetchOptions);
}
async function filterHandler(val, update) {
@ -279,69 +229,26 @@ function nullishToTrue(value) {
const getVal = (val) => ($props.useLike ? { like: `%${val}%` } : val);
async function onScroll({ to, direction, from, index }) {
const lastIndex = myOptions.value.length - 1;
if (from === 0 && index === 0) return;
if (!useURL.value && !$props.fetchRef) return;
if (direction === 'decrease') return;
if (to === lastIndex && arrayData.store.hasMoreData && !isLoading.value) {
isLoading.value = true;
await arrayData.loadMore();
setOptions(arrayData.store.data);
vnSelectRef.value.scrollTo(lastIndex);
isLoading.value = false;
}
}
defineExpose({ opts: myOptions });
function handleKeyDown(event) {
if (event.key === 'Tab' && !event.shiftKey) {
event.preventDefault();
const inputValue = vnSelectRef.value?.inputValue;
if (inputValue) {
const matchingOption = myOptions.value.find(
(option) =>
option[optionLabel.value].toLowerCase() === inputValue.toLowerCase()
);
if (matchingOption) {
emit('update:modelValue', matchingOption[optionValue.value]);
} else {
emit('update:modelValue', inputValue);
}
vnSelectRef.value?.hidePopup();
}
const focusableElements = document.querySelectorAll(
'a: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(
focusableElements,
event.target
);
if (currentIndex >= 0 && currentIndex < focusableElements.length - 1) {
focusableElements[currentIndex + 1].focus();
}
}
}
function getCaption(opt) {
if (optionCaption.value === false) return;
return opt[optionCaption.value] || opt[optionValue.value];
}
</script>
<template>
<FetchData
ref="dataRef"
:url="$props.url"
@on-fetch="(data) => setOptions(data)"
:where="where || { [optionValue]: value }"
:limit="limit"
:sort-by="sortBy"
:fields="fields"
:params="params"
/>
<QSelect
v-model="value"
:options="myOptions"
:option-label="optionLabel"
:option-value="optionValue"
v-bind="{ ...$attrs, ...styleAttrs }"
v-bind="$attrs"
@filter="filterHandler"
:emit-value="nullishToTrue($attrs['emit-value'])"
:map-options="nullishToTrue($attrs['map-options'])"
@ -350,22 +257,16 @@ function getCaption(opt) {
:fill-input="nullishToTrue($attrs['fill-input'])"
ref="vnSelectRef"
lazy-rules
:class="{ required: isRequired }"
:class="{ required: $attrs.required }"
:rules="mixinRules"
virtual-scroll-slice-size="options.length"
hide-bottom-space
:input-debounce="useURL ? '300' : '0'"
:loading="isLoading"
@virtual-scroll="onScroll"
@keydown="handleKeyDown"
:data-cy="$attrs.dataCy ?? $attrs.label + '_select'"
:data-url="url"
>
<template #append>
<template v-if="isClearable" #append>
<QIcon
v-show="isClearable && value"
v-show="value"
name="close"
@click="
@click.stop="
() => {
value = null;
emit('remove');
@ -376,38 +277,7 @@ function getCaption(opt) {
/>
</template>
<template v-for="(_, slotName) in $slots" #[slotName]="slotData" :key="slotName">
<div v-if="slotName == 'append'">
<QIcon
v-show="isClearable && value"
name="close"
@click.stop="
() => {
value = null;
emit('remove');
}
"
class="cursor-pointer"
size="xs"
/>
<slot name="append" v-if="$slots.append" v-bind="slotData ?? {}" />
</div>
<slot v-else :name="slotName" v-bind="slotData ?? {}" :key="slotName" />
</template>
<template #option="{ opt, itemProps }">
<QItem v-bind="itemProps">
<QItemSection v-if="typeof opt !== 'object'"> {{ opt }}</QItemSection>
<QItemSection v-else-if="opt[optionValue] == opt[optionLabel]">
<QItemLabel>{{ opt[optionLabel] }}</QItemLabel>
</QItemSection>
<QItemSection v-else>
<QItemLabel>
{{ opt[optionLabel] }}
</QItemLabel>
<QItemLabel caption v-if="getCaption(opt)">
{{ `#${getCaption(opt)}` }}
</QItemLabel>
</QItemSection>
</QItem>
<slot :name="slotName" v-bind="slotData ?? {}" :key="slotName" />
</template>
</QSelect>
</template>

View File

@ -43,7 +43,6 @@ const isAllowedToCreate = computed(() => {
>
<template v-if="isAllowedToCreate" #append>
<QIcon
:data-cy="$attrs.dataCy ?? $attrs.label + '_icon'"
@click.stop.prevent="$refs.dialog.show()"
:name="actionIcon"
:size="actionIcon === 'add' ? 'xs' : 'sm'"

View File

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

View File

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

View File

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

View File

@ -1,28 +0,0 @@
import { vi, describe, expect, it, beforeAll, afterEach } from 'vitest';
import { createWrapper } from 'app/test/vitest/helper';
import VnDiscount from 'components/common/vnDiscount.vue';
describe('VnDiscount', () => {
let vm;
beforeAll(() => {
vm = createWrapper(VnDiscount, {
props: {
data: {},
price: 100,
quantity: 2,
discount: 10,
}
}).vm;
});
afterEach(() => {
vi.clearAllMocks();
});
describe('total', () => {
it('should calculate total correctly', () => {
expect(vm.total).toBe(180);
});
});
});

View File

@ -1,87 +0,0 @@
import { createWrapper, axios } from 'app/test/vitest/helper';
import VnDmsList from 'src/components/common/VnDmsList.vue';
import { vi, afterEach, beforeAll, describe, expect, it } from 'vitest';
describe('VnDmsList', () => {
let vm;
const dms = {
userFk: 1,
name: 'DMS 1'
};
beforeAll(() => {
vi.spyOn(axios, 'get').mockResolvedValue({ data: [] });
vm = createWrapper(VnDmsList, {
props: {
model: 'WorkerDms/1110/filter',
defaultDmsCode: 'hhrrData',
filter: 'wd.workerFk',
updateModel: 'Workers',
deleteModel: 'WorkerDms',
downloadModel: 'WorkerDms'
}
}).vm;
});
afterEach(() => {
vi.clearAllMocks();
});
describe('setData()', () => {
const data = [
{
userFk: 1,
name: 'Jessica',
lastName: 'Jones',
file: '4.jpg',
created: '2021-07-28 21:00:00'
},
{
userFk: 2,
name: 'Bruce',
lastName: 'Banner',
created: '2022-07-28 21:00:00',
dms: {
userFk: 2,
name: 'Bruce',
lastName: 'BannerDMS',
created: '2022-07-28 21:00:00',
file: '4.jpg',
}
},
{
userFk: 3,
name: 'Natasha',
lastName: 'Romanoff',
file: '4.jpg',
created: '2021-10-28 21:00:00'
}
]
it('Should replace objects that contain the "dms" property with the value of the same and sort by creation date', () => {
vm.setData(data);
expect([vm.rows][0][0].lastName).toEqual('BannerDMS');
expect([vm.rows][0][1].lastName).toEqual('Romanoff');
});
});
describe('parseDms()', () => {
const resultDms = { ...dms, userId:1};
it('Should add properties that end with "Fk" by changing the suffix to "Id"', () => {
const parsedDms = vm.parseDms(dms);
expect(parsedDms).toEqual(resultDms);
});
});
describe('showFormDialog()', () => {
const resultDms = { ...dms, userId:1};
it('should call fn parseDms() and set show true if dms is defined', () => {
vm.showFormDialog(dms);
expect(vm.formDialog.show).toEqual(true);
expect(vm.formDialog.dms).toEqual(resultDms);
});
});
});

View File

@ -1,72 +0,0 @@
import { createWrapper } from 'app/test/vitest/helper.js';
import { describe, it, expect } from 'vitest';
import VnInputDate from 'components/common/VnInputDate.vue';
let vm;
let wrapper;
function generateWrapper(date, outlined, required) {
wrapper = createWrapper(VnInputDate, {
props: {
modelValue: date,
},
attrs: {
isOutlined: outlined,
required: required
},
});
wrapper = wrapper.wrapper;
vm = wrapper.vm;
};
describe('VnInputDate', () => {
describe('formattedDate', () => {
it('formats a valid date correctly', async () => {
generateWrapper('2023-12-25', false, false);
await vm.$nextTick();
expect(vm.formattedDate).toBe('25/12/2023');
});
it('updates the model value when a new date is set', async () => {
const input = wrapper.find('input');
await input.setValue('31/12/2023');
expect(wrapper.emitted()['update:modelValue']).toBeTruthy();
expect(wrapper.emitted()['update:modelValue'][0][0]).toBe('2023-12-31T00:00:00.000Z');
});
it('should not update the model value when an invalid date is set', async () => {
const input = wrapper.find('input');
await input.setValue('invalid-date');
expect(wrapper.emitted()['update:modelValue'][0][0]).toBe('2023-12-31T00:00:00.000Z');
});
});
describe('styleAttrs', () => {
it('should return empty styleAttrs when isOutlined is false', async () => {
generateWrapper('2023-12-25', false, false);
await vm.$nextTick();
expect(vm.styleAttrs).toEqual({});
});
it('should set styleAttrs when isOutlined is true', async () => {
generateWrapper('2023-12-25', true, false);
await vm.$nextTick();
expect(vm.styleAttrs.outlined).toBe(true);
});
});
describe('required', () => {
it('should not applies required class when isRequired is false', async () => {
generateWrapper('2023-12-25', false, false);
await vm.$nextTick();
expect(wrapper.find('.vn-input-date').classes()).not.toContain('required');
});
it('should applies required class when isRequired is true', async () => {
generateWrapper('2023-12-25', false, true);
await vm.$nextTick();
expect(wrapper.find('.vn-input-date').classes()).toContain('required');
});
});
});

View File

@ -1,63 +0,0 @@
import { vi, describe, expect, it, beforeAll, afterEach } from 'vitest';
import { createWrapper } from 'app/test/vitest/helper';
import VnInputTime from 'components/common/VnInputTime.vue';
describe('VnInputTime', () => {
let wrapper;
let vm;
beforeAll(() => {
wrapper = createWrapper(VnInputTime, {
props: {
isOutlined: true,
timeOnly: false,
},
});
vm = wrapper.vm;
wrapper = wrapper.wrapper;
});
afterEach(() => {
vi.clearAllMocks();
});
it('should return the correct data if isOutlined is true', () => {
expect(vm.isOutlined).toBe(true);
expect(vm.styleAttrs).toEqual({ dense: true, outlined: true, rounded: true });
});
it('should return the formatted data', () => {
expect(vm.dateToTime('2022-01-01T03:23:43')).toBe('03:23');
});
describe('formattedTime', () => {
it('should return the formatted time for a valid ISO date', () => {
vm.model = '2025-01-02T15:45:00';
expect(vm.formattedTime).toBe('15:45');
});
it('should handle null model value gracefully', () => {
vm.model = null;
expect(vm.formattedTime).toBe(null);
});
it('should handle time-only input correctly', async () => {
await wrapper.setProps({ timeOnly: true });
vm.formattedTime = '14:30';
expect(vm.model).toBe('14:30');
});
it('should pad short time values correctly', async () => {
await wrapper.setProps({ timeOnly: true });
vm.formattedTime = '9';
expect(vm.model).toBe('09:00');
});
it('should not update the model if the value is unchanged', () => {
vm.model = '14:30';
const previousModel = vm.model;
vm.formattedTime = '14:30';
expect(vm.model).toBe(previousModel);
});
});
});

View File

@ -1,95 +0,0 @@
import { describe, it, expect } from 'vitest';
import VnJsonValue from 'src/components/common/VnJsonValue.vue';
import { createWrapper } from 'app/test/vitest/helper';
const buildComponent = (props) => {
return createWrapper(VnJsonValue, {
props,
}).wrapper;
};
describe('VnJsonValue', () => {
it('renders null value correctly', async () => {
const wrapper = buildComponent({ value: null });
const span = wrapper.find('span');
expect(span.text()).toBe('∅');
expect(span.classes()).toContain('json-null');
});
it('renders boolean true correctly', async () => {
const wrapper = buildComponent({ value: true });
const span = wrapper.find('span');
expect(span.text()).toBe('✓');
expect(span.classes()).toContain('json-true');
});
it('renders boolean false correctly', async () => {
const wrapper = buildComponent({ value: false });
const span = wrapper.find('span');
expect(span.text()).toBe('✗');
expect(span.classes()).toContain('json-false');
});
it('renders a short string correctly', async () => {
const wrapper = buildComponent({ value: 'Hello' });
const span = wrapper.find('span');
expect(span.text()).toBe('Hello');
expect(span.classes()).toContain('json-string');
});
it('renders a long string correctly with ellipsis', async () => {
const longString = 'a'.repeat(600);
const wrapper = buildComponent({ value: longString });
const span = wrapper.find('span');
expect(span.text()).toContain('...');
expect(span.text().length).toBeLessThanOrEqual(515);
expect(span.attributes('title')).toBe(longString);
expect(span.classes()).toContain('json-string');
});
it('renders a number correctly', async () => {
const wrapper = buildComponent({ value: 123.4567 });
const span = wrapper.find('span');
expect(span.text()).toBe('123.457');
expect(span.classes()).toContain('json-number');
});
it('renders an integer correctly', async () => {
const wrapper = buildComponent({ value: 42 });
const span = wrapper.find('span');
expect(span.text()).toBe('42');
expect(span.classes()).toContain('json-number');
});
it('renders a date correctly', async () => {
const date = new Date('2023-01-01');
const wrapper = buildComponent({ value: date });
const span = wrapper.find('span');
expect(span.text()).toBe('2023-01-01');
expect(span.classes()).toContain('json-object');
});
it('renders an object correctly', async () => {
const obj = { key: 'value' };
const wrapper = buildComponent({ value: obj });
const span = wrapper.find('span');
expect(span.text()).toBe(obj.toString());
expect(span.classes()).toContain('json-object');
});
it('renders an array correctly', async () => {
const arr = [1, 2, 3];
const wrapper = buildComponent({ value: arr });
const span = wrapper.find('span');
expect(span.text()).toBe(arr.toString());
expect(span.classes()).toContain('json-object');
});
it('updates value when prop changes', async () => {
const wrapper = buildComponent({ value: true });
await wrapper.setProps({ value: 123 });
const span = wrapper.find('span');
expect(span.text()).toBe('123');
expect(span.classes()).toContain('json-number');
});
});

View File

@ -1,91 +0,0 @@
import { createWrapper } from 'app/test/vitest/helper';
import VnLocation from 'components/common/VnLocation.vue';
import { vi, afterEach, expect, it, beforeEach, describe } from 'vitest';
function buildComponent(data) {
return createWrapper(VnLocation, {
global: {
props: {
location: data
}
},
}).vm;
}
afterEach(() => {
vi.clearAllMocks();
});
describe('formatLocation', () => {
let locationBase;
beforeEach(() => {
locationBase = {
postcode: '46680',
city: 'Algemesi',
province: { name: 'Valencia' },
country: { name: 'Spain' }
};
});
it('should return the postcode, city, province and country', () => {
const location = { ...locationBase };
const vm = buildComponent(location);
expect(vm.formatLocation(location)).toEqual('46680, Algemesi(Valencia), Spain');
});
it('should return the postcode and country', () => {
const location = { ...locationBase, city: undefined };
const vm = buildComponent(location);
expect(vm.formatLocation(location)).toEqual('46680, Spain');
});
it('should return the city, province and country', () => {
const location = { ...locationBase, postcode: undefined };
const vm = buildComponent(location);
expect(vm.formatLocation(location)).toEqual('Algemesi(Valencia), Spain');
});
it('should return the country', () => {
const location = { ...locationBase, postcode: undefined, city: undefined, province: undefined };
const vm = buildComponent(location);
expect(vm.formatLocation(location)).toEqual('Spain');
});
});
describe('showLabel', () => {
let locationBase;
beforeEach(() => {
locationBase = {
code: '46680',
town: 'Algemesi',
province: 'Valencia',
country: 'Spain'
};
});
it('should show the label with postcode, city, province and country', () => {
const location = { ...locationBase };
const vm = buildComponent(location);
expect(vm.showLabel(location)).toEqual('46680, Algemesi(Valencia), Spain');
});
it('should show the label with postcode and country', () => {
const location = { ...locationBase, town: undefined };
const vm = buildComponent(location);
expect(vm.showLabel(location)).toEqual('46680, Spain');
});
it('should show the label with city, province and country', () => {
const location = { ...locationBase, code: undefined };
const vm = buildComponent(location);
expect(vm.showLabel(location)).toEqual('Algemesi(Valencia), Spain');
});
it('should show the label with country', () => {
const location = { ...locationBase, code: undefined, town: undefined, province: undefined };
const vm = buildComponent(location);
expect(vm.showLabel(location)).toEqual('Spain');
});
});

View File

@ -1,107 +0,0 @@
import { describe, it, expect, vi, beforeAll, afterEach, beforeEach } from 'vitest';
import { createWrapper, axios } from 'app/test/vitest/helper';
import VnNotes from 'src/components/ui/VnNotes.vue';
describe('VnNotes', () => {
let vm;
let wrapper;
let spyFetch;
let postMock;
let expectedBody;
const mockData= {name: 'Tony', lastName: 'Stark', text: 'Test Note', observationTypeFk: 1};
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',
body: { name: 'Tony', lastName: 'Stark' },
}
});
wrapper = wrapper.wrapper;
vm = wrapper.vm;
});
beforeEach(() => {
postMock = vi.spyOn(axios, 'post').mockResolvedValue(mockData);
spyFetch = vi.spyOn(vm.vnPaginateRef, 'fetch').mockImplementation(() => vi.fn());
});
afterEach(() => {
vi.clearAllMocks();
expectedBody = {};
});
describe('insert', () => {
it('should not call axios.post and vnPaginateRef.fetch if newNote.text is null', async () => {
await setTestParams( null, null, true );
await vm.insert();
expect(postMock).not.toHaveBeenCalled();
expect(spyFetch).not.toHaveBeenCalled();
});
it('should not call axios.post and vnPaginateRef.fetch if newNote.text is empty', async () => {
await setTestParams( "", null, false );
await vm.insert();
expect(postMock).not.toHaveBeenCalled();
expect(spyFetch).not.toHaveBeenCalled();
});
it('should not call axios.post and vnPaginateRef.fetch if observationTypeFk is missing and selectType is true', async () => {
await setTestParams( "Test Note", null, true );
await vm.insert();
expect(postMock).not.toHaveBeenCalled();
expect(spyFetch).not.toHaveBeenCalled();
});
it('should call axios.post and vnPaginateRef.fetch if observationTypeFk is missing and selectType is false', async () => {
await setTestParams( "Test Note", null, false );
generateExpectedBody();
await vm.insert();
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();
});
it('should call axios.post and vnPaginateRef.fetch when newNote is valid', async () => {
await setTestParams( "Test Note", 1, true );
generateExpectedBody();
await vm.insert();
expect(postMock).toHaveBeenCalledWith(vm.$props.url, expectedBody);
expect(spyFetch).toHaveBeenCalled();
});
});
});

View File

@ -6,7 +6,6 @@ import { useArrayData } from 'composables/useArrayData';
import { useSummaryDialog } from 'src/composables/useSummaryDialog';
import { useState } from 'src/composables/useState';
import { useRoute } from 'vue-router';
import VnMoreOptions from './VnMoreOptions.vue';
const $props = defineProps({
url: {
@ -48,6 +47,7 @@ let store;
let entity;
const isLoading = ref(false);
const isSameDataKey = computed(() => $props.dataKey === route.meta.moduleName);
const menuRef = ref();
defineExpose({ getData });
onBeforeMount(async () => {
@ -159,11 +159,24 @@ const toModule = computed(() =>
</QTooltip>
</QBtn>
</RouterLink>
<VnMoreOptions v-if="$slots.menu">
<template #menu="{ menuRef }">
<slot name="menu" :entity="entity" :menu-ref="menuRef" />
</template>
</VnMoreOptions>
<QBtn
v-if="$slots.menu"
color="white"
dense
flat
icon="more_vert"
round
size="md"
>
<QTooltip>
{{ t('components.cardDescriptor.moreOptions') }}
</QTooltip>
<QMenu :ref="menuRef">
<QList>
<slot name="menu" :entity="entity" :menu-ref="menuRef" />
</QList>
</QMenu>
</QBtn>
</div>
<slot name="before" />
<div class="body q-py-sm">

View File

@ -2,9 +2,8 @@
import { ref, computed, watch, onBeforeMount } from 'vue';
import { useRoute } from 'vue-router';
import SkeletonSummary from 'components/ui/SkeletonSummary.vue';
import VnLv from 'src/components/ui/VnLv.vue';
import { useArrayData } from 'src/composables/useArrayData';
import { isDialogOpened } from 'src/filters';
import VnMoreOptions from './VnMoreOptions.vue';
const props = defineProps({
url: {
@ -59,6 +58,22 @@ async function fetch() {
emit('onFetch', Array.isArray(data) ? data[0] : data);
isLoading.value = false;
}
const showRedirectToSummaryIcon = computed(() => {
const exist = existSummary(route.matched);
return !isSummary.value && route.meta.moduleName && exist;
});
function existSummary(routes) {
const hasSummary = routes.some((r) => r.name === `${route.meta.moduleName}Summary`);
if (hasSummary) return hasSummary;
for (const current of routes) {
if (current.path != '/' && current.children) {
const exist = existSummary(current.children);
if (exist) return exist;
}
}
}
</script>
<template>
@ -69,7 +84,7 @@ async function fetch() {
<div class="summaryHeader bg-primary q-pa-sm text-weight-bolder">
<slot name="header-left">
<router-link
v-if="isDialogOpened()"
v-if="showRedirectToSummaryIcon"
class="header link"
:to="{
name: `${moduleName ?? route.meta.moduleName}Summary`,
@ -81,16 +96,11 @@ async function fetch() {
<span v-else></span>
</slot>
<slot name="header" :entity="entity" dense>
{{ entity.id + ' - ' + entity.name }}
<VnLv :label="`${entity.id} -`" :value="entity.name" />
</slot>
<slot name="header-right">
<span></span>
</slot>
<span class="row no-wrap">
<slot name="header-right" :entity="entity" />
<VnMoreOptions v-if="$slots.menu && isDialogOpened()">
<template #menu="{ menuRef }">
<slot name="menu" :entity="entity" :menu-ref="menuRef" />
</template>
</VnMoreOptions>
</span>
</div>
<div class="summaryBody row q-mb-md">
<slot name="body" :entity="entity" />
@ -108,7 +118,6 @@ async function fetch() {
.cardSummary {
width: 100%;
max-height: 70vh;
.summaryHeader {
text-align: center;
font-size: 20px;

View File

@ -1,5 +1,5 @@
<script setup>
import { ref, toRef } from 'vue';
import { ref } from 'vue';
import { useI18n } from 'vue-i18n';
import VnLv from 'components/ui/VnLv.vue';
@ -13,7 +13,7 @@ const DEFAULT_PRICE_KG = 0;
const { t } = useI18n();
const props = defineProps({
defineProps({
item: {
type: Object,
required: true,
@ -25,63 +25,57 @@ const props = defineProps({
});
const dialog = ref(null);
const card = toRef(props, 'item');
</script>
<template>
<div class="container order-catalog-item overflow-hidden">
<QCard class="card shadow-6">
<div class="img-wrapper">
<VnImg :id="card.id" class="image" zoom-resolution="1600x900" />
<div v-if="card.hex && isCatalog" class="item-color-container">
<VnImg :id="item.id" class="image" zoom-resolution="1600x900" />
<div v-if="item.hex && isCatalog" class="item-color-container">
<div
class="item-color"
:style="{ backgroundColor: `#${card.hex}` }"
:style="{ backgroundColor: `#${item.hex}` }"
></div>
</div>
</div>
<div class="content">
<span class="link">
{{ card.name }}
<ItemDescriptorProxy :id="card.id" />
{{ item.name }}
<ItemDescriptorProxy :id="item.id" />
</span>
<p class="subName">{{ card.subName }}</p>
<p class="subName">{{ item.subName }}</p>
<template v-for="index in 4" :key="`tag-${index}`">
<VnLv
v-if="card?.[`tag${index + 4}`]"
:label="card?.[`tag${index + 4}`] + ':'"
:value="card?.[`value${index + 4}`]"
v-if="item?.[`tag${index + 4}`]"
:label="item?.[`tag${index + 4}`] + ':'"
:value="item?.[`value${index + 4}`]"
/>
</template>
<div v-if="card.minQuantity" class="min-quantity">
<div v-if="item.minQuantity" class="min-quantity">
<QIcon name="production_quantity_limits" size="xs" />
{{ card.minQuantity }}
{{ item.minQuantity }}
</div>
<div class="footer">
<div class="price">
<p v-if="isCatalog">
{{ card.available }} {{ t('to') }}
{{ toCurrency(card.price) }}
{{ item.available }} {{ t('to') }}
{{ toCurrency(item.price) }}
</p>
<slot name="price" />
<QIcon v-if="isCatalog" name="add_circle" class="icon">
<QTooltip>{{ t('globals.add') }}</QTooltip>
<QPopupProxy ref="dialog">
<OrderCatalogItemDialog
:item="card"
@added="
(quantityAdded) => {
card.available += quantityAdded;
dialog.hide();
}
"
:prices="item.prices"
@added="() => dialog.hide()"
/>
</QPopupProxy>
</QIcon>
</div>
<p v-if="card.priceKg" class="price-kg">
<p v-if="item.priceKg" class="price-kg">
{{ t('price-kg') }}
{{ toCurrency(card.priceKg) || DEFAULT_PRICE_KG }}
{{ toCurrency(item.priceKg) || DEFAULT_PRICE_KG }}
</p>
</div>
</div>

View File

@ -16,12 +16,7 @@ const $props = defineProps({
required: false,
default: 'value',
},
columns: {
type: Number,
default: 3,
},
});
const tags = computed(() => {
return Object.keys($props.item)
.filter((i) => i.startsWith(`${$props.tag}`))
@ -33,21 +28,10 @@ const tags = computed(() => {
return acc;
}, {});
});
const columnStyle = computed(() => {
if ($props.columns) {
return {
'grid-template-columns': `repeat(${$props.columns}, 1fr)`,
'max-width': `${$props.columns * 4}rem`,
};
}
return {};
});
</script>
<template>
<div class="fetchedTags">
<div class="wrap" :style="columnStyle">
<div class="wrap">
<div
v-for="(val, key) in tags"
:key="key"
@ -55,43 +39,37 @@ const columnStyle = computed(() => {
:title="`${key}: ${val}`"
:class="{ empty: !val }"
>
<span class="text">{{ val }} </span>
{{ val }}
</div>
</div>
</div>
</template>
<style lang="scss" scoped>
.fetchedTags {
align-items: center;
.wrap {
display: grid;
width: 100%;
flex-wrap: wrap;
display: flex;
}
.inline-tag {
display: flex;
align-items: center;
justify-content: center;
height: 1rem;
margin: 0.05rem;
color: var(--vn-label-color);
color: $color-font-secondary;
text-align: center;
font-size: smaller;
padding: 1px;
border: 1px solid var(--vn-label-color);
flex: 1;
border: 1px solid $color-spacer;
text-overflow: ellipsis;
overflow: hidden;
min-width: 4rem;
max-width: 4rem;
}
.text {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
font-size: smaller;
}
.empty {
border: 1px solid var(--vn-empty-tag);
border: 1px solid #2b2b2b;
}
}
</style>

View File

@ -1,49 +1,38 @@
<template>
<div class="header bg-primary q-pa-sm q-mb-md">
<QSkeleton type="rect" square />
<QSkeleton type="rect" square />
</div>
<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="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="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="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="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="text" square />
<QSkeleton type="text" square />
<QSkeleton type="text" square />
<QSkeleton type="text" square />
<QSkeleton type="text" square />
</div>
<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="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="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="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="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 />
</div>
</template>

View File

@ -6,7 +6,7 @@ import { useColor } from 'src/composables/useColor';
import { getCssVar } from 'quasar';
const $props = defineProps({
workerId: { type: [Number, undefined], default: null },
workerId: { type: Number, required: true },
description: { type: String, default: null },
title: { type: String, default: null },
color: { type: String, default: null },
@ -38,13 +38,7 @@ watch(src, () => (showLetter.value = false));
<template v-if="showLetter">
{{ title.charAt(0) }}
</template>
<QImg
v-else-if="workerId"
:src="src"
spinner-color="white"
@error="showLetter = true"
/>
<QIcon v-else name="mood" size="xs" />
<QImg v-else :src="src" spinner-color="white" @error="showLetter = true" />
</QAvatar>
<div class="description">
<slot name="description" v-if="description">

View File

@ -30,11 +30,10 @@ const props = defineProps({
},
});
const emit = defineEmits(['confirm', 'cancel', ...useDialogPluginComponent.emits]);
defineEmits(['confirm', ...useDialogPluginComponent.emits]);
defineExpose({ show: () => dialogRef.value.show(), hide: () => dialogRef.value.hide() });
const { dialogRef, onDialogHide, onDialogOK, onDialogCancel } =
useDialogPluginComponent();
const { dialogRef, onDialogOK } = useDialogPluginComponent();
const title = props.title || t('Confirm');
const message =
@ -54,14 +53,9 @@ async function confirm() {
}
onDialogOK(props.data);
}
function cancel() {
emit('cancel');
onDialogCancel();
}
</script>
<template>
<QDialog ref="dialogRef" @hide="onDialogHide">
<QDialog ref="dialogRef">
<QCard class="q-pa-sm">
<QCardSection class="row items-center q-pb-none">
<QAvatar
@ -73,14 +67,7 @@ function cancel() {
/>
<span class="text-h6">{{ title }}</span>
<QSpace />
<QBtn
icon="close"
:disable="isLoading"
flat
round
dense
@click="cancel()"
/>
<QBtn icon="close" :disable="isLoading" flat round dense v-close-popup />
</QCardSection>
<QCardSection class="q-pb-none">
<span v-if="message !== false" v-html="message" />
@ -94,17 +81,15 @@ function cancel() {
color="primary"
:disable="isLoading"
flat
@click="cancel()"
v-close-popup
/>
<QBtn
:label="t('globals.confirm')"
:title="t('globals.confirm')"
color="primary"
:loading="isLoading"
@click="confirm()"
unelevated
autofocus
data-cy="VnConfirm_confirm"
/>
</QCardActions>
</QCard>

View File

@ -1,14 +1,12 @@
<script setup>
import { ref, computed } from 'vue';
import { onMounted, ref, computed, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { useArrayData } from 'composables/useArrayData';
import { useRoute } from 'vue-router';
import toDate from 'filters/toDate';
import VnFilterPanelChip from 'components/ui/VnFilterPanelChip.vue';
import { useFilterParams } from 'src/composables/useFilterParams';
import { useRoute } from 'vue-router';
const { t, te } = useI18n();
const route = useRoute();
const { t } = useI18n();
const $props = defineProps({
modelValue: {
type: Object,
@ -39,7 +37,7 @@ const $props = defineProps({
},
hiddenTags: {
type: Array,
default: () => ['filter', 'or', 'and'],
default: () => ['filter', 'search', 'or', 'and'],
},
customTags: {
type: Array,
@ -51,18 +49,15 @@ const $props = defineProps({
},
searchUrl: {
type: String,
default: 'table',
default: 'params',
},
redirect: {
type: Boolean,
default: true,
},
arrayData: {
type: Object,
default: null,
},
});
defineExpose({ search, sanitizer });
const emit = defineEmits([
'update:modelValue',
'refresh',
@ -73,19 +68,48 @@ const emit = defineEmits([
'setUserParams',
]);
const arrayData =
$props.arrayData ??
useArrayData($props.dataKey, {
exprBuilder: $props.exprBuilder,
searchUrl: $props.searchUrl,
navigate: $props.redirect ? {} : null,
});
const arrayData = useArrayData($props.dataKey, {
exprBuilder: $props.exprBuilder,
searchUrl: $props.searchUrl,
navigate: $props.redirect ? {} : null,
});
const route = useRoute();
const store = arrayData.store;
const userParams = ref(useFilterParams($props.dataKey).params);
const userOrders = ref(useFilterParams($props.dataKey).orders);
const userParams = ref({});
onMounted(() => {
userParams.value = $props.modelValue ?? {};
emit('init', { params: userParams.value });
});
defineExpose({ search, params: userParams, remove });
function setUserParams(watchedParams) {
if (!watchedParams || Object.keys(watchedParams).length == 0) return;
if (typeof watchedParams == 'string') watchedParams = JSON.parse(watchedParams);
if (typeof watchedParams?.filter == 'string')
watchedParams.filter = JSON.parse(watchedParams.filter);
watchedParams = { ...watchedParams, ...watchedParams.filter?.where };
const order = watchedParams.filter?.order;
delete watchedParams.filter;
userParams.value = sanitizer(watchedParams);
emit('setUserParams', userParams.value, order);
}
watch(
() => route.query[$props.searchUrl],
(val, oldValue) => (val || oldValue) && setUserParams(val)
);
watch(
() => arrayData.store.userParams,
(val, oldValue) => (val || oldValue) && setUserParams(val)
);
watch(
() => $props.modelValue,
(val) => (userParams.value = val ?? {})
);
const isLoading = ref(false);
async function search(evt) {
@ -96,9 +120,10 @@ async function search(evt) {
isLoading.value = true;
const filter = { ...userParams.value, ...$props.modelValue };
store.userParamsChanged = true;
await arrayData.addFilter({
const { params: newParams } = await arrayData.addFilter({
params: filter,
});
userParams.value = newParams;
if (!$props.showAll && !Object.values(filter).length) store.data = [];
emit('search');
@ -111,7 +136,7 @@ async function clearFilters() {
try {
isLoading.value = true;
store.userParamsChanged = true;
arrayData.resetPagination();
arrayData.reset(['skip', 'filter.skip', 'page']);
// Filtrar los params no removibles
const removableFilters = Object.keys(userParams.value).filter((param) =>
$props.unremovableParams.includes(param)
@ -121,8 +146,9 @@ async function clearFilters() {
for (const key of removableFilters) {
newParams[key] = userParams.value[key];
}
await arrayData.applyFilter({ params: { ...newParams } });
userParams.value = {};
userParams.value = { ...newParams }; // Actualizar los params con los removibles
await arrayData.applyFilter({ params: userParams.value });
if (!$props.showAll) {
store.data = [];
@ -144,36 +170,16 @@ const tagsList = computed(() => {
return tagList;
});
const formatTags = (tags) => {
const formattedTags = [];
tags.forEach((tag) => {
if (tag.label === 'and') {
tag.value.forEach((item) => {
for (const key in item) {
formattedTags.push({ label: key, value: item[key] });
}
});
} else {
formattedTags.push(tag);
}
});
return formattedTags;
};
const tags = computed(() => {
const filteredTags = tagsList.value.filter(
(tag) => !($props.customTags || []).includes(tag.label)
);
return formatTags(filteredTags);
return tagsList.value.filter((tag) => !($props.customTags || []).includes(tag.label));
});
const customTags = computed(() =>
tagsList.value.filter((tag) => ($props.customTags || []).includes(tag.label))
);
async function remove(key) {
userParams.value[key] = undefined;
await search();
search();
emit('remove', key);
emit('update:modelValue', userParams.value);
}
@ -185,13 +191,15 @@ function formatValue(value) {
return `"${value}"`;
}
const getLocale = (label) => {
const param = label.split('.').at(-1);
const globalLocale = `globals.params.${param}`;
if (te(globalLocale)) return t(globalLocale);
else if (te(t(`params.${param}`)));
else return t(`${route.meta.moduleName.toLowerCase()}.params.${param}`);
};
function sanitizer(params) {
for (const [key, value] of Object.entries(params)) {
if (value && typeof value === 'object') {
const param = Object.values(value)[0];
if (typeof param == 'string') params[key] = param.replaceAll('%', '');
}
}
return params;
}
</script>
<template>
@ -202,11 +210,7 @@ const getLocale = (label) => {
style="position: fixed; z-index: 1; right: 0; bottom: 0"
icon="search"
@click="search()"
>
<QTooltip bottom anchor="bottom right">
{{ t('globals.search') }}
</QTooltip>
</QBtn>
></QBtn>
<QForm @submit="search" id="filterPanelForm" @keyup.enter="search()">
<QList dense>
<QItem class="q-mt-xs">
@ -243,14 +247,8 @@ const getLocale = (label) => {
:key="chip.label"
:removable="!unremovableParams?.includes(chip.label)"
@remove="remove(chip.label)"
data-cy="vnFilterPanelChip"
>
<slot
name="tags"
:tag="chip"
:format-fn="formatValue"
:get-locale="getLocale"
>
<slot name="tags" :tag="chip" :format-fn="formatValue">
<div class="q-gutter-x-xs">
<strong>{{ chip.label }}:</strong>
<span>"{{ formatValue(chip.value) }}"</span>
@ -263,7 +261,6 @@ const getLocale = (label) => {
:params="userParams"
:tags="customTags"
:format-fn="formatValue"
:get-locale="getLocale"
:search-fn="search"
/>
</div>
@ -271,13 +268,7 @@ const getLocale = (label) => {
<QSeparator />
</QList>
<QList dense class="list q-gutter-y-sm q-mt-sm">
<slot
name="body"
:get-locale="getLocale"
:params="userParams"
:orders="userOrders"
:search-fn="search"
></slot>
<slot name="body" :params="sanitizer(userParams)" :search-fn="search"></slot>
</QList>
</QForm>
<QInnerLoading

View File

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

View File

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

View File

@ -39,7 +39,7 @@ const val = computed(() => $props.value);
<template v-else>
<div v-if="label || $slots.label" class="label">
<slot name="label">
<span style="color: var(--vn-label-color)">{{ label }}</span>
<span>{{ label }}</span>
</slot>
</div>
<div class="value">

View File

@ -1,20 +0,0 @@
<template>
<QBtn
color="white"
dense
flat
icon="more_vert"
round
size="md"
data-cy="descriptor-more-opts"
>
<QTooltip>
{{ $t('components.cardDescriptor.moreOptions') }}
</QTooltip>
<QMenu ref="menuRef">
<QList>
<slot name="menu" :menu-ref="$refs.menuRef" />
</QList>
</QMenu>
</QBtn>
</template>

View File

@ -6,6 +6,7 @@ import { useI18n } from 'vue-i18n';
import { useQuasar } from 'quasar';
import { toDateHourMin } from 'src/filters';
import { useState } from 'src/composables/useState';
import VnPaginate from 'components/ui/VnPaginate.vue';
import VnUserLink from 'components/ui/VnUserLink.vue';
@ -25,7 +26,9 @@ const $props = defineProps({
});
const { t } = useI18n();
const state = useState();
const quasar = useQuasar();
const currentUser = ref(state.getUser());
const newNote = reactive({ text: null, observationTypeFk: null });
const observationTypes = ref([]);
const vnPaginateRef = ref();
@ -62,9 +65,13 @@ onBeforeRouteLeave((to, from, next) => {
auto-load
@on-fetch="(data) => (observationTypes = data)"
/>
<QCard class="q-pa-xs q-mb-lg full-width" v-if="$props.addNote">
<QCard class="q-pa-xs q-mb-xl full-width" v-if="$props.addNote">
<QCardSection horizontal>
{{ t('New note') }}
<VnAvatar :worker-id="currentUser.id" size="md" />
<div class="full-width row justify-between q-pa-xs">
<VnUserLink :name="t('New note')" :worker-id="currentUser.id" />
{{ t('globals.now') }}
</div>
</QCardSection>
<QCardSection class="q-px-xs q-my-none q-py-none">
<VnRow class="full-width">
@ -98,7 +105,6 @@ onBeforeRouteLeave((to, from, next) => {
@click="insert"
class="q-mb-xs"
dense
data-cy="saveNote"
/>
</template>
</VnInput>
@ -110,7 +116,7 @@ onBeforeRouteLeave((to, from, next) => {
:url="$props.url"
order="created DESC"
:limit="0"
:user-filter="$props.filter"
:filter="$props.filter"
auto-load
ref="vnPaginateRef"
class="show"
@ -138,7 +144,7 @@ onBeforeRouteLeave((to, from, next) => {
<div class="full-width row justify-between q-pa-xs">
<div>
<VnUserLink
:name="`${note.worker.user.name}`"
:name="`${note.worker.user.nickname}`"
:worker-id="note.worker.id"
/>
<QBadge

View File

@ -44,7 +44,7 @@ const props = defineProps({
},
limit: {
type: Number,
default: 20,
default: 10,
},
userParams: {
type: Object,
@ -74,10 +74,6 @@ const props = defineProps({
type: Boolean,
default: false,
},
mapKey: {
type: String,
default: '',
},
});
const emit = defineEmits(['onFetch', 'onPaginate', 'onChange']);
@ -100,20 +96,15 @@ const arrayData = useArrayData(props.dataKey, {
exprBuilder: props.exprBuilder,
keepOpts: props.keepOpts,
searchUrl: props.searchUrl,
mapKey: props.mapKey,
});
const store = arrayData.store;
onMounted(async () => {
if (props.autoLoad && !store.data?.length) await fetch();
else emit('onFetch', store.data);
if (props.autoLoad) await fetch();
mounted.value = true;
});
onBeforeUnmount(() => {
if (!store.keepData) arrayData.reset(['data']);
arrayData.resetPagination();
});
onBeforeUnmount(() => arrayData.reset());
watch(
() => props.data,
@ -124,11 +115,7 @@ watch(
watch(
() => store.data,
(data) => {
if (!mounted.value) return;
emit('onChange', data);
},
{ immediate: true }
(data) => emit('onChange', data)
);
watch(
@ -141,24 +128,10 @@ const addFilter = async (filter, params) => {
async function fetch(params) {
useArrayData(props.dataKey, params);
arrayData.resetPagination();
arrayData.reset(['filter.skip', 'skip']);
await arrayData.fetch({ append: false });
return emitStoreData();
}
async function update(params) {
useArrayData(props.dataKey, params);
const { limit, skip } = store;
store.limit = limit + skip;
store.skip = 0;
await arrayData.fetch({ append: false });
store.limit = limit;
store.skip = skip;
return emitStoreData();
}
function emitStoreData() {
if (!store.hasMoreData) isLoading.value = false;
emit('onFetch', store.data);
return store.data;
}
@ -204,20 +177,13 @@ async function onLoad(index, done) {
done(isDone);
}
defineExpose({
fetch,
update,
addFilter,
paginate,
userParams: arrayData.store.userParams,
currentFilter: arrayData.store.currentFilter,
});
defineExpose({ fetch, addFilter, paginate });
</script>
<template>
<div class="full-width">
<div
v-if="!store.data && !store.data?.length && !isLoading"
v-if="!props.autoLoad && !store.data && !isLoading"
class="info-row q-pa-md text-center"
>
<h5>

View File

@ -1,5 +1,8 @@
<script setup>
defineProps({ wrap: { type: Boolean, default: false } });
</script>
<template>
<div class="vn-row q-gutter-md">
<div class="vn-row q-gutter-md q-mb-md">
<slot />
</div>
</template>
@ -18,9 +21,6 @@
&:not(.wrap) {
flex-direction: column;
}
&[fixed] {
flex-direction: row;
}
}
}
</style>

View File

@ -1,16 +1,14 @@
<script setup>
import { onMounted, ref, computed, watch } from 'vue';
import { onMounted, ref, watch } from 'vue';
import { useQuasar } from 'quasar';
import { useArrayData } from 'composables/useArrayData';
import VnInput from 'src/components/common/VnInput.vue';
import { useI18n } from 'vue-i18n';
import { useStateStore } from 'src/stores/useStateStore';
import { useRoute } from 'vue-router';
const quasar = useQuasar();
const { t } = useI18n();
const state = useStateStore();
const route = useRoute();
const props = defineProps({
dataKey: {
@ -47,12 +45,16 @@ const props = defineProps({
},
limit: {
type: Number,
default: 20,
default: 10,
},
userParams: {
type: Object,
default: null,
},
staticParams: {
type: Array,
default: () => [],
},
exprBuilder: {
type: Function,
default: null,
@ -65,10 +67,6 @@ const props = defineProps({
type: Function,
default: undefined,
},
searchRemoveParams: {
type: Boolean,
default: true,
},
});
const searchText = ref();
@ -85,17 +83,6 @@ if (props.redirect)
};
let arrayData = useArrayData(props.dataKey, arrayDataProps);
let store = arrayData.store;
const to = computed(() => {
const url = { path: route.path, query: { ...(route.query ?? {}) } };
const searchUrl = arrayData.store.searchUrl;
const currentFilter = {
...arrayData.store.currentFilter,
search: searchText.value || undefined,
};
if (searchUrl) url.query[searchUrl] = JSON.stringify(currentFilter);
return url;
});
watch(
() => props.dataKey,
@ -113,25 +100,17 @@ onMounted(() => {
});
async function search() {
const staticParams = Object.keys(store.userParams ?? {}).length
? store.userParams
: store.defaultParams;
arrayData.resetPagination();
const staticParams = Object.entries(store.userParams);
arrayData.reset(['skip', 'page']);
const filter = {
params: {
...Object.fromEntries(staticParams),
search: searchText.value,
},
filter: props.filter,
...{ filter: props.filter },
};
if (!props.searchRemoveParams || !searchText.value) {
filter.params = {
...staticParams,
search: searchText.value,
};
}
if (props.whereFilter) {
filter.filter = {
where: props.whereFilter(searchText.value),
@ -139,38 +118,27 @@ async function search() {
delete filter.params.search;
}
await arrayData.applyFilter(filter);
searchText.value = undefined;
}
</script>
<template>
<Teleport to="#searchbar" v-if="state.isHeaderMounted()">
<QForm @submit="search" id="searchbarForm">
<RouterLink
:to="to"
@click="
!$event.shiftKey && !$event.ctrlKey && search();
$refs.input.focus();
"
>
<QIcon
v-if="!quasar.platform.is.mobile"
class="cursor-pointer"
name="search"
size="sm"
>
<QTooltip>{{ t('link') }}</QTooltip>
</QIcon>
</RouterLink>
<VnInput
id="searchbar"
ref="input"
v-model.trim="searchText"
:placeholder="t(props.label)"
dense
standout
autofocus
data-cy="vn-searchbar"
borderless
>
<template #prepend>
<QIcon
v-if="!quasar.platform.is.mobile"
class="cursor-pointer"
name="search"
@click="search"
/>
</template>
<template #append>
<QIcon
v-if="props.info && $q.screen.gt.xs"
@ -195,52 +163,20 @@ async function search() {
.q-field {
transition: width 0.36s;
}
</style>
:deep(.q-field__native) {
padding-top: 10px;
padding-left: 5px;
}
:deep(.q-field--dark .q-field__native:focus) {
color: black;
}
:deep(.q-field--focused) {
.q-icon {
color: black;
}
}
<style lang="scss">
.cursor-info {
cursor: help;
}
.q-form {
display: flex;
align-items: center;
border-radius: 4px;
padding: 0 5px;
background-color: var(--vn-search-color);
&:hover {
background-color: var(--vn-search-color-hover);
}
&:focus-within {
#searchbar {
.q-field--standout.q-field--highlighted .q-field__control {
background-color: white;
color: black;
.q-field__native,
.q-icon {
color: black;
color: black !important;
}
}
}
.q-icon {
color: var(--vn-label-color);
}
</style>
<i18n>
en:
link: click to search, ctrl + click to open in a new tab, shift + click to open in a new window
es:
link: clic para buscar, ctrl + clic para abrir en una nueva pestaña, shift + clic para abrir en una nueva ventana
</i18n>

View File

@ -54,7 +54,6 @@ function formatNumber(number) {
:offset="100"
:limit="5"
auto-load
map-key="smsFk"
>
<template #body="{ rows }">
<QCard

View File

@ -1,5 +1,6 @@
<script setup>
import { useRoute } from 'vue-router';
import { defineProps } from 'vue';
const props = defineProps({
routeName: {

View File

@ -1,78 +0,0 @@
import { vi, describe, expect, it, beforeAll, afterEach, beforeEach } from 'vitest';
import { createWrapper, axios } from 'app/test/vitest/helper';
import CardSummary from 'src/components/ui/CardSummary.vue';
import * as vueRouter from 'vue-router';
describe('CardSummary', () => {
let vm;
let wrapper;
beforeAll(() => {
vi.spyOn(axios, 'get').mockResolvedValue({ data: [] });
});
vi.spyOn(vueRouter, 'useRoute').mockReturnValue({
query: {},
params: {},
meta: { moduleName: 'mockName' },
path: 'mockName/1/summary',
name: 'CardSummary',
});
beforeEach(() => {
wrapper = createWrapper(CardSummary, {
propsData: {
dataKey: 'cardSummaryKey',
url: 'cardSummaryUrl',
filter: 'cardFilter',
},
});
vm = wrapper.vm;
wrapper = wrapper.wrapper;
});
afterEach(() => {
vi.clearAllMocks();
});
it('should fetch data correctly', async () => {
const fetchSpy = vi
.spyOn(vm.arrayData, 'fetch')
.mockResolvedValue({ data: [{ id: 1, name: 'Test Entity' }] });
await vm.fetch();
expect(fetchSpy).toHaveBeenCalledWith({ append: false, updateRouter: false });
expect(wrapper.emitted('onFetch')).toBeTruthy();
expect(vm.isLoading).toBe(false);
});
it('should set correct props to the store', () => {
expect(vm.store.url).toEqual('cardSummaryUrl');
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 () => {
const newUrl = 'CardSummary/35';
const newKey = 'cardSummaryKey/35';
const fetchSpy = vi.spyOn(vm.arrayData, 'fetch');
await wrapper.setProps({ url: newUrl, filter: { key: newKey } });
expect(fetchSpy).toHaveBeenCalled();
expect(vm.store.url).toBe(newUrl);
expect(vm.store.filter).toEqual({ key: newKey });
});
it('should return true if route path ends with /summary' , () => {
expect(vm.isSummary).toBe(true);
});
});

View File

@ -1,81 +0,0 @@
import { describe, expect, it } from 'vitest';
import { createWrapper } from 'app/test/vitest/helper';
import FetchedTags from 'src/components/ui/FetchedTags.vue';
describe('tags computed property', () => {
it('returns an object with the correct keys and values', () => {
const vm = createWrapper(FetchedTags, {
props: {
item: {
tag1: 'JavaScript',
value1: 'Programming Language',
tag2: 'Vue',
value2: 'Framework',
tag3: 'EmptyTag',
},
tag: 'tag',
value: 'value',
columns: 2,
},
}).vm;
expect(vm.tags).toEqual({
JavaScript: 'Programming Language',
Vue: 'Framework',
EmptyTag: '',
});
});
it('returns an empty object if the item prop is an empty object', () => {
const vm = createWrapper(FetchedTags, {
props: {
item: {},
tag: 'tag',
value: 'value',
},
}).vm;
expect(vm.tags).toEqual({});
});
it('should calculate the correct columnStyle when columns prop is defined', () => {
const vm = createWrapper(FetchedTags, {
props: {
item: {
tag1: 'JavaScript',
value1: 'Programming Language',
tag2: 'Vue',
value2: 'Framework',
tag3: 'EmptyTag',
},
tag: 'tag',
value: 'value',
columns: 2,
},
}).vm;
const expectedStyle = {
'grid-template-columns': 'repeat(2, 1fr)',
'max-width': '8rem',
};
expect(vm.columnStyle).toEqual(expectedStyle);
});
it('should return an empty object for columnStyle when columns prop is not defined', () => {
const vm = createWrapper(FetchedTags, {
props: {
item: {
tag1: 'JavaScript',
value1: 'Programming Language',
tag2: 'Vue',
value2: 'Framework',
tag3: 'EmptyTag',
},
tag: 'tag',
value: 'value',
columns: null,
},
}).vm;
expect(vm.columnStyle).toEqual({});
});
});

View File

@ -1,50 +0,0 @@
import { describe, it, expect, beforeAll, vi } from 'vitest';
import { axios } from 'app/test/vitest/helper';
import parsePhone from 'src/filters/parsePhone';
describe('parsePhone filter', () => {
beforeAll(async () => {
vi.spyOn(axios, 'get').mockReturnValue({ data: { prefix: '34' } });
});
it('no phone', async () => {
const phone = await parsePhone(null, '34');
expect(phone).toBe(undefined);
});
it("adds prefix +34 if it doesn't have one", async () => {
const phone = await parsePhone('123456789', '34');
expect(phone).toBe('34123456789');
});
it('maintains prefix +34 if it is already correct', async () => {
const phone = await parsePhone('+34123456789', '34');
expect(phone).toBe('34123456789');
});
it('converts prefix 0034 to +34', async () => {
const phone = await parsePhone('0034123456789', '34');
expect(phone).toBe('34123456789');
});
it('converts prefix 34 without symbol to +34', async () => {
const phone = await parsePhone('34123456789', '34');
expect(phone).toBe('34123456789');
});
it('replaces incorrect prefix with the correct one', async () => {
const phone = await parsePhone('+44123456789', '34');
expect(phone).toBe('44123456789');
});
it('adds default prefix on error', async () => {
vi.spyOn(axios, 'get').mockImplementation((url) => {
if (url.includes('Prefixes'))
return Promise.reject(new Error('Network error'));
else if (url.includes('PbxConfigs'))
return Promise.resolve({ data: { defaultPrefix: '39' } });
});
const phone = await parsePhone('123456789', '34');
expect(phone).toBe('39123456789');
});
});

View File

@ -1,36 +0,0 @@
import { vi, describe, expect, it, beforeAll, afterAll } from 'vitest';
import { axios } from 'app/test/vitest/helper';
import { downloadFile } from 'src/composables/downloadFile';
import { useSession } from 'src/composables/useSession';
const session = useSession();
const token = session.getToken();
describe('downloadFile', () => {
const baseUrl = 'http://localhost:9000';
let defaulCreateObjectURL;
beforeAll(() => {
defaulCreateObjectURL = window.URL.createObjectURL;
window.URL.createObjectURL = vi.fn(() => 'blob:http://localhost:9000/blob-id');
});
afterAll(() => (window.URL.createObjectURL = defaulCreateObjectURL));
it('should open a new window to download the file', async () => {
const res = {
data: new Blob(['file content'], { type: 'application/octet-stream' }),
headers: { 'content-disposition': 'attachment; filename="test-file.txt"' },
};
vi.spyOn(axios, 'get').mockImplementation((url) => {
if (url == 'Urls/getUrl') return Promise.resolve({ data: baseUrl });
else if (url.includes('downloadFile')) return Promise.resolve(res);
});
await downloadFile(1);
expect(axios.get).toHaveBeenCalledWith(
`${baseUrl}/api/dms/1/downloadFile?access_token=${token}`,
{ responseType: 'blob' }
);
});
});

View File

@ -1,45 +0,0 @@
import { describe, expect, it, vi } from 'vitest';
import axios from 'axios';
import { getExchange } from 'src/composables/getExchange';
vi.mock('axios');
describe('getExchange()', () => {
it('should return the correct exchange rate', async () => {
axios.get.mockResolvedValue({
data: { value: 1.2 },
});
const amount = 100;
const currencyFk = 1;
const dated = '2023-01-01';
const result = await getExchange(amount, currencyFk, dated);
expect(result).toBe('83.33');
});
it('should return the correct exchange rate with custom decimal places', async () => {
axios.get.mockResolvedValue({
data: { value: 1.2 },
});
const amount = 100;
const currencyFk = 1;
const dated = '2023-01-01';
const decimalPlaces = 3;
const result = await getExchange(amount, currencyFk, dated, decimalPlaces);
expect(result).toBe('83.333');
});
it('should return null if the API call fails', async () => {
axios.get.mockRejectedValue(new Error('Network error'));
const amount = 100;
const currencyFk = 1;
const dated = '2023-01-01';
const result = await getExchange(amount, currencyFk, dated);
expect(result).toBeNull();
});
});

View File

@ -1,55 +0,0 @@
import { vi, describe, expect, it } from 'vitest';
import { getTotal } from 'src/composables/getTotal';
vi.mock('src/filters', () => ({
toCurrency: vi.fn((value, currency) => `${currency} ${value.toFixed(2)}`),
}));
describe('getTotal()', () => {
const rows = [
{ amount: 10.5, tax: 2.1 },
{ amount: 20.75, tax: 3.25 },
{ amount: 30.25, tax: 4.75 },
];
it('should calculate the total for a given key', () => {
const total = getTotal(rows, 'amount');
expect(total).toBe('61.50');
});
it('should calculate the total with a callback function', () => {
const total = getTotal(rows, null, { cb: (row) => row.amount + row.tax });
expect(total).toBe('71.60');
});
it('should format the total as currency', () => {
const total = getTotal(rows, 'amount', { currency: 'USD' });
expect(total).toBe('USD 61.50');
});
it('should format the total as currency with default currency', () => {
const total = getTotal(rows, 'amount', { currency: 'default' });
expect(total).toBe('undefined 61.50');
});
it('should calculate the total with integer formatting', () => {
const total = getTotal(rows, 'amount', { decimalPlaces: 0 });
expect(total).toBe('62');
});
it('should calculate the total with custom decimal places', () => {
const total = getTotal(rows, 'amount', { decimalPlaces: 1 });
expect(total).toBe('61.5');
});
it('should handle rows with missing keys', () => {
const rowsWithMissingKeys = [{ amount: 10.5 }, { amount: 20.75 }, {}];
const total = getTotal(rowsWithMissingKeys, 'amount');
expect(total).toBe('31.25');
});
it('should handle empty rows', () => {
const total = getTotal([], 'amount');
expect(total).toBe('0.00');
});
});

View File

@ -1,9 +0,0 @@
import { describe, expect, it } from 'vitest';
import { useAccountShortToStandard } from 'src/composables/useAccountShortToStandard';
describe('useAccountShortToStandard()', () => {
it('should pad the decimal part with zeros for short numbers', () => {
expect(useAccountShortToStandard('123.45')).toBe('1230000045');
expect(useAccountShortToStandard('123.')).toBe('1230000000');
});
});

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