Compare commits

..

1 Commits

Author SHA1 Message Date
Sergio De la torre f81426c643 feat: roadMap #7195
gitea/salix/pipeline/pr-dev There was a failure building this commit Details
2024-05-29 12:20:26 +02:00
2888 changed files with 63599 additions and 35371 deletions

View File

@ -36,7 +36,3 @@ rules:
jasmine/no-focused-tests: 0
jasmine/prefer-toHaveBeenCalledWith: 0
arrow-spacing: ["error", { "before": true, "after": true }]
no-restricted-syntax:
- "error"
- selector: "NewExpression[callee.name='Date']"
message: "Use Date.vnNew() instead of new Date()."

View File

@ -1,417 +1,3 @@
# Version 24.38 - 2024-09-17
### Added 🆕
- chore: refs #7323 filter data by:jorgep
- chore: refs #7323 fix test by:jorgep
- chore: refs #7323 worker changes by:jorgep
- chore: refs #7323 worker changes wip by:jorgep
- chore: refs #7524 add select limit by:jorgep
- feat(AccessToken&ACL): refs #7547 upgrade security by:alexm
- feat: deleted code and redirect to Lilium by:Jon
- feat: refs #4515 New throw buy_checkItem by:guillermo
- feat: refs #6650 Added saleGroupLog by:guillermo
- feat: refs #6650 new itemShelvingLog by:guillermo
- feat: refs #6760 refs #actualiza campo nickname by:jgallego
- feat: refs #7277 fdescribe by:jgallego
- feat: refs #7277 fit by:jgallego
- feat: refs #7277 refundInvoices by:jgallego
- feat: refs #7277 test with warehouse by:jgallego
- feat: refs #7277 traducciones by:jgallego
- feat: refs #7277 transfer addressFk by:jgallego
- feat: refs #7532 Requested changes by:guillermo
- feat: refs #7564 Added proc by:guillermo
- feat: refs #7564 Added ticket_setVolumeItemCost by:guillermo
- feat: refs #7564 Added volume column by:guillermo
- feat: refs #7564 Fix version by:guillermo
- feat: refs #7564 Requested changes by:guillermo
- feat: refs #7615 setDeleted by:robert
- feat: refs #7650 Added no transfer lines to inventory entry and fixtures by:guillermo
- feat: refs #7650 Fix tests by:guillermo
- feat: refs #7747 Delete buyUltimate and buyUltimateFromInterval by:ivanm
- feat: refs #7759 Changed defined only of vn objects by:guillermo
- feat: refs #7759 Changed definer root to vn-admin by:guillermo
- feat: refs #7759 Changed name by:guillermo
- feat: refs #7759 Deleted version 11163-maroonEucalyptus by:guillermo
- feat: refs #7759 Revoke routine grants vn by:guillermo
- feat: refs #7811 Added comment by:guillermo
- feat: refs #7811 Added new params in datasources.json by:guillermo
- feat: refs #7898 Add column "floor" in vn.parking by:ivanm
- feat: refs #7898 Modify default by:ivanm
- feat: refs #7905 Added new method getBuysCsv by:guillermo
- feat: refs #7905 Added param toCsv by:guillermo
- feat: refs #7938 remove unnecessary insert in clientLog by:alexm
- feat: refs #7953 pullinfo (7953-devToTest_2438) by:alexm
- feat(salix): #7671 define isDestiny field in model by:Javier Segarra
- feat(salix): refs #7896 update version and changelog (origin/7896_down_devToTest_2436) by:Javier Segarra
- feat(salix): refs #7905 #7905 use getBuys toCSV flattened by:Javier Segarra
- feat(ssalix): refs #7671 #7671 checkDates by:Javier Segarra
- feat(ssalix): refs #7671 #7671 checkDates to present by:Javier Segarra
- feat: ticket 215005 Changed acl show transferClient by:guillermo
### Changed 📦
- perf: refs #7671 improve showBadDates by:Javier Segarra
- perf(salix): refs #7671 #7671 imrpove and revert where changes by:Javier Segarra
- refactor: deleted e2e & added back descriptor and summary by:Jon
### Fixed 🛠️
- chore: refs #7323 fix test by:jorgep
- feat: refs #7650 Added no transfer lines to inventory entry and fixtures by:guillermo
- fix by:guillermo
- fixes: refs #7760 collection problems by:Carlos Andrés
- fix merge dev (7407-workerMedical) by:alexm
- fix: refs #6727 No delete log tables data in clean procedures by:guillermo
- fix: refs #6897 back and tests by:carlossa
- fix: refs #6897 back by:carlossa
- fix: refs #6897 fix filter by:carlossa
- fix: refs #6897 fix json by:carlossa
- fix: refs #6897 travel filter by:carlossa
- fix: refs #6897 error test by:jgallego
- fix: refs #7323 fetch from right source by:jorgep
- fix: refs #7564 Deleted query by:guillermo
- fix: refs #7759 Added user 'vn'@'localhost' & grants by:guillermo
- fix: refs #7760 collection problems by:Carlos Andrés
- fix: refs #7760 tmp.ticketIPT by:Carlos Andrés
- fix: refs #7905 added comments to flatten.js by:guillermo
- fix: refs ##7905 Handle error by:guillermo
- fix(salix): refs #7905 #7905 use right fn to flatten data by:Javier Segarra
- perf(salix): refs #7671 #7671 imrpove and revert where changes by:Javier Segarra
- refs #6898 fix supplier remove by:carlossa
- refs #7407 fix acls fixtures by:carlossa
- test: fix connections e2e (7547-accessToken-security) by:alexm
- test: refs #7277 fix test proposal by:Javier Segarra
- test(salix): refs #7671 #7671 improve and revert where changes by:Javier Segarra
# Version 24.36 - 2024-09-03
### Added 🆕
- chore: refs #7524 WIP limit call by:jorgep
- chore: refs #7524 modify ormConfig table col (origin/7524-warmfix-modifyColumn) by:jorgep
- feat(update-user): refs #7848 add twoFactor by:alexm
- feat: #3199 Requested changes by:guillermo
- feat: refs #3199 Added more scopes ticket_recalcByScope by:guillermo
- feat: refs #3199 Added one more scope ticket_recalcByScope by:guillermo
- feat: refs #3199 Created ticket_recalcItemTaxCountryByScope by:guillermo
- feat: refs #3199 Requested changes by:guillermo
- feat: refs #7346 add multiple feature by:jgallego
- feat: refs #7346 backTest checks new implementation by:jgallego
- feat: refs #7346 mas intuitivo by:jgallego
- feat: refs #7514 Changes to put srt log (origin/7514-srtLog) by:guillermo
- feat: refs #7524 add default limit (origin/7524-limitSelect) by:jorgep
- feat: refs #7524 add mock limit on find query by:jorgep
- feat: refs #7524 wip remote hooks by:jorgep
- feat: refs #7562 Requested changes by:guillermo
- feat: refs #7567 Changed time to call event by:guillermo
- feat: refs #7567 Requested changes by:guillermo
- feat: refs #7710 pr revision by:jgallego
- feat: refs #7710 test fixed (origin/7710-cloneWithTicketPackaging, 7710-cloneWithTicketPackaging) by:jgallego
- feat: refs #7712 Fix by:guillermo
- feat: refs #7712 Unify by:guillermo
- feat: refs #7712 sizeLimit (origin/7712-sizeLimit) by:guillermo
- feat: refs #7758 Add code mandateType and accountDetailType by:ivanm
- feat: refs #7758 Modify code lowerCamelCase and UNIQUE by:ivanm
- feat: refs #7758 accountDetailType fix deploy error by:ivanm
- feat: refs #7784 Changes in entry-order-pdf by:guillermo
- feat: refs #7784 Requested changes by:guillermo
- feat: refs #7799 Added Fk in vn.item.itemPackingTypeFk by:guillermo
- feat: refs #7800 Added company Fk by:guillermo
- feat: refs #7842 Added editorFk in vn.host by:guillermo
- feat: refs #7860 Update new packagings (origin/7860-newPackaging) by:guillermo
- feat: refs #7862 roadmap new fields by:ivanm
- feat: refs #7882 Added quadMindsConfig table by:guillermo
### Changed 📦
- refactor: refs #7567 Fix and improvement by:guillermo
- refactor: refs #7567 Minor change by:guillermo
- refactor: refs #7756 Fix tests by:guillermo
- refactor: refs #7798 Drop bi.Greuges_comercial_detail by:guillermo
- refactor: refs #7848 adapt to lilium by:alexm
### Fixed 🛠️
- feat: refs #7710 test fixed (origin/7710-cloneWithTicketPackaging, 7710-cloneWithTicketPackaging) by:jgallego
- feat: refs #7758 accountDetailType fix deploy error by:ivanm
- fix(salix): #7283 ItemFixedPrice duplicated (origin/7283_itemFixedPrice_duplicated) by:Javier Segarra
- fix: refs #7346 minor error (origin/7346, 7346) by:jgallego
- fix: refs #7355 remove and tests accounts (origin/7355-accountMigration2) by:carlossa
- fix: refs #7355 remove and tests accounts by:carlossa
- fix: refs #7524 default limit select by:jorgep
- fix: refs #7756 Foreign keys invoiceOut (origin/7756-fixRefFk) by:guillermo
- fix: refs #7756 id 0 by:guillermo
- fix: refs #7800 tpvMerchantEnable PRIMARY KEY (origin/7800-tpvMerchantEnable) by:guillermo
- fix: refs #7800 tpvMerchantEnable PRIMARY KEY by:guillermo
- fix: refs #7916 itemShelving_transfer (origin/test, test) by:guillermo
- fix: refs #pako Deleted duplicated version by:guillermo
# Version 24.34 - 2024-08-20
### Added 🆕
- #6900 feat: clear empty by:jorgep
- #6900 feat: empty commit by:jorgep
- chore: refs #6900 beautify code by:jorgep
- chore: refs #6989 add config model by:jorgep
- feat workerActivity refs #6078 by:sergiodt
- feat: #6453 Refactor (origin/6453-orderConfirm) by:guillermo
- feat: #6453 Rollback always split by itemPackingType by:guillermo
- feat: deleted worker module code & redirect to Lilium by:Jon
- feat: refs #6453 Added new ticket search by:guillermo
- feat: refs #6453 Fixes by:guillermo
- feat: refs #6453 Minor changes by:guillermo
- feat: refs #6453 Requested changes by:guillermo
- feat: refs #6900 drop section by:jorgep
- feat: refs #7283 order by desc date by:jorgep
- feat: refs #7323 add locale by:jorgep
- feat: refs #7323 redirect to lilium by:jorgep
- feat: refs #7646 delete scannableCodeType by:robert
- feat: refs #7713 Created ACLLog by:guillermo
- feat: refs #7774 (origin/7774-ticket_cloneWeekly) by:robert
- feat: refs #7774 #7774 Changes ticket_cloneWeekly by:guillermo
- feat: refs #7774 ticket_cloneWeekly by:robert
### Changed 📦
- refactor: refs #6453 Major changes by:guillermo
- refactor: refs #6453 Minor changes by:guillermo
- refactor: refs #6453 order_confirmWithUser by:guillermo
- refactor: refs #7646 #7646 Deleted scannable* variables productionConfig by:guillermo
- refactor: refs #7820 Deprecated silexACL by:guillermo
### Fixed 🛠️
- #6900 fix: #6900 rectificative filter by:jorgep
- #6900 fix: empty commit by:jorgep
- fix(orders_filter): add sourceApp accepts by:alexm
- fix: refs #6130 commit lint by:pablone
- fix: refs #6453 order_confirmWithUser by:guillermo
- fix: refs #7283 sql by:jorgep
- fix: refs #7713 ACL Log by:guillermo
- test: fix claim descriptor redirect to lilium by:alexm
- test: fix ticket redirect to lilium by:alexm
- test: fix ticket sale e2e by:alexm
# Version 24.32 - 2024-08-06
### Added 🆕
- chore: refs #7197 add supplierActivityFk filter by:jorgep
- feat checkExpeditionPrintOut refs #7751 by:sergiodt
- feat(defaulter_filter): add department by:alexm
- feat: redirect to lilium page not found by:alexm
- feat: refactor buyUltimate refs #7736 by:Carlos Andrés
- feat: refs #6403 add delete by:pablone
- feat: refs #7126 Added manaClaim calc by:guillermo
- feat: refs #7126 Refactor and added columns in bs.waste table & proc by:guillermo
- feat: refs #7197 filter by correcting by:jorgep
- feat: refs #7297 add new columns by:pablone
- feat: refs #7356 new parameters in sql for Weekly tickets front by:Jon
- feat: refs #7401 redirect lilium by:pablone
- feat: refs #7511 Fix tests by:guillermo
- feat: refs #7511 Rename to multiConfig tables by:guillermo
- feat: refs #7589 Added display (item_valuateInventory) by:guillermo
- feat: refs #7589 Added vItemTypeFk & vItemCategoryFk (item_valuateInventory) by:guillermo
- feat: refs #7681 Changes by:guillermo
- feat: refs #7681 Optimization and refactor by:guillermo
- feat: refs #7683 drop temporary table by:robert
- feat: refs #7683 productionControl by:robert
- feat: refs #7728 Added throw due date by:guillermo
- feat: refs #7740 Ticket before update added restriction by:guillermo
- feat(salix): #7648 Add field for endpoint as buyLabel report by:Javier Segarra
- feat(salix): #7648 remove white line by:Javier Segarra
- feat: tabla config dias margen vctos. refs #7728 by:Carlos Andrés
### Changed 📦
- eat: refactor buyUltimate refs #7736 by:Carlos Andrés
- feat: refactor buyUltimate refs #7736 by:Carlos Andrés
- feat: refs #7681 Optimization and refactor by:guillermo
- refactor: refs #7126 Requested changes by:guillermo
- refactor: refs #7511 Minor change by:guillermo
- refactor: refs #7640 Multipleinventory available by:guillermo
- refactor: refs #7681 Changes by:guillermo
- refactor: refs #7681 Requested changes by:guillermo
### Fixed 🛠️
- add prefix (hotFix_liliumRedirection) by:alexm
- fix(client_filter): add recovery by:alexm
- fix: defaulter filter correct sql (6943-fix_defaulter_filter) by:alexm
- fix(deletExpeditions): merge test → dev by:guillermo
- fix: refs #6403 fix mrw cancel shipment return type by:pablone
- fix: refs #7126 Added addressWaste type by:guillermo
- fix: refs #7126 Fix by:guillermo
- fix: refs #7126 Minor change by:guillermo
- fix: refs #7126 Primary key no unique data by:guillermo
- fix: refs #7126 Slow update by:guillermo
- fix: refs #7511 Minor change by:guillermo
- fix: refs #7546 Deleted insert util.binlogQueue by:guillermo
- fix: refs #7811 Variables pm2 by:guillermo
- fix: without path by:alexm
# Version 24.28 - 2024-07-09
### Added 🆕
- feat boxPicking refs #7357 by:sergiodt
- feat boxPicking refs #7357 (origin/7357_dipole_review) by:sergiodt
- feat:concurrency issue refs #6861 by:Carlos Andrés
- feat expeditionPalletPrint refs #5210 by:sergiodt
- feat front-reservas refs #6861 (origin/6861-Reservas-front) by:sergiodt
- feat itemShelving_filterBuyer refs #7023 by:sergiodt
- feat itemShelvingLog refs #7168 by:sergiodt
- feat itemShelvingSale refs #6861 by:sergiodt
- feat: previas con reserva refs #6861 by:Carlos Andrés
- feat: previas con sitema de reservas refs #6861 by:Carlos Andrés
- feat: previas con sitema de reservas refs #6861 (origin/6861-Pasar-modo-trabajo-de-previa-a-reservas) by:Carlos Andrés
- feat refactor setParking REGEXP refs #7575 (origin/7575_setParking_regExp) by:sergiodt
- feat: refs #6238 add travelKgPercentage table and model (origin/6238-addPercentage) by:jorgep
- feat: refs #6286 check if is teamBoss (origin/6286-setRightWorkerTimeControlAcls) by:jorgep
- feat: refs #6701 Fix error by:guillermo
- feat: refs #6861 trigger by:sergiodt
- feat: refs #7027 mailError managed by:jgallego
- feat: refs #7168 Added vRecords param in proc by:guillermo
- feat: refs #7168 Minor change by:guillermo
- feat: refs #7216 logUnpaid (origin/7216-clientUnpaid) by:jgallego
- feat: refs #7216 triggers by:jgallego
- feat: refs #7296 by:robert
- feat: refs #7296 drop column expeditionTruckFk by:robert
- feat: refs #7490 Changes (origin/7490-duaInvoiceInBooking) by:guillermo
- feat: refs #7545 Deleted hasIncoterms client column (origin/7545-hasIncoterms) by:guillermo
- feat: refs #7555 remove account.password__ by:alexm
- feat: return sql check error by:alexm
- feat roadmap refs #7195 by:sergiodt
- #refs 5890 feat:add assignCollection by:sergiodt
- refs#5890 feat: delete trigger and modify getTickets by:sergiodt
- refs #5890 feat:itemShelving_add by:sergiodt
- refs #5890 feat:reserves by:sergiodt
- refs #5890 feat:trigger by:sergiodt
- refs #5890 feat: triggers by:sergiodt
- refs #6861 feat: getLock by:sergiodt
- refs #6861 feat: obsrevation by:sergiodt
- refs #6861 feat: previas a reservas by:sergiodt
- refs #6861 feat:reserve previos by:sergiodt
- refs #6861 feat: reservePrevious by:sergiodt
- refs #6861 feat:reserveWithReservation by:sergiodt
- refs #6861 feat:sectoCollection reserve by:sergiodt
- refs #6861 feat: skipTest by:sergiodt
- refs #6861 feat: trigger by:sergiodt
### Changed 📦
- feat refactor setParking REGEXP refs #7575 (origin/7575_setParking_regExp) by:sergiodt
- refactor: refs #5447 changed models by:Jon
- refactor: refs #6238 drop useless round by:jorgep
- refactor: refs #6286 replace name by:jorgep
- refactor: refs #6701 Refactor claim_ratio_routine by:guillermo
- refactor: refs #7490 Added final update by:guillermo
- refactor: refs #7490 Deleted update duaInvoiceInBooking by:guillermo
- refactor: refs #7490 Minor changes by:guillermo
- refactor: refs #7519 Minor change by:guillermo
### Fixed 🛠️
- acls, fixtures, models by:carlossa
- fix: refs #6238 delete unused SQL script by:jorgep
- fix: refs #6238 insert ignore by:jorgep
- fix: refs #6238 use scheme by:jorgep
- fix: refs #6286 replace id for reason by:jorgep
- fix: refs #6286 update WorkerTimeControl permissions by:jorgep
- fix(WorkerIncome): refs #7409 fix models by:alexm
- refs #5890 fix: dev by:sergiodt
- refs #6897 fix entry Salix by:carlossa
- refs #6897 fix es.yml by:carlossa
- refs #6897 fix redirection by:carlossa
- refs #6897 fix remove by:carlossa
- refs #7406 fix back by:carlossa
- refs #7406 fix pr by:carlossa
- refs #7409 fix acls by:carlossa
- refs #7409 fix back (origin/7409-workerIncome) by:carlossa
- refs #7409 fix pr by:carlossa
# Version 24.24 - 2024-06-11
### Added 🆕
- 6281 feat:buyFk in itemShekving by:sergiodt
- 6281 feat:buyFk in itemShelving by:sergiodt
- feat: #6408 tests by:jgallego
- feat: packaging refs #4021 (origin/4021_packaging) by:sergiodt
- feat: refs #6021 add new field by:pablone
- feat: refs #6281 change fixtures by:robert
- feat: refs # 6408 test ok (origin/6408-rocketChat) by:jgallego
- feat: refs #6477 productionConfig add column by:robert
- feat: refs #6600 add column (origin/6600-createItemPhotoComment) by:jorgep
- feat: refs #6600 Add photoMotivation column to item table and create itemPhotoComment table by:jorgep
- feat: refs #6889 add back tests by:jorgep
- feat: refs #6889 fixtures & models by:jorgep
- feat : refs #6889 wip: check if is productionReviewer or owner by:jorgep
- feat: refs #6942 set false isBooed & ledger by:jorgep
- feat: refs #6942 toUnbook by:jorgep
- feat: refs #6942 xdiario fixtures by:jorgep
- feat: refs #7398 Change by:guillermo
- feat: refs #7438 Added volume to item_valuateInventory by:guillermo
- feat: refs #7438 Requested changes and little changes by:guillermo
- refs #6281 feat:buyFk in itemShelving by:sergiodt
- feat: refs #6449 item ID is displayed in the sale line by:jorgep
### Changed 📦
- refactor: refs #6600 add space by:jorgep
- refactor: refs #6889 improve file loading logic by:jorgep
- refactor: refs #6889 sale tests e2e by:jorgep
- refactor: refs #6889 script sql (origin/6889-dropAddSaleByCode) by:jorgep
- refactor: refs #6889 use addSale by:jorgep
- refactor: refs #6942 toUnbook & drop buyer acls by:jorgep
- refactor: refs #7398 Refactor and change ekt_scan (origin/7398-ektScan) by:guillermo
- refactor: refs #7486 Optimized procs by:guillermo
### Fixed 🛠️
- feat: refs #6281 change fixtures by:robert
- feat: refs #6889 fixtures & models by:jorgep
- feat: refs #6942 xdiario fixtures by:jorgep
- fix: checking process.env.NODE_ENV by:alexm
- fix: en translations by:alexm
- fix: move to boot (origin/7421-fix_checking_NODE_ENV, 7421-fix_checking_NODE_ENV) by:alexm
- fix: refs #6095 filter by refFk null by:pablone
- fix: refs #6600 rollback by:jorgep
- fix: refs #6889 allocate 'productionReviewer' role to revision dep. workers & check if is owner or reviewer by:jorgep
- fix: refs #6889 check if has collection or sectorCollection by:jorgep
- fix: refs #6889 e2e tests by:jorgep
- fix: refs #6889 fix back tests by:jorgep
- fix: refs #6889 modify fixtures by:jorgep
- fix: refs #6889 rollback by:jorgep
- fix: refs #6942 acls & back by:jorgep
- fix: refs #6942 add deleteById acl by:jorgep
- fix: refs #6942 add test & change column name by:jorgep
- fix: refs #6942 create invoiceIn acl by:jorgep
- fix: refs #6942 delete by:jorgep
- fix: refs #6942 drop quotes by:jorgep
- fix : refs #6942 remove grafana update priv by:jorgep
- fix: refs #6942 revoke update isBooked by:jorgep
- fix: refs #6942 toBook/toUnbook by:jorgep
- fix: refs #7442 Fix kubernetes deploy by:Juan Ferrer Toribio
- fix(salix): refs #7272 #7272 Add aclService in routes.js by:Javier Segarra
- fix(salix): refs #7272 #7272 Back validateToken endpoint by:Javier Segarra
- fix(salix): refs #7272 #7272 Bug when acl not loaded by:Javier Segarra
- fix(salix): refs #7272 #7272 Call validateToken by:Javier Segarra
- fix(salix): refs #7272 #7272 Errors when Token not exists by:Javier Segarra
- fix(salix): refs #7272 #7272 Front retry calls by:Javier Segarra
- fix(salix): refs #7272 #7272 i18n Error by:Javier Segarra
- fix(salix): refs #7272 #7272 Remove aclService from auth.js by:Javier Segarra
- fix: simplify by:alexm
- fix traduction & e2e by:carlossa
- refs #6820 fix back by:carlossa
- refs #6820 fix pr by:carlossa
- refs #6832 fix: ToItem (origin/6832_refactorBackToItem) by:Sergio De la torre
- refs #7292 fix tback by:carlossa
- refs #7296 fix pr errors, trad by:carlossa
- test(salix): refs #7272 #7272 fix renew-token.spec by:Javier Segarra
# Changelog

10
Jenkinsfile vendored
View File

@ -103,7 +103,7 @@ pipeline {
NODE_ENV = ''
}
steps {
sh 'node back/tests.js --junit'
sh 'node back/tests.js --ci --junit --network jenkins'
}
post {
always {
@ -121,7 +121,7 @@ pipeline {
steps {
script {
def packageJson = readJSON file: 'package.json'
env.VERSION = "${packageJson.version}-build${env.BUILD_ID}"
env.VERSION = packageJson.version
}
sh 'docker-compose build back'
}
@ -159,7 +159,7 @@ pipeline {
steps {
script {
def packageJson = readJSON file: 'package.json'
env.VERSION = "${packageJson.version}-build${env.BUILD_ID}"
env.VERSION = packageJson.version
}
sh 'gulp build'
sh 'docker-compose build front'
@ -179,7 +179,7 @@ pipeline {
steps {
script {
def packageJson = readJSON file: 'package.json'
env.VERSION = "${packageJson.version}-build${env.BUILD_ID}"
env.VERSION = packageJson.version
}
sh 'docker login --username $CREDENTIALS_USR --password $CREDENTIALS_PSW $REGISTRY'
sh 'docker-compose push'
@ -210,7 +210,7 @@ pipeline {
steps {
script {
def packageJson = readJSON file: 'package.json'
env.VERSION = "${packageJson.version}-build${env.BUILD_ID}"
env.VERSION = packageJson.version
}
withKubeConfig([
serverUrl: "$KUBERNETES_API",

View File

@ -28,7 +28,7 @@ Pull from repository.
Run this commands on project root directory to install Node dependencies.
```
$ pnpm install
$ npm install
$ gulp install
```

View File

@ -32,7 +32,8 @@ RUN apt-get update \
RUN apt-get update \
&& apt-get install -y --no-install-recommends \
samba-common-bin samba-dsdb-modules\
&& rm -rf /var/lib/apt/lists/*
&& rm -rf /var/lib/apt/lists/* \
&& npm -g install pm2
# Salix
@ -54,4 +55,7 @@ COPY \
README.md \
./
CMD ["node", "--tls-min-v1.0", "--openssl-legacy-provider", "./loopback/server/server.js"]
CMD ["pm2-runtime", "./back/process.yml"]
HEALTHCHECK --interval=15s --timeout=10s \
CMD curl -f http://localhost:3000/api/Applications/status || exit 1

View File

@ -20,14 +20,9 @@ module.exports = Self => {
if (typeof options == 'object')
Object.assign(myOptions, options);
const randStr = Math.random().toString(36).substring(3);
const result = await Self.rawSql(`
CALL vn.collection_assign(?, @vCollectionFk);
SELECT @vCollectionFk ?
`, [userId, randStr], myOptions);
// Por si entra en SELECT FOR UPDATE una o varias veces
const collectionFk = result.find(item => item[0]?.[randStr] !== undefined)?.[0]?.[randStr];
const [, , [{collectionFk}]] =
await Self.rawSql('CALL vn.collection_assign(?, @vCollectionFk); SELECT @vCollectionFk collectionFk',
[userId], myOptions);
if (!collectionFk) throw new UserError('There are not picking tickets');
await Self.rawSql('CALL vn.collection_printSticker(?, NULL)', [collectionFk], myOptions);

View File

@ -1,36 +0,0 @@
const UserError = require('vn-loopback/util/user-error');
module.exports = Self => {
Self.remoteMethodCtx('assignCollection', {
description: 'Assign a collection',
accessType: 'WRITE',
http: {
path: `/assignCollection`,
verb: 'POST'
},
returns: {
type: ['object'],
root: true
},
});
Self.assignCollection = async(ctx, options) => {
const userId = ctx.req.accessToken.userId;
const myOptions = {userId};
if (typeof options == 'object')
Object.assign(myOptions, options);
const randStr = Math.random().toString(36).substring(3);
const result = await Self.rawSql(`
CALL vn.collection_getAssigned(?, @vCollectionFk);
SELECT @vCollectionFk ?
`, [userId, randStr], myOptions);
const collectionFk = result.find(item => item[0]?.[randStr] !== undefined)?.[0]?.[randStr];
if (!collectionFk) throw new UserError('There are not picking tickets');
await Self.rawSql('CALL vn.collection_printSticker(?, NULL)', [collectionFk], myOptions);
return collectionFk;
};
};

View File

@ -1,6 +1,6 @@
module.exports = Self => {
Self.remoteMethodCtx('getSales', {
description: 'Get sales from ticket, collection or sectorCollection',
description: 'Get sales from ticket or collection',
accessType: 'READ',
accepts: [
{
@ -29,8 +29,10 @@ module.exports = Self => {
});
Self.getSales = async(ctx, collectionOrTicketFk, print, source, options) => {
const models = Self.app.models;
const userId = ctx.req.accessToken.userId;
const myOptions = {userId};
const $t = ctx.req.__;
if (typeof options == 'object')
Object.assign(myOptions, options);
@ -57,6 +59,20 @@ module.exports = Self => {
if (print) await Self.rawSql('CALL vn.collection_printSticker(?,NULL)', [id], myOptions);
for (let ticket of tickets) {
let observations = ticket.observaciones.split(' ');
for (let observation of observations) {
const salesPerson = ticket.salesPersonFk;
if (observation.startsWith('#') || observation.startsWith('@')) {
await models.Chat.send(ctx,
observation,
$t('ticketCommercial', {ticket: ticket.ticketFk, salesPerson})
);
}
}
}
return getCollection(id, tickets, sales, placements, myOptions);
};

View File

@ -37,7 +37,6 @@ module.exports = Self => {
const promises = [];
const [tickets] = await Self.rawSql(`CALL vn.collection_getTickets(?)`, [id], myOptions);
const sales = await Self.rawSql(`
SELECT s.ticketFk,
sgd.saleGroupFk,
@ -57,80 +56,37 @@ module.exports = Self => {
ROW_NUMBER () OVER (PARTITION BY s.id ORDER BY pickingOrder) currentItemShelving,
COUNT(*) OVER (PARTITION BY s.id ORDER BY s.id) totalItemShelving,
sh.code,
p2.code parkingCodePrevia,
p2.pickingOrder pickingOrderPrevia,
p.code parkingCode,
p.pickingOrder pickingOrder,
IFNULL(p2.code, p.code) parkingCode,
IFNULL(p2.pickingOrder, p.pickingOrder) pickingOrder,
iss.id itemShelvingSaleFk,
iss.isPicked,
iss.itemShelvingFk
iss.isPicked
FROM ticketCollection tc
LEFT JOIN collection c ON c.id = tc.collectionFk
JOIN sale s ON s.ticketFk = tc.ticketFk
JOIN ticket t ON t.id = tc.ticketFk
JOIN sale s ON s.ticketFk = t.id
LEFT JOIN saleGroupDetail sgd ON sgd.saleFk = s.id
LEFT JOIN saleGroup sg ON sg.id = sgd.saleGroupFk
LEFT JOIN parking p2 ON p2.id = sg.parkingFk
JOIN item i ON i.id = s.itemFk
JOIN itemShelvingSale iss ON iss.saleFk = s.id
LEFT JOIN itemShelvingSale iss ON iss.saleFk = s.id
LEFT JOIN itemShelving ish ON ish.id = iss.itemShelvingFk
LEFT JOIN shelving sh ON sh.id = ish.shelvingFk
LEFT JOIN shelving sh ON sh.code = ish.shelvingFk
LEFT JOIN parking p ON p.id = sh.parkingFk
LEFT JOIN itemColor ic ON ic.itemFk = s.itemFk
LEFT JOIN origin o ON o.id = i.originFk
WHERE tc.collectionFk = ?
GROUP BY s.id, ish.id, p.code, p2.code
UNION ALL
SELECT s.ticketFk,
sgd.saleGroupFk,
s.id saleFk,
s.itemFk,
i.longName,
i.size,
ic.color,
o.code origin,
ish.packing,
ish.grouping,
s.isAdded,
s.originalQuantity,
s.quantity,
iss.quantity,
SUM(iss.quantity) OVER (PARTITION BY s.id ORDER BY ish.id),
ROW_NUMBER () OVER (PARTITION BY s.id ORDER BY p.pickingOrder),
COUNT(*) OVER (PARTITION BY s.id ORDER BY s.id) ,
sh.code,
p2.code,
p2.pickingOrder,
p.code,
p.pickingOrder,
iss.id itemShelvingSaleFk,
iss.isPicked,
iss.itemShelvingFk
FROM sectorCollection sc
JOIN sectorCollectionSaleGroup ss ON ss.sectorCollectionFk = sc.id
JOIN saleGroup sg ON sg.id = ss.saleGroupFk
LEFT JOIN saleGroupDetail sgd ON sgd.saleGroupFk = sg.id
JOIN sale s ON s.id = sgd.saleFk
LEFT JOIN parking p2 ON p2.id = sg.parkingFk
JOIN item i ON i.id = s.itemFk
JOIN itemShelvingSale iss ON iss.saleFk = s.id
LEFT JOIN itemShelving ish ON ish.id = iss.itemShelvingFk
LEFT JOIN shelving sh ON sh.id = ish.shelvingFk
LEFT JOIN parking p ON p.id = sh.parkingFk
LEFT JOIN itemColor ic ON ic.itemFk = s.itemFk
LEFT JOIN origin o ON o.id = i.originFk
WHERE sc.id = ?
AND sgd.saleGroupFk
GROUP BY s.id, ish.id, p.code, p2.code`, [id, id], myOptions);
ORDER BY pickingOrder;`, [id], myOptions);
if (print)
await Self.rawSql(`CALL vn.collection_printSticker(?, ?)`, [id, null], myOptions);
const collection = {collectionFk: id, tickets: []};
if (tickets && tickets.length) {
for (const ticket of tickets) {
const ticketId = ticket.ticketFk;
if (ticket.observation) {
for (observation of ticket.observation?.split(' ')) {
if (ticket.observaciones != '') {
for (observation of ticket.observaciones.split(' ')) {
if (['#', '@'].includes(observation.charAt(0))) {
promises.push(Self.app.models.Chat.send(ctx, observation,
$t('The ticket is in preparation', {
@ -144,11 +100,11 @@ module.exports = Self => {
if (sales && sales.length) {
const barcodes = await Self.rawSql(`
SELECT s.id saleFk, b.code, c.id
FROM sale s
LEFT JOIN itemBarcode b ON b.itemFk = s.itemFk
LEFT JOIN buy c ON c.itemFk = s.itemFk
LEFT JOIN entry e ON e.id = c.entryFk
LEFT JOIN travel tr ON tr.id = e.travelFk
FROM vn.sale s
LEFT JOIN vn.itemBarcode b ON b.itemFk = s.itemFk
LEFT JOIN vn.buy c ON c.itemFk = s.itemFk
LEFT JOIN vn.entry e ON e.id = c.entryFk
LEFT JOIN vn.travel tr ON tr.id = e.travelFk
WHERE s.ticketFk = ?
AND tr.landed >= util.VN_CURDATE() - INTERVAL 1 YEAR`,
[ticketId], myOptions);

View File

@ -28,10 +28,9 @@ describe('ticket assign()', () => {
await tx.rollback();
});
it('should throw an error when there are no picking tickets', async() => {
it('should throw an error when there is not picking tickets', async() => {
try {
await models.Collection.assign(ctx, options);
fail('Expected an error to be thrown, but none was thrown.');
} catch (e) {
expect(e.message).toEqual('There are not picking tickets');
}

View File

@ -1,36 +0,0 @@
const models = require('vn-loopback/server/server').models;
const LoopBackContext = require('loopback-context');
describe('ticket assignCollection()', () => {
let ctx;
let options;
let tx;
beforeEach(async() => {
ctx = {
req: {
accessToken: {userId: 1106},
headers: {origin: 'http://localhost'},
__: value => value
},
args: {}
};
spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({active: ctx.req});
options = {transaction: tx};
tx = await models.Sale.beginTransaction({});
options.transaction = tx;
});
afterEach(async() => {
if (tx) await tx.rollback();
});
it('should throw an error when there is not picking tickets', async() => {
try {
await models.Collection.assignCollection(ctx, options);
} catch (e) {
expect(e.message).toEqual('There are not picking tickets');
}
});
});

View File

@ -4,7 +4,15 @@ describe('collection getSales()', () => {
const collectionOrTicketFk = 999999;
const print = true;
const source = 'CHECKER';
const ctx = beforeAll.getCtx();
beforeAll(() => {
ctx = {
req: {
accessToken: {userId: 9},
headers: {origin: 'http://localhost'},
}
};
});
it('should return a collection with tickets, placements and barcodes settled correctly', async() => {
const tx = await models.Collection.beginTransaction({});

View File

@ -1,7 +1,15 @@
const models = require('vn-loopback/server/server').models;
describe('collection getTickets()', () => {
const ctx = beforeAll.getCtx();
let ctx;
beforeAll(async() => {
ctx = {
req: {
accessToken: {userId: 9},
headers: {origin: 'http://localhost'}
}
};
});
it('should get tickets, sales and barcodes from collection', async() => {
const tx = await models.Collection.beginTransaction({});
@ -18,8 +26,8 @@ describe('collection getTickets()', () => {
expect(collectionTickets.tickets[1].ticketFk).toEqual(2);
expect(collectionTickets.tickets[2].ticketFk).toEqual(23);
expect(collectionTickets.tickets[0].sales[0].ticketFk).toEqual(1);
expect(collectionTickets.tickets[1].sales.length).toEqual(0);
expect(collectionTickets.tickets[2].sales.length).toEqual(0);
expect(collectionTickets.tickets[0].sales[1].ticketFk).toEqual(1);
expect(collectionTickets.tickets[0].sales[2].ticketFk).toEqual(1);
expect(collectionTickets.tickets[0].sales[0].Barcodes.length).toBeTruthy();
await tx.rollback();

View File

@ -1,7 +1,20 @@
const models = require('vn-loopback/server/server').models;
const LoopBackContext = require('loopback-context');
describe('setSaleQuantity()', () => {
beforeAll.mockLoopBackContext();
beforeAll(async() => {
const activeCtx = {
accessToken: {userId: 9},
http: {
req: {
headers: {origin: 'http://localhost'}
}
}
};
spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({
active: activeCtx
});
});
it('should change quantity sale', async() => {
const tx = await models.Ticket.beginTransaction({});

View File

@ -38,7 +38,7 @@ module.exports = Self => {
{
arg: 'hasFile',
type: 'Boolean',
description: 'True if has the original in paper'
description: 'True if has an attached file'
},
{
arg: 'hasFileAttached',

View File

@ -4,45 +4,21 @@ module.exports = Self => {
/**
* Returns basic headers
*
* @param {string} cookie - The docuware cookie
* @return {object} - The headers
*/
Self.getOptions = async() => {
const docuwareConfig = await Self.app.models.DocuwareConfig.findOne();
const now = Date.vnNow();
let {url, username, password, token, expired} = docuwareConfig;
if (process.env.NODE_ENV && (!expired || expired < now + 60)) {
const {data: {IdentityServiceUrl}} = await axios.get(`${url}/Home/IdentityServiceInfo`);
const {data: {token_endpoint}} = await axios.get(`${IdentityServiceUrl}/.well-known/openid-configuration`);
const {data} = await axios.post(token_endpoint, {
grant_type: 'password',
scope: 'docuware.platform',
client_id: 'docuware.platform.net.client',
username,
password
}, {headers: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded'
}});
const newToken = data.access_token;
token = data.token_type + ' ' + newToken;
await docuwareConfig.updateAttributes({
token,
expired: now + data.expires_in
});
}
const headers = {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': token
'Cookie': docuwareConfig.cookie
}
};
return {
url,
url: docuwareConfig.url,
headers
};
};

View File

@ -2,54 +2,87 @@ const axios = require('axios');
const models = require('vn-loopback/server/server').models;
describe('Docuware core', () => {
const fileCabinetCode = 'deliveryNote';
beforeAll(async() => {
beforeAll(() => {
process.env.NODE_ENV = 'testing';
});
const docuwareInfo = await models.Docuware.findOne({
where: {
code: fileCabinetCode
}
afterAll(() => {
delete process.env.NODE_ENV;
});
describe('getOptions()', () => {
it('should return url and headers', async() => {
const result = await models.Docuware.getOptions();
expect(result.url).toBeDefined();
expect(result.headers).toBeDefined();
});
});
spyOn(axios, 'get').and.callFake(url => {
if (url.includes('IdentityServiceInfo')) return {data: {IdentityServiceUrl: 'IdentityServiceUrl'}};
if (url.includes('IdentityServiceUrl')) return {data: {token_endpoint: 'token_endpoint'}};
if (url.includes('dialogs')) {
return {
data: {
Dialog: [
{
DisplayName: 'find',
Id: 'getDialogTest'
}
]
}
};
}
describe('getDialog()', () => {
it('should return dialogId', async() => {
const dialogs = {
data: {
Dialog: [
{
DisplayName: 'find',
Id: 'getDialogTest'
}
]
}
};
spyOn(axios, 'get').and.returnValue(new Promise(resolve => resolve(dialogs)));
const result = await models.Docuware.getDialog('deliveryNote', 'find', 'randomFileCabinetId');
if (url.includes('FileCabinets')) {
return {data: {
expect(result).toEqual('getDialogTest');
});
});
describe('getFileCabinet()', () => {
it('should return fileCabinetId', async() => {
const code = 'deliveryNote';
const docuwareInfo = await models.Docuware.findOne({
where: {
code
}
});
const dialogs = {
data: {
FileCabinet: [
{
Name: docuwareInfo.fileCabinetName,
Id: 'getFileCabinetTest'
}
]
}};
}
}
};
spyOn(axios, 'get').and.returnValue(new Promise(resolve => resolve(dialogs)));
const result = await models.Docuware.getFileCabinet(code);
expect(result).toEqual('getFileCabinetTest');
});
});
describe('get()', () => {
it('should return data without parse', async() => {
spyOn(models.Docuware, 'getFileCabinet').and.returnValue((new Promise(resolve => resolve(Math.random()))));
spyOn(models.Docuware, 'getDialog').and.returnValue((new Promise(resolve => resolve(Math.random()))));
const data = {
data: {
id: 1
}
};
spyOn(axios, 'post').and.returnValue(new Promise(resolve => resolve(data)));
const result = await models.Docuware.get('deliveryNote');
expect(result.id).toEqual(1);
});
spyOn(axios, 'post').and.callFake(url => {
if (url.includes('token_endpoint')) {
return {data: {
access_token: 'access_token',
token_type: 'bearer',
expires_in: 10000
}};
}
if (url.includes('DialogExpression')) {
return {data: {
it('should return data with parse', async() => {
spyOn(models.Docuware, 'getFileCabinet').and.returnValue((new Promise(resolve => resolve(Math.random()))));
spyOn(models.Docuware, 'getDialog').and.returnValue((new Promise(resolve => resolve(Math.random()))));
const data = {
data: {
Items: [{
Fields: [
{
@ -70,52 +103,12 @@ describe('Docuware core', () => {
]
}]
}
};
}
});
});
afterAll(() => {
delete process.env.NODE_ENV;
});
describe('getOptions()', () => {
it('should return url and headers', async() => {
const result = await models.Docuware.getOptions();
expect(result.url).toBeDefined();
expect(result.headers).toBeDefined();
});
});
describe('Dialog()', () => {
it('should return dialogId', async() => {
const result = await models.Docuware.getDialog('deliveryNote', 'find', 'randomFileCabinetId');
expect(result).toEqual('getDialogTest');
});
});
describe('getFileCabinet()', () => {
it('should return fileCabinetId', async() => {
const result = await models.Docuware.getFileCabinet(fileCabinetCode);
expect(result).toEqual('getFileCabinetTest');
});
});
describe('get()', () => {
it('should return data without parse', async() => {
const [result] = await models.Docuware.get('deliveryNote');
expect(result.firstRequiredField).toEqual(1);
});
it('should return data with parse', async() => {
};
const parse = {
'firstRequiredField': 'id',
'secondRequiredField': 'name',
};
spyOn(axios, 'post').and.returnValue(new Promise(resolve => resolve(data)));
const [result] = await models.Docuware.get('deliveryNote', null, parse);
expect(result.id).toEqual(1);
@ -126,14 +119,17 @@ describe('Docuware core', () => {
describe('getById()', () => {
it('should return data', async() => {
spyOn(models.Docuware, 'get');
await models.Docuware.getById('deliveryNote', 1);
spyOn(models.Docuware, 'getFileCabinet').and.returnValue((new Promise(resolve => resolve(Math.random()))));
spyOn(models.Docuware, 'getDialog').and.returnValue((new Promise(resolve => resolve(Math.random()))));
const data = {
data: {
id: 1
}
};
spyOn(axios, 'post').and.returnValue(new Promise(resolve => resolve(data)));
const result = await models.Docuware.getById('deliveryNote', 1);
expect(models.Docuware.get).toHaveBeenCalledWith(
'deliveryNote',
{condition: [Object({DBName: 'N__ALBAR_N', Value: [1]})]},
undefined
);
expect(result.id).toEqual(1);
});
});
});

View File

@ -143,7 +143,7 @@ module.exports = Self => {
headers: {
'Content-Type': 'multipart/form-data',
'X-File-ModifiedDate': Date.vnNew(),
'Authorization': docuwareOptions.headers.headers.Authorization,
'Cookie': docuwareOptions.headers.headers.Cookie,
...data.getHeaders()
},
};

View File

@ -24,7 +24,7 @@ module.exports = Self => {
try {
const options = {transaction: tx, userId: ctx.req.accessToken.userId};
const files = await Self.rawSql('SELECT name, checksum, keyValue FROM edi.fileMultiConfig', null, options);
const files = await Self.rawSql('SELECT name, checksum, keyValue FROM edi.fileConfig', null, options);
const updatableFiles = [];
for (const file of files) {
@ -54,7 +54,7 @@ module.exports = Self => {
const tables = await Self.rawSql(`
SELECT fileName, toTable, file
FROM edi.tableMultiConfig
FROM edi.tableConfig
WHERE file IN (?)`, [fileNames], options);
for (const table of tables) {
@ -85,9 +85,9 @@ module.exports = Self => {
for (const file of updatableFiles) {
console.log(`Updating file ${file.name} checksum...`);
await Self.rawSql(`
UPDATE edi.fileMultiConfig
SET checksum = ?
WHERE name = ?`,
UPDATE edi.fileConfig
SET checksum = ?
WHERE name = ?`,
[file.checksum, file.name], options);
}
@ -228,7 +228,7 @@ module.exports = Self => {
await Self.rawSql(sqlTemplate, [filePath], options);
await Self.rawSql(`
UPDATE edi.tableMultiConfig
UPDATE edi.tableConfig
SET updated = ?
WHERE fileName = ?
`, [Date.vnNew(), baseName], options);

View File

@ -0,0 +1,132 @@
const {models} = require('vn-loopback/server/server');
describe('machineWorker updateInTime()', () => {
const itBoss = 104;
const davidCharles = 1106;
beforeAll(async() => {
ctx = {
req: {
accessToken: {},
headers: {origin: 'http://localhost'},
__: value => value
}
};
});
it('should throw an error if the plate does not exist', async() => {
const tx = await models.MachineWorker.beginTransaction({});
const options = {transaction: tx};
const plate = 'RE-123';
ctx.req.accessToken.userId = 1106;
try {
await models.MachineWorker.updateInTime(ctx, plate, options);
await tx.rollback();
} catch (e) {
const error = e;
expect(error.message).toContain('the plate does not exist');
await tx.rollback();
}
});
it('should grab a machine where is not in use', async() => {
const tx = await models.MachineWorker.beginTransaction({});
const options = {transaction: tx};
const plate = 'RE-003';
ctx.req.accessToken.userId = 1107;
try {
const totalBefore = await models.MachineWorker.find(null, options);
await models.MachineWorker.updateInTime(ctx, plate, options);
const totalAfter = await models.MachineWorker.find(null, options);
expect(totalAfter.length).toEqual(totalBefore.length + 1);
await tx.rollback();
} catch (e) {
await tx.rollback();
}
});
describe('less than 12h', () => {
const plate = 'RE-001';
it('should trow an error if it is not himself', async() => {
const tx = await models.MachineWorker.beginTransaction({});
const options = {transaction: tx};
ctx.req.accessToken.userId = davidCharles;
try {
await models.MachineWorker.updateInTime(ctx, plate, options);
await tx.rollback();
} catch (e) {
const error = e;
expect(error.message).toContain('This machine is already in use');
await tx.rollback();
}
});
it('should throw an error if it is himself with a different machine', async() => {
const tx = await models.MachineWorker.beginTransaction({});
const options = {transaction: tx};
ctx.req.accessToken.userId = itBoss;
const plate = 'RE-003';
try {
await models.MachineWorker.updateInTime(ctx, plate, options);
await tx.rollback();
} catch (e) {
const error = e;
expect(error.message).toEqual('You are already using a machine');
await tx.rollback();
}
});
it('should set the out time if it is himself', async() => {
const tx = await models.MachineWorker.beginTransaction({});
const options = {transaction: tx};
ctx.req.accessToken.userId = itBoss;
try {
const isNotParked = await models.MachineWorker.findOne({
where: {workerFk: itBoss}
}, options);
await models.MachineWorker.updateInTime(ctx, plate, options);
const isParked = await models.MachineWorker.findOne({
where: {workerFk: itBoss}
}, options);
expect(isNotParked.outTime).toBeNull();
expect(isParked.outTime).toBeDefined();
await tx.rollback();
} catch (e) {
await tx.rollback();
}
});
});
describe('equal or more than 12h', () => {
const plate = 'RE-002';
it('should set the out time and grab the machine', async() => {
const tx = await models.MachineWorker.beginTransaction({});
const options = {transaction: tx};
ctx.req.accessToken.userId = davidCharles;
const filter = {
where: {workerFk: davidCharles, machineFk: 2}
};
try {
const isNotParked = await models.MachineWorker.findOne(filter, options);
const totalBefore = await models.MachineWorker.find(null, options);
await models.MachineWorker.updateInTime(ctx, plate, options);
const isParked = await models.MachineWorker.findOne(filter, options);
const totalAfter = await models.MachineWorker.find(null, options);
expect(isNotParked.outTime).toBeNull();
expect(isParked.outTime).toBeDefined();
expect(totalAfter.length).toEqual(totalBefore.length + 1);
await tx.rollback();
} catch (e) {
await tx.rollback();
}
});
});
});

View File

@ -0,0 +1,77 @@
const UserError = require('vn-loopback/util/user-error');
module.exports = Self => {
Self.remoteMethodCtx('updateInTime', {
description: 'Updates the corresponding registry if the worker has been registered in the last few hours',
accessType: 'WRITE',
accepts: [
{
arg: 'plate',
type: 'string',
}
],
http: {
path: `/updateInTime`,
verb: 'POST'
}
});
Self.updateInTime = async(ctx, plate, options) => {
const models = Self.app.models;
const userId = ctx.req.accessToken.userId;
const $t = ctx.req.__;
let tx;
const myOptions = {};
if (typeof options == 'object')
Object.assign(myOptions, options);
if (!myOptions.transaction) {
tx = await Self.beginTransaction({});
myOptions.transaction = tx;
}
try {
const machine = await models.Machine.findOne({
fields: ['id', 'plate'],
where: {plate}
}, myOptions);
if (!machine)
throw new UserError($t('the plate does not exist', {plate}));
const machineWorker = await Self.findOne({
where: {
or: [{machineFk: machine.id}, {workerFk: userId}],
outTime: null,
}
}, myOptions);
const {maxHours} = await models.MachineWorkerConfig.findOne({fields: ['maxHours']}, myOptions);
const hoursDifference = (Date.vnNow() - machineWorker?.inTime?.getTime() ?? 0) / (60 * 60 * 1000);
if (machineWorker) {
const isHimself = userId == machineWorker.workerFk;
const isSameMachine = machine.id == machineWorker.machineFk;
if (hoursDifference < maxHours && !isHimself)
throw new UserError($t('This machine is already in use.'));
if (hoursDifference < maxHours && isHimself && !isSameMachine)
throw new UserError($t('You are already using a machine'));
await machineWorker.updateAttributes({
outTime: Date.vnNew()
}, myOptions);
}
if (!machineWorker || hoursDifference >= maxHours)
await models.MachineWorker.create({machineFk: machine.id, workerFk: userId}, myOptions);
if (tx) await tx.commit();
} catch (e) {
if (tx) await tx.rollback();
throw e;
}
};
};

View File

@ -2,7 +2,7 @@
<soap:Header>
<mrw:AuthInfo>
<mrw:CodigoFranquicia><%= mrw.franchiseCode %></mrw:CodigoFranquicia>
<mrw:CodigoAbonado><%= clientType %></mrw:CodigoAbonado>
<mrw:CodigoAbonado><%= mrw.subscriberCode %></mrw:CodigoAbonado>
<mrw:CodigoDepartamento/>
<mrw:UserName><%= mrw.user %></mrw:UserName>
<mrw:Password><%= mrw.password %></mrw:Password>

View File

@ -13,7 +13,7 @@ module.exports = Self => {
required: true
}],
returns: {
type: 'boolean',
type: ['object'],
root: true
},
http: {
@ -27,9 +27,9 @@ module.exports = Self => {
const mrw = await models.MrwConfig.findOne();
const {externalId} = await models.Expedition.findById(expeditionFk);
const clientType = await models.MrwConfig.getClientType(expeditionFk);
const template = fs.readFileSync(__dirname + '/cancelShipment.ejs', 'utf-8');
const renderedXml = ejs.render(template, {mrw, externalId, clientType});
const renderedXml = ejs.render(template, {mrw, externalId});
const response = await axios.post(mrw.url, renderedXml, {
headers: {
'Content-Type': 'application/soap+xml; charset=utf-8'
@ -39,10 +39,6 @@ module.exports = Self => {
const xmlString = response.data;
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(xmlString, 'text/xml');
await Self.rawSql('CALL util.debugAdd(?,?);', ['cancelShipment', xmlDoc]);
const result = xmlDoc.getElementsByTagName('Mensaje')[0].textContent;
return result.toLowerCase().includes('se ha cancelado correctamente');
return xmlDoc.getElementsByTagName('Mensaje')[0].textContent;
};
};

View File

@ -3,7 +3,7 @@
<soap:Header>
<mrw:AuthInfo>
<mrw:CodigoFranquicia><%= mrw.franchiseCode %></mrw:CodigoFranquicia>
<mrw:CodigoAbonado><%= clientType %></mrw:CodigoAbonado>
<mrw:CodigoAbonado><%= mrw.subscriberCode %></mrw:CodigoAbonado>
<mrw:CodigoDepartamento/>
<mrw:UserName><%= mrw.user %></mrw:UserName>
<mrw:Password><%= mrw.password %></mrw:Password>
@ -25,25 +25,17 @@
</mrw:Direccion>
<mrw:Nif><%= expeditionData.fi %></mrw:Nif>
<mrw:Nombre><%= expeditionData.clientName %></mrw:Nombre>
<mrw:Telefono><%= expeditionData.mobile %></mrw:Telefono>
<mrw:Observaciones><%= expeditionData.deliveryObservation %></mrw:Observaciones>
<mrw:Telefono><%= expeditionData.phone %></mrw:Telefono>
</mrw:DatosEntrega>
<mrw:DatosServicio>
<mrw:Fecha><%= expeditionData.created %></mrw:Fecha>
<mrw:Referencia><%= expeditionData.reference %></mrw:Referencia>
<mrw:Referencia><%= expeditionData.expeditionDataId %></mrw:Referencia>
<mrw:CodigoServicio><%= expeditionData.serviceType %></mrw:CodigoServicio>
<mrw:NumeroBultos>1</mrw:NumeroBultos>
<mrw:EntregaSabado><%= expeditionData.weekDays %></mrw:EntregaSabado>
<mrw:Peso><%= expeditionData.kg %></mrw:Peso>
<mrw:Reembolso/>
<mrw:ImporteReembolso/>
<mrw:Bultos>
<mrw:BultoRequest>
<mrw:Alto><%= mrw.defaultHeight %></mrw:Alto>
<mrw:Largo><%= mrw.defaultLength %></mrw:Largo>
<mrw:Ancho><%= mrw.defaultWidth %></mrw:Ancho>
<mrw:Peso><%= mrw.defaultWeight %></mrw:Peso>
</mrw:BultoRequest>
</mrw:Bultos>
</mrw:DatosServicio>
</mrw:request>
</mrw:TransmEnvio>

View File

@ -1,3 +1,7 @@
const axios = require('axios');
const {DOMParser} = require('xmldom');
const fs = require('fs');
const ejs = require('ejs');
const UserError = require('vn-loopback/util/user-error');
module.exports = Self => {
@ -19,27 +23,29 @@ module.exports = Self => {
}
});
Self.createShipment = async expeditionFk => {
const models = Self.app.models;
const mrw = await Self.getConfig();
const clientType = await models.MrwConfig.getClientType(expeditionFk);
Self.createShipment = async(expeditionFk, options) => {
const myOptions = {};
let tx;
const today = Date.vnNew();
const [hours, minutes] = mrw?.expeditionDeadLine ? mrw.expeditionDeadLine.split(':').map(Number) : [0, 0];
if (typeof options == 'object')
Object.assign(myOptions, options);
const deadLine = Date.vnNew();
deadLine.setHours(hours, minutes, 0);
if (today > deadLine && (!mrw.notified || mrw.notified.setHours(0, 0, 0, 0) !== today.setHours(0, 0, 0, 0))) {
await models.NotificationQueue.create({notificationFk: 'mrw-deadline'});
await mrw.updateAttributes({notified: Date.vnNow()});
if (!myOptions.transaction) {
tx = await Self.beginTransaction({});
myOptions.transaction = tx;
}
const models = Self.app.models;
const mrw = await models.MrwConfig.findOne(null, myOptions);
if (!mrw)
throw new UserError(`Some mrwConfig parameters are not set`);
const query =
`SELECT
CASE co.code
WHEN 'ES' THEN a.postalCode
WHEN 'PT' THEN LEFT(a.postalCode, mc.portugalPostCodeTrim)
WHEN 'PT' THEN LEFT(a.postalCode, 4)
WHEN 'AD' THEN REPLACE(a.postalCode, 'AD', '00')
END postalCode,
a.city,
@ -47,45 +53,62 @@ module.exports = Self => {
co.code countryCode,
c.fi,
c.name clientName,
IFNULL(a.mobile, c.mobile) mobile,
c.phone,
DATE_FORMAT(t.shipped, '%d/%m/%Y') created,
t.shipped,
CONCAT( e.ticketFk, LPAD(e.counter, mc.counterWidth, '0')) reference,
LPAD(IF(mw.serviceType IS NULL, ms.serviceType, mw.serviceType), mc.serviceTypeWidth, '0') serviceType,
IF(mw.weekdays, 'S', 'N') weekDays,
ta.description deliveryObservation
e.id expeditionId,
LPAD(IF(mw.params IS NULL, ms.serviceType, mw.serviceType), 4 ,'0') serviceType,
IF(mw.weekdays, 'S', 'N') weekDays
FROM expedition e
JOIN ticket t ON e.ticketFk = t.id
JOIN agencyMode am ON am.id = t.agencyModeFk
JOIN mrwService ms ON ms.agencyModeCodeFk = am.code
LEFT JOIN mrwServiceWeekday mw ON mw.agencyModeCodeFk = am.code
AND mw.weekDays & (1 << WEEKDAY(t.landed))
LEFT JOIN mrwServiceWeekday mw ON mw.weekdays = DATE_FORMAT(t.shipped, '%a')
JOIN client c ON t.clientFk = c.id
JOIN address a ON t.addressFk = a.id
LEFT JOIN ticketObservation ta ON ta.ticketFk = t.id
AND ta.observationTypeFk IN (SELECT id FROM observationType ot WHERE ot.code = 'agency')
JOIN province p ON a.provinceFk = p.id
JOIN country co ON co.id = p.countryFk
JOIN mrwConfig mc
WHERE e.id = ?
LIMIT 1`;
const [expeditionData] = await Self.rawSql(query, [expeditionFk]);
const [expeditionData] = await Self.rawSql(query, [expeditionFk], myOptions);
if (expeditionData?.shipped.setHours(0, 0, 0, 0) < today.setHours(0, 0, 0, 0))
if (!expeditionData)
throw new UserError(`This expedition is not a MRW shipment`);
const today = Date.vnNew();
today.setHours(0, 0, 0, 0);
if (expeditionData?.shipped.setHours(0, 0, 0, 0) < today)
throw new UserError(`This ticket has a shipped date earlier than today`);
const shipmentResponse = await Self.sendXmlDoc(
__dirname + `/createShipment.ejs`,
{mrw, expeditionData, clientType},
'application/soap+xml'
);
const shipmentId = Self.getTextByTag(shipmentResponse, 'NumeroEnvio');
const shipmentResponse = await sendXmlDoc('createShipment', {mrw, expeditionData}, 'application/soap+xml');
const shipmentId = getTextByTag(shipmentResponse, 'NumeroEnvio');
if (!shipmentId) throw new UserError(Self.getTextByTag(shipmentResponse, 'Mensaje'));
if (!shipmentId)
throw new UserError(getTextByTag(shipmentResponse, 'Mensaje'));
const file = await models.MrwConfig.getLabel(shipmentId, clientType);
const getLabelResponse = await sendXmlDoc('getLabel', {mrw, shipmentId}, 'text/xml');
const file = getTextByTag(getLabelResponse, 'EtiquetaFile');
if (tx) await tx.commit();
return {shipmentId, file};
};
function getTextByTag(xmlDoc, tag) {
return xmlDoc?.getElementsByTagName(tag)[0]?.textContent;
}
async function sendXmlDoc(xmlDock, params, contentType) {
const parser = new DOMParser();
const xmlTemplate = fs.readFileSync(__dirname + `/${xmlDock}.ejs`, 'utf-8');
const renderedTemplate = ejs.render(xmlTemplate, params);
const data = await axios.post(params.mrw.url, renderedTemplate, {
headers: {
'Content-Type': `${contentType}; charset=utf-8`
}
});
return parser.parseFromString(data.data, 'text/xml');
}
};

View File

@ -2,7 +2,7 @@
<soapenv:Header>
<mrw:AuthInfo>
<mrw:CodigoFranquicia><%= mrw.franchiseCode %></mrw:CodigoFranquicia>
<mrw:CodigoAbonado><%= clientType %></mrw:CodigoAbonado>
<mrw:CodigoAbonado><%= mrw.subscriberCode %></mrw:CodigoAbonado>
<mrw:CodigoDepartamento/>
<mrw:UserName><%= mrw.user %></mrw:UserName>
<mrw:Password><%= mrw.password %></mrw:Password>

View File

@ -1,37 +0,0 @@
module.exports = Self => {
Self.remoteMethod('getLabel', {
description: 'Return a base64Binary label from de MRW WebService',
accessType: 'READ',
accepts: [{
arg: 'shipmentId',
type: 'string',
required: true
},
{
arg: 'clientType',
type: 'string',
required: true
},
],
returns: {
type: 'string',
root: true
},
http: {
path: `/getLabel`,
verb: 'GET'
}
});
Self.getLabel = async(shipmentId, clientType) => {
const mrw = await Self.getConfig();
const getLabelResponse = await Self.sendXmlDoc(
__dirname + `/getLabel.ejs`,
{mrw, shipmentId, clientType},
'text/xml'
);
return Self.getTextByTag(getLabelResponse, 'EtiquetaFile');
};
};

View File

@ -2,7 +2,6 @@ const models = require('vn-loopback/server/server').models;
const axios = require('axios');
const fs = require('fs');
const filter = {notificationFk: 'mrw-deadline'};
const mockBase64Binary = 'base64BinaryString';
const ticket1 = {
'id': '44',
@ -12,8 +11,9 @@ const ticket1 = {
'addressFk': 1,
'agencyModeFk': 999
};
let expedition;
const expedition1 = {
'id': 17,
'agencyModeFk': 999,
'ticketFk': 44,
'freightItemFk': 71,
@ -28,49 +28,25 @@ const expedition1 = {
'editorFk': 100
};
let tx;
let options;
describe('MRWConfig createShipment()', () => {
beforeAll(async() => {
beforeEach(async() => {
options = tx = undefined;
tx = await models.MrwConfig.beginTransaction({});
options = {transaction: tx};
await models.Agency.create(
{'id': 999, 'name': 'mrw'}
{'id': 999, 'name': 'mrw'},
options
);
await models.AgencyMode.create(
{'id': 999, 'name': 'mrw', 'agencyFk': 999, 'code': 'mrw'}
{'id': 999, 'name': 'mrw', 'agencyFk': 999, 'code': 'mrw'},
options
);
await models.MrwService.create(
{'agencyModeCodeFk': 'mrw', 'clientType': '000001', 'serviceType': 105, 'kg': 10}
);
await createMrwConfig();
await models.Ticket.create(ticket1);
expedition = await models.Expedition.create(expedition1);
});
afterAll(async() => {
await cleanFixtures();
await models.Ticket.destroyAll(ticket1);
await models.Expedition.destroyAll(ticket1);
});
beforeEach(async() => {
const mockPostResponses = [
{data: fs.readFileSync(__dirname + '/mockGetLabel.xml', 'utf-8')},
{data: fs.readFileSync(__dirname + '/mockCreateShipment.xml', 'utf-8')}
];
spyOn(axios, 'post').and.callFake(() => Promise.resolve(mockPostResponses.pop()));
await cleanFixtures();
});
async function cleanFixtures() {
await models.NotificationQueue.destroyAll(filter);
await models.MrwConfig.updateAll({id: 1}, {expeditionDeadLine: null, notified: null});
}
async function createMrwConfig() {
await models.MrwConfig.create(
{
'id': 1,
@ -78,82 +54,68 @@ describe('MRWConfig createShipment()', () => {
'user': 'user',
'password': 'password',
'franchiseCode': 'franchiseCode',
'subscriberCode': 'subscriberCode',
'clientTypeWidth': 6
}
'subscriberCode': 'subscriberCode'
}, options
);
}
async function getLastNotification() {
return models.NotificationQueue.findOne({
order: 'id DESC',
where: filter
});
}
await models.Application.rawSql(
`INSERT INTO vn.mrwService
SET agencyModeCodeFk = 'mrw',
clientType = 1,
serviceType = 1,
kg = 1`, null, options
);
await models.Ticket.create(ticket1, options);
await models.Expedition.create(expedition1, options);
});
afterEach(async() => {
await tx.rollback();
});
it('should create a shipment and return a base64Binary label', async() => {
const {file} = await models.MrwConfig.createShipment(expedition.id);
const mockPostResponses = [
{data: fs.readFileSync(__dirname + '/mockGetLabel.xml', 'utf-8')},
{data: fs.readFileSync(__dirname + '/mockCreateShipment.xml', 'utf-8')}
];
spyOn(axios, 'post').and.callFake(() => Promise.resolve(mockPostResponses.pop()));
const {file} = await models.MrwConfig.createShipment(expedition1.id, options);
expect(file).toEqual(mockBase64Binary);
});
it('should fail if mrwConfig has no data', async() => {
let error;
await models.MrwConfig.destroyAll();
await models.MrwConfig.createShipment(expedition.id).catch(e => {
await models.MrwConfig.createShipment(expedition1.id).catch(e => {
error = e;
}).finally(async() => {
expect(error.message).toEqual(`MRW service is not configured`);
expect(error.message).toEqual(`Some mrwConfig parameters are not set`);
});
await createMrwConfig();
expect(error).toBeDefined();
});
it('should fail if expeditionFk is not a MrwExpedition', async() => {
let error;
await models.MrwConfig.createShipment(15).catch(e => {
await models.MrwConfig.createShipment(undefined, options).catch(e => {
error = e;
}).finally(async() => {
expect(error.message).toEqual(`ClientType not available`);
expect(error.message).toEqual(`This expedition is not a MRW shipment`);
});
});
it('should fail if the creation date of this ticket is before the current date', async() => {
it(' should fail if the creation date of this ticket is before the current date it', async() => {
let error;
const yesterday = Date.vnNew();
yesterday.setDate(yesterday.getDate() - 1);
await models.Ticket.updateAll({id: ticket1.id}, {shipped: yesterday});
await models.MrwConfig.createShipment(expedition.id).catch(e => {
yesterday.setDate(yesterday.getDate() - 1);
await models.Ticket.updateAll({id: ticket1.id}, {shipped: yesterday}, options);
await models.MrwConfig.createShipment(expedition1.id, options).catch(e => {
error = e;
}).finally(async() => {
expect(error.message).toEqual(`This ticket has a shipped date earlier than today`);
});
await models.Ticket.updateAll({id: ticket1.id}, {shipped: Date.vnNew()});
});
it('should send mail if you are past the dead line and is not notified today', async() => {
await models.MrwConfig.updateAll({id: 1}, {expeditionDeadLine: '10:00:00', notified: null});
await models.MrwConfig.createShipment(expedition.id);
const notification = await getLastNotification();
expect(notification.notificationFk).toEqual(filter.notificationFk);
});
it('should send mail if you are past the dead line and it is notified from another day', async() => {
await models.MrwConfig.updateAll({id: 1}, {expeditionDeadLine: '10:00:00', notified: new Date()});
await models.MrwConfig.createShipment(expedition.id);
const notification = await getLastNotification();
expect(notification.notificationFk).toEqual(filter.notificationFk);
});
it('should not send mail if you are past the dead line and it is notified', async() => {
await models.MrwConfig.updateAll({id: 1}, {expeditionDeadLine: '10:00:00', notified: Date.vnNew()});
await models.MrwConfig.createShipment(expedition.id);
const notification = await getLastNotification();
expect(notification).toEqual(null);
});
});

View File

@ -11,6 +11,13 @@ module.exports = Self => {
arg: 'filter',
type: 'object',
description: 'Filter defining where, order, offset, and limit - must be a JSON-encoded string',
http: {source: 'query'}
},
{
arg: 'search',
type: 'string',
description: 'Value to filter',
http: {source: 'query'}
},
],
returns: {
@ -22,11 +29,13 @@ module.exports = Self => {
verb: 'GET',
},
});
Self.filter = async(filter = {}, options) => {
Self.filter = async(ctx, filter, options) => {
const myOptions = {};
if (typeof options == 'object')
Object.assign(myOptions, options);
filter = ctx?.filter ?? {};
const conn = Self.dataSource.connector;
const where = buildFilter(filter?.where, (param, value) => {
switch (param) {
@ -41,33 +50,31 @@ module.exports = Self => {
};
}
}) ?? {};
delete filter.where;
delete ctx.filter.where;
const stmts = [];
let stmt;
stmt = new ParameterizedSQL(`
SELECT
pc.townFk,
t.provinceFk,
p.countryFk,
pc.code,
t.name as town,
p.name as province,
c.name country
FROM
postCode pc
JOIN town t on t.id = pc.townFk
JOIN province p on p.id = t.provinceFk
JOIN country c on c.id = p.countryFk
SELECT
pc.townFk,
t.provinceFk,
p.countryFk,
pc.code,
t.name as town,
p.name as province,
c.name country
FROM
postCode pc
JOIN town t on t.id = pc.townFk
JOIN province p on p.id = t.provinceFk
JOIN country c on c.id = p.countryFk
`);
stmt.merge(conn.makeSuffix({where}));
stmt.merge(conn.makeLimit(filter));
stmt.merge(conn.makeSuffix({where, ...ctx}));
const itemsIndex = stmts.push(stmt) - 1;
const sql = ParameterizedSQL.join(stmts, ';');
const result = await conn.executeStmt(sql, myOptions);
return itemsIndex === 0 ? result : result[itemsIndex];
};
};

View File

@ -6,9 +6,12 @@ describe('Postcode filter()', () => {
const options = {transaction: tx};
try {
const results = await models.Postcode.filter({
const ctx = {
filter: {
},
limit: 1
}, options);
};
const results = await models.Postcode.filter(ctx, options);
expect(results.length).toEqual(1);
await tx.rollback();
@ -23,13 +26,16 @@ describe('Postcode filter()', () => {
const options = {transaction: tx};
try {
const results = await models.Postcode.filter({
where: {
search: 46,
}
}, options);
const ctx = {
filter: {
where: {
search: 46,
}
},
};
const results = await models.Postcode.filter(ctx, options);
expect(results.length).toEqual(5);
expect(results.length).toEqual(4);
await tx.rollback();
} catch (e) {
await tx.rollback();
@ -42,9 +48,14 @@ describe('Postcode filter()', () => {
const options = {transaction: tx};
try {
const results = await models.Postcode.filter({where: {
search: 'Alz',
}}, options);
const ctx = {
filter: {
where: {
search: 'Alz',
}
},
};
const results = await models.Postcode.filter(ctx, options);
expect(results.length).toEqual(1);
await tx.rollback();
@ -59,11 +70,16 @@ describe('Postcode filter()', () => {
const options = {transaction: tx};
try {
const results = await models.Postcode.filter({where: {
search: 'one',
}}, options);
const ctx = {
filter: {
where: {
search: 'one',
}
},
};
const results = await models.Postcode.filter(ctx, options);
expect(results.length).toEqual(5);
expect(results.length).toEqual(4);
await tx.rollback();
} catch (e) {
await tx.rollback();
@ -76,11 +92,14 @@ describe('Postcode filter()', () => {
const options = {transaction: tx};
try {
const results = await models.Postcode.filter({
where: {
search: 'Ec',
}
}, options);
const ctx = {
filter: {
where: {
search: 'Ec',
}
},
};
const results = await models.Postcode.filter(ctx, options);
expect(results.length).toEqual(1);
await tx.rollback();

View File

@ -1,88 +0,0 @@
const axios = require('axios');
const UserError = require('vn-loopback/util/user-error');
const moment = require('moment');
module.exports = Self => {
Self.remoteMethod('sendOrders', {
description: 'Sends a set of orders',
accessType: 'WRITE',
accepts: [{
arg: 'tickets',
type: ['number'],
required: true
}
],
returns: {
type: 'string',
root: true
},
http: {
path: `/sendOrders`,
verb: 'POST'
}
});
Self.sendOrders = async tickets => {
const config = await Self.app.models.QuadmindsApiConfig.findOne();
if (!config) throw new UserError('Config params not set');
if (tickets.length > config.maxObjects)
throw new UserError(`Quadminds does not support more than ${config.maxObjects} tickets`);
let poisData = [];
let isOk;
for (let offset = 0; !isOk; offset = offset + config.limit) {
const pois = await axios.get(`${config.url}pois/search?limit=${config.limit}&offset=${offset}`, {
headers: {
'Accept': 'application/json',
'X-Saas-Apikey': config.key
}
});
pois.data.data.length ? poisData.push(...pois.data.data) : isOk = true;
}
const poiMap = new Map(poisData.map(poi => [poi.code, poi._id]));
let orders = await Self.rawSql(`
SELECT a.id poiCode,
t.id code,
t.shipped date,
'PEDIDO' operation,
t.totalWithVat totalAmount,
t.totalWithoutVat totalAmountWithoutTaxes,
SUM(sv.volume) volume
FROM ticket t
JOIN address a ON a.id = t.addressFk
JOIN saleVolume sv ON sv.ticketFk = t.id
WHERE t.id IN (?)
GROUP BY t.id
`, [tickets]);
// Transformo code en string ya que lo obtenermos como integer
orders = orders.map(order => {
return {
...order,
poiId: poiMap.get(order.poiCode.toString()) || undefined,
code: order.code.toString(),
date: moment(order.date).format('YYYY-MM-DD'),
totalAmount: order.totalAmount || undefined,
totalAmountWithoutTaxes: order.totalAmountWithoutTaxes || undefined,
timeWindow: [{
from: config.orderTimeFrom,
to: config.orderTimeTo
}],
orderMeasures: [{
constraintId: 3, // Volumen
value: order.volume
}]
};
});
await axios.post(`${config.url}orders`, orders, {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-Saas-Apikey': config.key
}
});
};
};

View File

@ -1,87 +0,0 @@
const axios = require('axios');
const UserError = require('vn-loopback/util/user-error');
module.exports = Self => {
Self.remoteMethod('sendPois', {
description: 'Sends a set of pois',
accessType: 'WRITE',
accepts: [{
arg: 'tickets',
type: ['number'],
required: true
}
],
returns: {
type: 'string',
root: true
},
http: {
path: `/sendPois`,
verb: 'POST'
}
});
Self.sendPois = async tickets => {
const config = await Self.app.models.QuadmindsApiConfig.findOne();
if (!config) throw new UserError('Config params not set');
if (tickets.length > config.maxObjects)
throw new UserError(`Quadminds does not support more than ${config.maxObjects} tickets`);
let pois = await Self.rawSql(`
WITH deliveryNotes AS (
SELECT t.id, t.routeFk, tn.description
FROM ticket t
JOIN ticketObservation tn ON tn.ticketFk = t.id
JOIN observationType ot ON ot.id = tn.observationTypeFk
WHERE ot.code = 'delivery'
)
SELECT a.id code,
c.socialName name,
IF(ABS(a.latitude - ROUND(a.latitude)) < 0.000001, NULL, a.latitude) latitude,
IF(ABS(a.longitude - ROUND(a.longitude)) < 0.000001, NULL, a.longitude) longitude,
a.street,
a.city locality,
p.name state,
co.name country,
CONCAT_WS(', ', IFNULL(a.street, ''), IFNULL(a.city, ''), IFNULL(p.name, '')) longAddress,
CONCAT(IFNULL(a.mobile, c.mobile)) phoneNumber,
dn.description poiDeliveryComments,
c.email email
FROM ticket t
JOIN address a ON a.id = t.addressFk
JOIN province p ON p.id = a.provinceFk
JOIN country co ON co.id = p.countryFk
JOIN client c ON c.id = t.clientFk
LEFT JOIN deliveryNotes dn ON dn.id = t.id
WHERE t.id IN (?)
GROUP BY t.id
`, [tickets]);
// Transformo code en string ya que lo obtenermos como integer
pois = pois.map(poi => {
return {
...poi,
code: poi.code.toString(),
latitude: poi.latitude || undefined,
longitude: poi.longitude || undefined,
address: {
street: poi.street || undefined,
locality: poi.locality || undefined,
state: poi.state || undefined,
country: poi.country || undefined
},
poiDeliveryComments: poi.poiDeliveryComments || undefined,
phoneNumber: poi.phoneNumber || undefined,
email: poi.email || undefined
};
});
await axios.post(`${config.url}pois`, pois, {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-Saas-Apikey': config.key
}
});
};
};

View File

@ -1,7 +1,22 @@
const {models} = require('vn-loopback/server/server');
const LoopBackContext = require('loopback-context');
describe('getStarredModules()', () => {
const ctx = beforeAll.getCtx();
const activeCtx = {
accessToken: {userId: 9},
http: {
req: {
headers: {origin: 'http://localhost'}
}
}
};
const ctx = {req: activeCtx};
beforeEach(() => {
spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({
active: activeCtx
});
});
it(`should return the starred modules for a given user`, async() => {
const newStarred = await models.StarredModule.create({workerFk: 9, moduleFk: 'customer', position: 1});

View File

@ -1,8 +1,24 @@
const {models} = require('vn-loopback/server/server');
const LoopBackContext = require('loopback-context');
describe('setPosition()', () => {
const ctx = beforeAll.getCtx();
beforeAll.mockLoopBackContext();
const activeCtx = {
accessToken: {userId: 9},
http: {
req: {
headers: {origin: 'http://localhost'}
}
}
};
const ctx = {
req: activeCtx
};
beforeEach(() => {
spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({
active: activeCtx
});
});
it('should increase the orders module position by replacing it with clients and vice versa', async() => {
const tx = await models.StarredModule.beginTransaction({});

View File

@ -1,7 +1,24 @@
const {models} = require('vn-loopback/server/server');
const LoopBackContext = require('loopback-context');
describe('toggleStarredModule()', () => {
const ctx = beforeAll.getCtx();
const activeCtx = {
accessToken: {userId: 9},
http: {
req: {
headers: {origin: 'http://localhost'}
}
}
};
const ctx = {
req: activeCtx
};
beforeEach(() => {
spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({
active: activeCtx
});
});
it('should create a new starred module and then remove it by calling the method again with same args', async() => {
const starredModule = await models.StarredModule.toggleStarredModule(ctx, 'order');
@ -9,7 +26,7 @@ describe('toggleStarredModule()', () => {
expect(starredModules.length).toEqual(1);
expect(starredModule.moduleFk).toEqual('order');
expect(starredModule.workerFk).toEqual(ctx.req.accessToken.userId);
expect(starredModule.workerFk).toEqual(activeCtx.accessToken.userId);
expect(starredModule.position).toEqual(starredModules.length);
await models.StarredModule.toggleStarredModule(ctx, 'order');

View File

@ -22,7 +22,7 @@ module.exports = Self => {
const url = await Self.app.models.Url.findOne({
where: {
appName,
environment: process.env.NODE_ENV || 'dev'
environment: process.env.NODE_ENV || 'development'
}
});
return url?.url;

View File

@ -1,12 +1,12 @@
const models = require('vn-loopback/server/server').models;
describe('userConfig getUserConfig()', () => {
const ctx = beforeAll.getCtx();
it(`should return the configuration data of a given user`, async() => {
const tx = await models.Item.beginTransaction({});
const options = {transaction: tx};
try {
const ctx = {req: {accessToken: {userId: 9}}};
const result = await models.UserConfig.getUserConfig(ctx, options);
expect(result.warehouseFk).toEqual(1);

View File

@ -20,7 +20,7 @@ module.exports = Self => {
}
});
Self.renderer = async expeditionFk => {
Self.renderer = async (expeditionFk) => {
const models = Self.app.models;
const viaexpressConfig = await models.ViaexpressConfig.findOne({
@ -109,7 +109,7 @@ module.exports = Self => {
const ticket = expedition.ticket();
const sender = ticket.company().client();
const shipped = ticket.shipped.toISOString();
const isInterdia = (ticket.agencyModeFk === viaexpressConfig.agencyModeFk);
const isInterdia = (ticket.agencyModeFk === viaexpressConfig.agencyModeFk)
const data = {
viaexpressConfig,
sender,

View File

@ -1,29 +0,0 @@
module.exports = Self => {
Self.remoteMethodCtx('killSession', {
description: 'Kill session',
accepts: [{
arg: 'userId',
type: 'integer',
description: 'The user id',
required: true,
}, {
arg: 'created',
type: 'date',
description: 'The created time',
required: true,
}],
accessType: 'WRITE',
http: {
path: `/killSession`,
verb: 'POST'
}
});
Self.killSession = async function(ctx, userId, created) {
await Self.app.models.VnUser.userSecurity(ctx, ctx.req.accessToken.userId);
const tokens = await Self.app.models.AccessToken.find({where: {userId, created}});
if (!tokens?.length) return;
for (const token of tokens)
await Self.app.models.AccessToken.deleteById(token.id);
};
};

View File

@ -1,72 +0,0 @@
module.exports = Self => {
Self.remoteMethodCtx('acls', {
description: 'Get all of the current user acls',
returns: {
type: 'Object',
root: true
},
http: {
path: '/acls',
verb: 'GET'
}
});
const staticAcls = new Map();
const app = require('vn-loopback/server/server');
app.on('started', function() {
for (const model of app.models()) {
for (const acl of model.settings.acls) {
if (acl.principalType == 'ROLE' && acl.permission == 'ALLOW') {
const staticAcl = {
model: model.name,
property: '*',
accessType: acl.accessType,
permission: acl.permission,
principalType: acl.principalType,
principalId: acl.principalId,
};
if (staticAcls.has(acl.principalId))
staticAcls.get(acl.principalId).push(staticAcl);
else
staticAcls.set(acl.principalId, [staticAcl]);
}
}
}
});
Self.acls = async function(ctx) {
const models = Self.app.models;
const acls = [];
const userId = ctx.req.accessToken.userId;
if (userId) {
const roleMapping = await models.RoleMapping.find({
where: {
principalId: userId
},
include: [
{
relation: 'role',
scope: {
fields: [
'name'
]
}
}
]
});
const dynamicAcls = await models.ACL.find({
where: {
principalId: {
inq: roleMapping.map(rm => rm.role().name)
}
}
});
dynamicAcls.forEach(acl => acls.push(acl));
staticAcls.get('$authenticated').forEach(acl => acls.push(acl));
} else
staticAcls.get('$unauthenticated').forEach(acl => acls.push(acl));
staticAcls.get('$everyone').forEach(acl => acls.push(acl));
return acls;
};
};

View File

@ -16,51 +16,36 @@ module.exports = Self => {
accessScopes: ['DEFAULT', 'read:multimedia']});
Self.renewToken = async function(ctx) {
const {accessToken: token} = ctx.req;
const {courtesyTime} = await models.AccessTokenConfig.findOne({
fields: ['courtesyTime']
});
const isNotExceeded = await Self.validateToken(ctx);
if (isNotExceeded)
return token;
// Schedule to remove current token
setTimeout(async() => {
try {
const exists = await models.AccessToken.findById(token.id);
exists && await Self.logout(token.id);
} catch (err) {
// eslint-disable-next-line no-console
console.error(err);
}
}, courtesyTime * 1000);
// Get scopes
let createTokenOptions = {};
let token; let isNotExceeded;
try {
token = ctx.req.accessToken;
const {scopes} = token;
if (scopes)
createTokenOptions = {scopes: [scopes[0]]};
// Create new accessToken
const user = await Self.findById(token.userId);
const accessToken = await user.accessTokens.create(createTokenOptions);
const {courtesyTime} = await models.AccessTokenConfig.findOne({
fields: ['courtesyTime']
});
isNotExceeded = await Self.validateToken(ctx);
if (isNotExceeded)
return token;
// Schedule to remove current token
setTimeout(async() => {
try {
await Self.logout(token.id);
} catch (error) {
// FIXME: Crash if do throw new Error(error)
}
}, courtesyTime * 1000);
// Get scopes
const {scopes} = token;
if (scopes)
createTokenOptions = {scopes: [scopes[0]]};
// Create new accessToken
const user = await Self.findById(token.userId);
const accessToken = await user.accessTokens.create(createTokenOptions);
return {id: accessToken.id, ttl: accessToken.ttl};
} catch (error) {
const body = {
error: error.message,
userId: token?.userId ?? null,
token: token?.id,
scopes: token?.scopes,
createTokenOptions,
isNotExceeded
};
await handleError(JSON.stringify(body));
throw new Error(error);
}
return {id: accessToken.id, ttl: accessToken.ttl};
};
};
async function handleError(body) {
await models.Application.rawSql('CALL util.debugAdd(?,?);', ['renewToken', body]);
}

View File

@ -67,9 +67,7 @@ module.exports = Self => {
if (vnUser.twoFactor === 'email') {
const $ = Self.app.models;
const min = 100000;
const max = 999999;
const code = String(Math.floor(Math.random() * (max - min + 1)) + min);
const code = String(Math.floor(Math.random() * 999999));
const maxTTL = ((60 * 1000) * 5); // 5 min
await $.AuthCode.upsertWithWhere({userFk: vnUser.id}, {
userFk: vnUser.id,

View File

@ -1,27 +0,0 @@
const {models} = require('vn-loopback/server/server');
const id = {administrative: 5, employee: 1, productionBoss: 50};
describe('VnUser acls()', () => {
it('should get its owns acls', async() => {
expect(await hasAcl('administrative', id.administrative)).toBeTruthy();
expect(await hasAcl('productionBoss', id.productionBoss)).toBeTruthy();
});
it('should not get administrative acls', async() => {
expect(await hasAcl('administrative', id.employee)).toBeFalsy();
});
it('should get the $authenticated acls', async() => {
expect(await hasAcl('$authenticated', id.employee)).toBeTruthy();
});
it('should get the $everyone acls', async() => {
expect(await hasAcl('$everyone', id.employee)).toBeTruthy();
});
});
const hasAcl = async(role, userId) => {
const ctx = {req: {accessToken: {userId}, headers: {origin: 'http://localhost'}}};
const acls = await models.VnUser.acls(ctx);
return Object.values(acls).some(acl => acl.principalId === role);
};

View File

@ -61,21 +61,4 @@ describe('Renew Token', () => {
expect(error).toBeUndefined();
expect(response.id).toEqual(ctx.req.accessToken.id);
});
it('throw error', async() => {
let error;
try {
await models.VnUser.renewToken({req: {token: null}});
} catch (e) {
error = e;
}
expect(error).toBeDefined();
const query = 'SELECT * FROM util.debug WHERE variable = "renewToken"';
const debugLog = await models.Application.rawSql(query);
expect(debugLog.length).toEqual(1);
});
});

View File

@ -24,10 +24,6 @@ module.exports = Self => {
arg: 'lang',
type: 'string',
description: 'The user lang'
}, {
arg: 'twoFactor',
type: 'any',
description: 'The user twoFactor'
}
],
http: {
@ -36,8 +32,8 @@ module.exports = Self => {
}
});
Self.updateUser = async(ctx, id, name, nickname, email, lang, twoFactor) => {
Self.updateUser = async(ctx, id, name, nickname, email, lang) => {
await Self.userSecurity(ctx, id);
await Self.upsertWithWhere({id}, {name, nickname, email, lang, twoFactor});
await Self.upsertWithWhere({id}, {name, nickname, email, lang});
};
};

View File

@ -58,7 +58,7 @@ module.exports = Self => {
fields: ['name', 'twoFactor']
}, myOptions);
if (user.name.toLowerCase() !== username.toLowerCase())
if (user.name !== username)
throw new UserError('Authentication failed');
await authCode.destroy(myOptions);

View File

@ -1,50 +0,0 @@
module.exports = Self => {
Self.remoteMethodCtx('add', {
description: 'Add activity if the activity is different or is the same but have exceed time for break',
accessType: 'WRITE',
accepts: [
{
arg: 'code',
type: 'string',
description: 'Code for activity'
},
{
arg: 'model',
type: 'string',
description: 'Origin model from insert'
},
],
http: {
path: `/add`,
verb: 'POST'
}
});
Self.add = async(ctx, code, model, options) => {
const userId = ctx.req.accessToken.userId;
const myOptions = {};
if (typeof options == 'object')
Object.assign(myOptions, options);
return await Self.rawSql(`
INSERT INTO workerActivity (workerFk, workerActivityTypeFk, model)
SELECT ?, ?, ?
FROM workerTimeControlConfig wtcc
LEFT JOIN (
SELECT wa.workerFk,
wa.created,
wat.code
FROM workerActivity wa
LEFT JOIN workerActivityType wat ON wat.code = wa.workerActivityTypeFk
WHERE wa.workerFk = ?
ORDER BY wa.created DESC
LIMIT 1
) sub ON TRUE
WHERE sub.workerFk IS NULL
OR sub.code <> ?
OR TIMESTAMPDIFF(SECOND, sub.created, util.VN_NOW()) > wtcc.dayBreak;`
, [userId, code, model, userId, code], myOptions);
};
};

View File

@ -1,30 +0,0 @@
const {models} = require('vn-loopback');
describe('workerActivity insert()', () => {
const ctx = beforeAll.getCtx(1106);
it('should insert in workerActivity', async() => {
const tx = await models.WorkerActivity.beginTransaction({});
let count = 0;
const options = {transaction: tx};
try {
await models.WorkerActivityType.create(
{'code': 'STOP', 'description': 'STOP'}, options
);
await models.WorkerActivity.add(ctx, 'STOP', 'APP', options);
count = await models.WorkerActivity.count(
{'workerFK': 1106}, options
);
await tx.rollback();
} catch (e) {
await tx.rollback();
throw e;
}
expect(count).toEqual(1);
});
});

View File

@ -28,9 +28,6 @@
"Company": {
"dataSource": "vn"
},
"Config": {
"dataSource": "vn"
},
"Continent": {
"dataSource": "vn"
},
@ -67,9 +64,6 @@
"EmailUser": {
"dataSource": "vn"
},
"Expedition_PrintOut": {
"dataSource": "vn"
},
"Image": {
"dataSource": "vn"
},
@ -79,9 +73,6 @@
"ImageCollectionSize": {
"dataSource": "vn"
},
"ImageConfig": {
"dataSource": "vn"
},
"ImageContainer": {
"dataSource": "imageStorage"
},
@ -91,6 +82,12 @@
"Machine": {
"dataSource": "vn"
},
"MachineWorker": {
"dataSource": "vn"
},
"MachineWorkerConfig": {
"dataSource": "vn"
},
"MobileAppVersionControl": {
"dataSource": "vn"
},
@ -115,15 +112,9 @@
"NotificationSubscription": {
"dataSource": "vn"
},
"OrmConfig": {
"dataSource": "vn"
},
"Province": {
"dataSource": "vn"
},
"QuadmindsApiConfig": {
"dataSource": "vn"
},
"Autonomy": {
"dataSource": "vn"
},
@ -142,12 +133,6 @@
"StarredModule": {
"dataSource": "vn"
},
"SaySimpleCountry": {
"dataSource": "vn"
},
"SaySimpleConfig": {
"dataSource": "vn"
},
"TempContainer": {
"dataSource": "tempStorage"
},
@ -178,15 +163,9 @@
"PrintConfig": {
"dataSource": "vn"
},
"QueueMember": {
"dataSource": "vn"
},
"ViaexpressConfig": {
"dataSource": "vn"
},
"VnToken": {
"dataSource": "vn"
},
"VnUser": {
"dataSource": "vn"
},
@ -210,8 +189,5 @@
},
"RouteConfig": {
"dataSource": "vn"
},
"MrwService": {
"dataSource": "vn"
}
}
}

View File

@ -16,10 +16,6 @@
"name": {
"type": "string",
"required": true
},
"hasDailyInvoice": {
"type": "boolean",
"description": "Indicates if the autonomy has daily invoice enabled"
}
},
"relations": {
@ -44,4 +40,4 @@
"permission": "ALLOW"
}
]
}
}

View File

@ -3,7 +3,6 @@ module.exports = Self => {
require('../methods/collection/setSaleQuantity')(Self);
require('../methods/collection/previousLabel')(Self);
require('../methods/collection/getTickets')(Self);
require('../methods/collection/assignCollection')(Self);
require('../methods/collection/assign')(Self);
require('../methods/collection/getSales')(Self);
};

View File

@ -1,16 +1,6 @@
{
"name": "Collection",
"base": "VnModel",
"properties": {
"id": {
"id": true,
"type": "number",
"required": true
},
"workerFk": {
"type": "number"
}
},
"options": {
"mysql": {
"table": "collection"

View File

@ -1,22 +0,0 @@
{
"name": "Config",
"base": "VnModel",
"options": {
"mysql": {
"table": "config"
}
},
"properties": {
"inventoried": {
"type": "date"
}
},
"acls": [
{
"accessType": "READ",
"principalType": "ROLE",
"principalId": "$authenticated",
"permission": "ALLOW"
}
]
}

View File

@ -25,13 +25,6 @@
},
"isSocialNameUnique": {
"type": "boolean"
},
"continentFk": {
"type": "number"
},
"hasDailyInvoice": {
"type": "boolean",
"description": "Indicates if the autonomy has daily invoice enabled"
}
},
"relations": {
@ -39,16 +32,6 @@
"type": "belongsTo",
"model": "Currency",
"foreignKey": "currencyFk"
},
"continent": {
"type": "belongsTo",
"model": "Continent",
"foreignKey": "continentFk"
},
"saySimpleCountry": {
"type": "hasOne",
"model": "SaySimpleCountry",
"foreignKey": "countryFk"
}
},
"acls": [
@ -59,4 +42,4 @@
"permission": "ALLOW"
}
]
}
}

View File

@ -3,7 +3,7 @@
"base": "VnModel",
"options": {
"mysql": {
"table": "salix.defaultViewMultiConfig"
"table": "salix.defaultViewConfig"
}
},
"properties": {

View File

@ -16,17 +16,17 @@
"url": {
"type": "string"
},
"token": {
"cookie": {
"type": "string"
},
"username": {
"type": "string"
},
"password": {
"type": "string"
},
"expired":{
"type": "number"
}
}
},
"acls": [
{
"property": "*",
"accessType": "*",
"principalType": "ROLE",
"principalId": "$everyone",
"permission": "ALLOW"
}
]
}

View File

@ -1,19 +0,0 @@
{
"name": "Expedition_PrintOut",
"base": "VnModel",
"options": {
"mysql": {
"table": "dipole.expedition_PrintOut"
}
},
"properties": {
"expeditionFk": {
"type": "number",
"id": true,
"description": "id expeditionFk"
},
"itemFk": {
"type": "number"
}
}
}

View File

@ -1,22 +0,0 @@
{
"name": "ImageConfig",
"base": "VnModel",
"options": {
"mysql": {
"table": "hedera.imageConfig"
}
},
"properties": {
"url": {
"type": "string"
}
},
"acls": [
{
"accessType": "READ",
"principalType": "ROLE",
"principalId": "$authenticated",
"permission": "ALLOW"
}
]
}

View File

@ -0,0 +1,18 @@
{
"name": "MachineWorkerConfig",
"base": "VnModel",
"options": {
"mysql": {
"table": "vn.machineWorkerConfig"
}
},
"properties": {
"id": {
"type": "number",
"id": true
},
"maxHours": {
"type": "number"
}
}
}

View File

@ -0,0 +1,3 @@
module.exports = Self => {
require('../methods/machine-worker/updateInTime')(Self);
};

View File

@ -0,0 +1,33 @@
{
"name": "MachineWorker",
"base": "VnModel",
"options": {
"mysql": {
"table": "vn.machineWorker"
}
},
"properties": {
"id": {
"type": "number",
"id": true
},
"workerFk": {
"type": "number"
},
"machineFk": {
"type": "number"
},
"inTime": {
"type": "date",
"mysql": {
"columnName": "inTimed"
}
},
"outTime": {
"type": "date",
"mysql": {
"columnName": "outTimed"
}
}
}
}

View File

@ -1,60 +1,4 @@
module.exports = Self => {
require('../methods/mrw-config/createShipment')(Self);
require('../methods/mrw-config/getLabel')(Self);
require('../methods/mrw-config/cancelShipment')(Self);
const fs = require('fs');
const ejs = require('ejs');
const UserError = require('vn-loopback/util/user-error');
const {DOMParser} = require('xmldom');
const axios = require('axios');
Self.getConfig = async function() {
const mrw = await Self.app.models.MrwConfig.findOne(null);
if (!mrw) throw new UserError(`MRW service is not configured`);
return mrw;
};
Self.getTextByTag = function(xmlDoc, tag) {
return xmlDoc?.getElementsByTagName(tag)[0]?.textContent;
};
Self.sendXmlDoc = async function(path, params, contentType) {
const parser = new DOMParser();
const xmlTemplate = fs.readFileSync(path, 'utf-8');
const renderedTemplate = ejs.render(xmlTemplate, params);
const data = await axios.post(params.mrw.url, renderedTemplate, {
headers: {
'Content-Type': `${contentType}; charset=utf-8`
}
});
return parser.parseFromString(data.data, 'text/xml');
};
Self.getClientType = async function(expeditionFk) {
if (!expeditionFk) throw new UserError(`No expeditionFk defined`);
const {clientTypeWidth} = await Self.getConfig();
const result = await Self.app.models.Expedition.findById(expeditionFk,
{include: [{
relation: 'ticket',
scope: {
include: {
relation: 'agencyMode',
scope: {
include: {
relation: 'mrwService',
}
}
}
}
}]}
);
const clientType = result?.ticket()?.agencyMode()?.mrwService()?.clientType;
if (!clientType || !clientTypeWidth) throw new UserError(`ClientType not available`);
return clientType.toString().padStart(clientTypeWidth, '0');
};
};

View File

@ -27,27 +27,6 @@
},
"subscriberCode": {
"type": "string"
},
"defaultHeight": {
"type": "number"
},
"defaultLength": {
"type": "number"
},
"defaultWidth": {
"type": "number"
},
"defaultWeight": {
"type": "number"
},
"expeditionDeadLine": {
"type": "string"
},
"notified":{
"type": "date"
},
"clientTypeWidth": {
"type": "number"
}
}
}

View File

@ -1,33 +0,0 @@
{
"name": "MrwService",
"base": "VnModel",
"options": {
"mysql": {
"table": "mrwService"
}
},
"properties": {
"agencyModeCodeFk": {
"id": true,
"type": "string",
"required": true
},
"clientType": {
"type": "number",
"required": true
},
"serviceType": {
"type": "number"
},
"kg": {
"type": "number"
}
},
"relations": {
"agency": {
"type": "hasOne",
"model": "AgencyMode",
"foreignKey": "code"
}
}
}

View File

@ -1,26 +0,0 @@
{
"name": "OrmConfig",
"base": "VnModel",
"options": {
"mysql": {
"table": "ormConfig"
}
},
"properties": {
"id": {
"type": "number",
"id": true
},
"selectLimit": {
"type": "number"
}
},
"acls": [
{
"accessType": "*",
"principalType": "ROLE",
"principalId": "$authenticated",
"permission": "ALLOW"
}
]
}

View File

@ -9,8 +9,7 @@
"properties": {
"code": {
"id": true,
"type": "string",
"required": true
"type": "string"
}
},
"relations": {
@ -48,4 +47,4 @@
}
}
}
}
}

View File

@ -3,23 +3,17 @@
"base": "VnModel",
"options": {
"mysql": {
"table": "productionConfig"
"table": "productionConfig"
}
},
},
"properties": {
"id": {
"type": "number",
"required": true,
"id": true
},
"sectorFromCode": {
"type": "string"
},
"sectorToCode": {
"type": "string"
},
"backupPrinterNotificationDelay": {
"type": "string"
}
}
}
}

View File

@ -16,9 +16,6 @@
"name": {
"type": "string",
"required": true
},
"autonomyFk": {
"type": "number"
}
},
"relations": {
@ -58,4 +55,4 @@
"permission": "ALLOW"
}
]
}
}

View File

@ -1,4 +0,0 @@
module.exports = Self => {
require('../methods/quadminds-api-config/sendPois')(Self);
require('../methods/quadminds-api-config/sendOrders')(Self);
};

View File

@ -1,34 +0,0 @@
{
"name": "QuadmindsApiConfig",
"base": "VnModel",
"options": {
"mysql": {
"table": "quadmindsApiConfig"
}
},
"properties": {
"id": {
"type": "number",
"id": true,
"required": true
},
"url": {
"type": "string"
},
"key": {
"type": "string"
},
"maxObjects": {
"type": "number"
},
"limit": {
"type": "number"
},
"orderTimeFrom": {
"type": "string"
},
"orderTimeTo": {
"type": "string"
}
}
}

View File

@ -1,38 +0,0 @@
{
"name": "QueueMember",
"base": "VnModel",
"options": {
"mysql": {
"table": "pbx.queueMember"
}
},
"properties": {
"id": {
"type": "number",
"id": true
},
"queue": {
"type": "string"
},
"extension": {
"type": "string"
}
},
"relations": {
"queueRelation": {
"type": "belongsTo",
"model": "Queue",
"foreignKey": "queue",
"primaryKey": "name"
}
},
"acls": [
{
"property": "*",
"accessType": "READ",
"principalType": "ROLE",
"principalId": "employee",
"permission": "ALLOW"
}
]
}

View File

@ -1,29 +0,0 @@
{
"name": "SaySimpleConfig",
"base": "VnModel",
"options": {
"mysql": {
"table": "saySimpleConfig"
}
},
"properties": {
"id": {
"type": "number",
"id": true
},
"url": {
"type": "string"
},
"defaultChannel": {
"type": "number"
}
},
"acls": [
{
"accessType": "READ",
"principalType": "ROLE",
"principalId": "$authenticated",
"permission": "ALLOW"
}
]
}

View File

@ -1,26 +0,0 @@
{
"name": "SaySimpleCountry",
"base": "VnModel",
"options": {
"mysql": {
"table": "saySimpleCountry"
}
},
"properties": {
"countryFk": {
"type": "number",
"id": true
},
"channel": {
"type": "number"
}
},
"acls": [
{
"accessType": "READ",
"principalType": "ROLE",
"principalId": "$authenticated",
"permission": "ALLOW"
}
]
}

View File

@ -1,13 +1,12 @@
const models = require('vn-loopback/server/server').models;
describe('loopback model MailAliasAccount', () => {
const ctx = beforeAll.getCtx();
it('should add a mail Alias', async() => {
const tx = await models.MailAliasAccount.beginTransaction({});
let error;
try {
const options = {transaction: tx, ctx};
const options = {transaction: tx, accessToken: {userId: 9}};
await models.MailAliasAccount.create({mailAlias: 2, account: 5}, options);
await tx.rollback();
@ -24,7 +23,7 @@ describe('loopback model MailAliasAccount', () => {
let error;
try {
const options = {transaction: tx, ctx};
const options = {transaction: tx, accessToken: {userId: 9}};
await models.MailAliasAccount.create({mailAlias: 3, account: 5}, options);
await tx.rollback();

View File

@ -12,8 +12,7 @@
"type": "number"
},
"name": {
"type": "string",
"required": true
"type": "string"
}
},
"relations": {
@ -55,4 +54,4 @@
"fields": ["id", "name", "provinceFk"]
}
}
}
}

View File

@ -3,7 +3,7 @@
"base": "VnModel",
"options": {
"mysql": {
"table": "userMultiConfig"
"table": "userConfig"
}
},
"properties": {

View File

@ -1,5 +0,0 @@
const vnModel = require('vn-loopback/common/models/vn-model');
module.exports = function(Self) {
vnModel(Self);
require('../methods/vn-token/killSession')(Self);
};

View File

@ -1,22 +0,0 @@
{
"name": "VnToken",
"base": "AccessToken",
"options": {
"mysql": {
"table": "salix.AccessToken"
}
},
"properties": {
"created": {
"type": "date"
}
},
"relations": {
"user": {
"type": "belongsTo",
"model": "VnUser",
"foreignKey": "userId"
}
},
"hidden": ["id"]
}

View File

@ -16,7 +16,6 @@ module.exports = function(Self) {
require('../methods/vn-user/share-token')(Self);
require('../methods/vn-user/update-user')(Self);
require('../methods/vn-user/validate-token')(Self);
require('../methods/vn-user/acls')(Self);
Self.definition.settings.acls = Self.definition.settings.acls.filter(acl => acl.property !== 'create');
@ -101,10 +100,9 @@ module.exports = function(Self) {
const headers = httpRequest.headers;
const origin = headers.origin;
const defaultHash = '!/reset-password?access_token=$token$';
const defaultHash = '/reset-password?access_token=$token$';
const recoverHashes = {
hedera: '!verificationToken=$token$',
lilium: '/resetPassword?access_token=$token$'
hedera: 'verificationToken=$token$'
};
const app = info.options?.app;
@ -116,7 +114,7 @@ module.exports = function(Self) {
const params = {
recipient: info.email,
lang: user.lang,
url: origin + '/#' + recoverHash
url: origin + '/#!' + recoverHash
};
const options = Object.assign({}, info.options);

View File

@ -140,13 +140,6 @@
"principalType": "ROLE",
"principalId": "$authenticated",
"permission": "ALLOW"
},
{
"property": "acls",
"accessType": "*",
"principalType": "ROLE",
"principalId": "$everyone",
"permission": "ALLOW"
}
],
"scopes": {
@ -165,8 +158,7 @@
"hasGrant",
"realm",
"email",
"emailVerified",
"twoFactor"
"emailVerified"
]
}
}

View File

@ -24,20 +24,9 @@
},
"isManaged": {
"type": "boolean"
},
"isDestiny": {
"type": "boolean"
},
"countryFk": {
"type": "number"
}
},
"relations": {
"country": {
"type": "belongsTo",
"model": "Country",
"foreignKey": "countryFk"
},
"address": {
"type": "belongsTo",
"model": "Address",
@ -59,4 +48,4 @@
}
}
}
}
}

View File

@ -1,3 +0,0 @@
module.exports = Self => {
require('../methods/workerActivity/add')(Self);
};

View File

@ -22,18 +22,18 @@
},
"description": {
"type": "string"
}
},
"relations": {
"workerFk": {
"type": "belongsTo",
"model": "Worker",
"foreignKey": "workerFk"
},
"workerActivityTypeFk": {
"type": "belongsTo",
"model": "WorkerActivityType",
"foreignKey": "workerActivityTypeFk"
"relations": {
"workerFk": {
"type": "belongsTo",
"model": "Worker",
"foreignKey": "workerFk"
},
"workerActivityTypeFk": {
"type": "belongsTo",
"model": "WorkerActivityType",
"foreignKey": "workerActivityTypeFk"
}
}
}
}

View File

@ -22,4 +22,4 @@
"modules/worker/front/**/*",
"modules/zone/front/**/*"
]
}
}

7
back/process.yml Normal file
View File

@ -0,0 +1,7 @@
apps:
- script: ./loopback/server/server.js
name: salix-back
instances: 1
max_restarts: 3
restart_delay: 15000
node_args: --tls-min-v1.0 --openssl-legacy-provider

View File

@ -10,13 +10,13 @@ async function init() {
host: process.env.DB_HOST,
port: process.env.DB_PORT
});
const bootOptions = {dataSources};
await new Promise((resolve, reject) => {
app.boot(bootOptions,
err => err ? reject(err) : resolve());
});
// FIXME: Workaround to wait for loopback to be ready
app.emit('started');
await app.models.Application.status();
}
@ -32,4 +32,3 @@ module.exports = {
if (require.main === module)
init();

View File

@ -84,7 +84,7 @@ async function test() {
'loopback/**/*[sS]pec.js',
'modules/*/back/**/*.[sS]pec.js'
],
helpers: [`back/vn-jasmine.js`],
helpers: []
};
if (PARALLEL) {
@ -114,6 +114,7 @@ async function test() {
if (opts.ci)
runner.jasmine.DEFAULT_TIMEOUT_INTERVAL = SPEC_TIMEOUT;
// runner.loadConfigFile('back/jasmine.json');
runner.loadConfig(config);
process.env.SPEC_IS_RUNNING = true;
await runner.execute();

View File

@ -1,48 +0,0 @@
const LoopBackContext = require('loopback-context');
const getAccessToken = (userId = 9) => {
return {accessToken: {userId}};
};
const DEFAULT_HEADERS = {headers: {origin: 'http://localhost'}};
const default_before_all = userId => {
return {
req: {
...getAccessToken(userId),
...DEFAULT_HEADERS,
...{__: value => value}
},
args: {}
};
};
const default_loopback_ctx = userId => {
return {
...getAccessToken(userId),
...default_before_all(userId),
http: {
...default_before_all(userId)
},
args: {}
};
};
function vnBeforeAll() {
Object.assign(beforeAll, {getCtx: default_before_all, mockLoopBackContext});
}
const mockLoopBackContext = userId => {
const activeCtx = default_loopback_ctx(userId);
beforeAll(() => {
spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({
active: activeCtx
});
});
return activeCtx;
};
module.exports = {
mockLoopBackContext
};
(function init() {
vnBeforeAll();
})();

View File

@ -9,7 +9,7 @@
},
"vn": {
"view": {
"expeditionPallet_Print": "99f75145ac2e7b612a6d71e74b6e55f194a465780fd9875a15eb01e6596b447e"
"expeditionPallet_Print": "06613719475fcdba8309607c38cc78efc2e348cca7bc96b48dc3ae3c12426f54"
}
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1,14 +1 @@
-- Executed before dump
CREATE USER 'vn'@'localhost';
GRANT SELECT,
INSERT,
UPDATE,
DELETE,
DROP,
CREATE TEMPORARY TABLES,
EXECUTE,
EVENT,
TRIGGER
ON *.* TO 'vn'@'localhost';

View File

@ -10,6 +10,9 @@ SET foreign_key_checks = 0;
INSERT INTO util.config (id, environment, mockTime, mockUtcTime, mockEnabled)
VALUES (1, 'local', '2001-01-01 12:00:00', '2001-01-01 11:00:00', TRUE);
INSERT INTO util.binlogQueue (code,logName, `position`)
VALUES ('mylogger', 'bin.000001', 4);
/* #5483
INSERT INTO vn.entryConfig (defaultEntry, mailToNotify, inventorySupplierFk, maxLockTime, defaultSupplierFk)
VALUES(1, NULL, 1, 300, 1);
@ -126,7 +129,7 @@ INSERT INTO vn.itemShelving (id,itemFk,visible,shelvingFk,`grouping`,packing,pac
INSERT INTO vn.beach (code,warehouseFk) VALUES
('TEST',1);
INSERT INTO vn.routesMonitor (routeFk,name,beachFk,m3,roadmapStopFk) VALUES
INSERT INTO vn.routesMonitor (routeFk,name,beachFk,m3,expeditionTruckFk) VALUES
(1,'TEST','TEST',1.0,1);
/* #5483
INSERT INTO vn.ticket (clientFk, warehouseFk, shipped, nickname, refFk, addressFk, workerFk, observations, isSigned, isLabeled, isPrinted, packages, location, `hour`, created, isBlocked, solution, routeFk, priority, hasPriority, companyFk, agencyModeFk, landed, isBoxed, isDeleted, zoneFk, zonePrice, zoneBonus, totalWithVat, totalWithoutVat, weight)
@ -311,4 +314,5 @@ INSERT INTO mysql.roles_mapping (`User`, `Host`, `Role`, `Admin_option`)
SELECT SUBSTR(`User`, @prefixLen + 1), `Host`, `Role`, `Admin_option`
FROM mysql.roles_mapping
WHERE `User` LIKE @prefixedLike AND `Host` = @genRoleHost;
FLUSH PRIVILEGES;

File diff suppressed because it is too large Load Diff

View File

@ -1,12 +0,0 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `account`.`mailAliasAccount_afterDelete`
AFTER DELETE ON `mailAliasAccount`
FOR EACH ROW
BEGIN
INSERT INTO userLog
SET `action` = 'delete',
`changedModel` = 'MailAliasAccount',
`changedModelId` = OLD.id,
`userFk` = account.myUser_getId();
END$$
DELIMITER ;

View File

@ -1,8 +0,0 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `account`.`mailAliasAccount_beforeInsert`
BEFORE INSERT ON `mailAliasAccount`
FOR EACH ROW
BEGIN
SET NEW.editorFk = account.myUser_getId();
END$$
DELIMITER ;

View File

@ -1,8 +0,0 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `account`.`mailAliasAccount_beforeUpdate`
BEFORE UPDATE ON `mailAliasAccount`
FOR EACH ROW
BEGIN
SET NEW.editorFk = account.myUser_getId();
END$$
DELIMITER ;

View File

@ -7,7 +7,8 @@ AS SELECT `u`.`id` AS `id`,
`u`.`email` AS `email`,
`u`.`nickname` AS `nickname`,
`u`.`lang` AS `lang`,
`u`.`role` AS `role`
`u`.`role` AS `role`,
`u`.`recoverPass` AS `recoverPass`
FROM `account`.`user` `u`
WHERE `u`.`name` = `myUser_getName`()
WITH CASCADED CHECK OPTION

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