Compare commits

...

17 Commits

Author SHA1 Message Date
09de4fd033 feat: outdated version handling 2023-10-05 09:56:25 +02:00
Rainer Killinger
cb196afded feat: communicate outdated app/api client version 2023-10-02 08:48:07 +00:00
e0b7e616b3 fix: live update distance in list items 2023-09-21 09:38:52 +00:00
38fb7a398d fix: long branch names prevent review deployment 2023-09-21 09:55:35 +02:00
a99e08cd68 refactor: change opening hours handling
fix: opening hours not updating
feat: lazy-load opening hours module
feat: add e2e tests for opening hours
refactor: migrate opening hours to on-push change detection
feat: show exact minutes in opening hours starting one hour before next change
2023-09-21 09:55:35 +02:00
a5c9d22016 feat: add external directions referral
feat: change map page
feat: add error handling and timeout to location fetching in directions

resolves #124
resolves #122
2023-09-15 18:52:28 +00:00
3c49c4cf6d fix: route stack service causes needless network traffic 2023-09-06 15:29:47 +02:00
f2c4ee308f feat: share loaded data to detail views across routes 2023-09-06 14:52:02 +02:00
bd09b36620 refactor: use observable chains in rating component 2023-08-29 10:20:35 +00:00
ca146b7761 refactor: separate dashboard schedule nav e2e tests 2023-08-28 13:48:34 +02:00
Thea Schöbl
001f978bf9 feat: cleanup profile page 2023-08-25 14:43:25 +00:00
Thea Schöbl
57a5b6061b fix: type errors in easy-ast when generating docs 2023-08-23 08:45:47 +00:00
Rainer Killinger
4fb5941c56 ci: prepare e2e jobs for non nonexistent cache 2023-08-22 17:09:14 +02:00
Rainer Killinger
314e6a6e86 ci: move most pipelines to GitLab OSS large runner 2023-08-08 17:31:14 +02:00
Thea Schöbl
e1cc33bba2 refactor: rename "recurring" to "week overview"
refactor: replace dashboard calendar icon
resolves #128

refactor: route dashboard "next unit" to date series instead of events
resolves #126
2023-08-07 15:51:23 +00:00
Rainer Killinger
9abd397578 refactor: update changelog
ci: publish release
2023-08-03 16:30:40 +02:00
Rainer Killinger
69fe8c6ac8 ci: polish publishing via ci pipelines 2023-08-03 16:30:35 +02:00
213 changed files with 2299 additions and 2287 deletions

View File

@@ -0,0 +1,5 @@
---
'@openstapps/app': minor
---
Detail views now won't load data again if it is being navigated to from a list item

View File

@@ -0,0 +1,11 @@
---
'@openstapps/app': patch
---
Refactored Opening Hours
- Migrated Opening Hours to use OnPush change detection
- Fixed a bug where opening hours would not update correctly
- Lazy-load opening hours module to keep it out of the main bundle
- Added e2e tests to verify functionality
- Changed live update status to show exact minutes starting one hour before the next change

View File

@@ -0,0 +1,5 @@
---
'@openstapps/app': patch
---
Use observable chains instead of change detection in the rating component

View File

@@ -0,0 +1,5 @@
---
'@openstapps/app': minor
---
Added the ability to remove and add date series from their detail page

View File

@@ -0,0 +1,5 @@
---
'@openstapps/app': patch
---
Add a way to hide action chips on list items

View File

@@ -0,0 +1,5 @@
---
'@openstapps/app': patch
---
Fixed distance not updating in list items

View File

@@ -0,0 +1,5 @@
---
'@openstapps/app': minor
---
Add directions to inPlace and place list items

View File

@@ -0,0 +1,9 @@
---
'@openstapps/app': minor
---
Improved calendar descriptions
- The dashboard quick link now has a more intuitive icon
- "Recurring" has been renamed to "Week Overview"
- Long words in calendar tabs will now break instead of overflowing

View File

@@ -14,7 +14,6 @@
"@openstapps/minimal-deployment": "2.0.0", "@openstapps/minimal-deployment": "2.0.0",
"@openstapps/minimal-plugin": "2.0.0", "@openstapps/minimal-plugin": "2.0.0",
"@openstapps/app": "2.0.0", "@openstapps/app": "2.0.0",
"@openstapps/app-release-template": "2.0.0",
"@openstapps/api": "2.0.0", "@openstapps/api": "2.0.0",
"@openstapps/api-cli": "2.0.0", "@openstapps/api-cli": "2.0.0",
"@openstapps/api-plugin": "2.0.0", "@openstapps/api-plugin": "2.0.0",
@@ -24,9 +23,13 @@
"@openstapps/easy-ast": "2.0.0", "@openstapps/easy-ast": "2.0.0",
"@openstapps/es-mapping-generator": "2.0.0", "@openstapps/es-mapping-generator": "2.0.0",
"@openstapps/gitlab-api": "2.0.0", "@openstapps/gitlab-api": "2.0.0",
"@openstapps/logger": "2.0.0" "@openstapps/logger": "2.0.0",
"@openstapps/app-builder-image": "3.0.0-next.3",
"@openstapps/node-base": "3.0.0-next.3",
"@openstapps/node-builder": "3.0.0-next.3"
}, },
"changesets": [ "changesets": [
"bright-dryers-act",
"cool-jars-kiss", "cool-jars-kiss",
"cuddly-bobcats-roll", "cuddly-bobcats-roll",
"dull-news-appear", "dull-news-appear",
@@ -40,9 +43,14 @@
"moody-parrots-develop", "moody-parrots-develop",
"neat-hats-trade", "neat-hats-trade",
"new-pianos-joke", "new-pianos-joke",
"pretty-timers-complain",
"proud-wolves-end", "proud-wolves-end",
"quick-houses-count", "quick-houses-count",
"rare-squids-bake", "rare-squids-bake",
"serious-meals-sin",
"silent-maps-float",
"silly-news-punch",
"smart-ghosts-shout",
"soft-donuts-fail", "soft-donuts-fail",
"sour-coins-visit", "sour-coins-visit",
"spicy-snails-sort", "spicy-snails-sort",
@@ -51,6 +59,7 @@
"tall-ducks-dream", "tall-ducks-dream",
"tame-mayflies-hug", "tame-mayflies-hug",
"tame-rings-dream", "tame-rings-dream",
"tasty-islands-smell",
"thick-weeks-compete", "thick-weeks-compete",
"thin-camels-give", "thin-camels-give",
"tidy-buses-reflect", "tidy-buses-reflect",

View File

@@ -0,0 +1,13 @@
---
'@openstapps/app': minor
---
Revamp "My Courses" section on profile page
The "My Courses" section on the profile page has been improved
- It will now show the upcoming courses for the next five days
- The section header is now consistent with the other sections
- The section now uses standard list items instead of the custom solution
Additionally, the profile page component has been cleaned up.

View File

@@ -0,0 +1,8 @@
---
'@openstapps/app': minor
---
Adjust map button and item behavior on different screen sizes
- Small screens will show the item without margins below the map actions
- Large screens will show the list item on the left side

View File

@@ -1,7 +1,6 @@
--- ---
'@openstapps/projectmanagement': patch '@openstapps/projectmanagement': patch
'@openstapps/prettier-config': patch '@openstapps/prettier-config': patch
'@openstapps/app-release-template': patch
'@openstapps/es-mapping-generator': patch '@openstapps/es-mapping-generator': patch
'@openstapps/backend-config': patch '@openstapps/backend-config': patch
'@openstapps/eslint-config': patch '@openstapps/eslint-config': patch

View File

@@ -0,0 +1,5 @@
---
'@openstapps/app': minor
---
Queue config update for next launch to not block app launches

View File

@@ -0,0 +1,5 @@
---
'@openstapps/app': patch
---
Fixed an issue that caused double and triple loading of data detail items through the route stack service

View File

@@ -0,0 +1,5 @@
---
'@openstapps/app': minor
---
Map items are now native list items

View File

@@ -0,0 +1,5 @@
---
'@openstapps/app': minor
---
Replaced simple links with list items in date-series detail

View File

@@ -0,0 +1,5 @@
---
'@openstapps/proxy': minor
---
Send 426 to outdated clients instead of 404

View File

@@ -0,0 +1,5 @@
---
'@openstapps/app': minor
---
Use event title for date series instead of the generic date series title

View File

@@ -7,14 +7,18 @@
# ``` # ```
# To your pipeline. # To your pipeline.
# https://docs.gitlab.com/ee/ci/pipelines/merge_request_pipelines.html#use-rules-to-add-jobs # https://docs.gitlab.com/ee/ci/pipelines/merge_request_pipelines.html#use-rules-to-add-jobs
.limit_pipelines:
rules:
- if: $CI_PIPELINE_SOURCE == 'merge_request_event' || $CI_COMMIT_BRANCH == 'main' || $CI_COMMIT_BRANCH == 'develop'
when: on_success
- when: never
include: include:
- local: /backend/backend/.gitlab-ci.yml - local: /backend/backend/.gitlab-ci.yml
- local: /frontend/app/.gitlab-ci.yml - local: /frontend/app/.gitlab-ci.yml
- local: /.gitlab/schedules.gitlab-ci.yml - local: /.gitlab/schedules.gitlab-ci.yml
- local: /.gitlab/publishing.gitlab-ci.yml - local: /.gitlab/publishing.gitlab-ci.yml
rules:
- if: '$CI_COMMIT_MESSAGE =~ /ci: publish release$/'
when: always
variables: variables:
TURBO_CACHE_BYPASS: TURBO_CACHE_BYPASS:
@@ -28,7 +32,7 @@ variables:
default: default:
image: registry.gitlab.com/openstapps/openstapps/node-builder image: registry.gitlab.com/openstapps/openstapps/node-builder
tags: tags:
- performance - saas-linux-xlarge-amd64
interruptible: true interruptible: true
before_script: before_script:
- corepack enable - corepack enable
@@ -76,13 +80,14 @@ build:
rules: &deploy-rules rules: &deploy-rules
- if: $CI_PIPELINE_SOURCE == 'merge_request_event' - if: $CI_PIPELINE_SOURCE == 'merge_request_event'
variables: variables:
DEPLOY_ID: $CI_MERGE_REQUEST_SOURCE_BRANCH_NAME DEPLOY_ID: $CI_MERGE_REQUEST_IID
- if: $CI_COMMIT_BRANCH == 'main' - if: $CI_COMMIT_BRANCH == 'main'
variables: variables:
DEPLOY_ID: production DEPLOY_ID: production
- if: $CI_COMMIT_BRANCH == 'develop' - if: $CI_COMMIT_BRANCH == 'develop'
variables: variables:
DEPLOY_ID: staging DEPLOY_ID: staging
- !reference [.limit_pipelines, rules]
stop review: stop review:
stage: build stage: build
@@ -121,15 +126,15 @@ unit:
coverage_format: cobertura coverage_format: cobertura
path: coverage.xml path: coverage.xml
rules: rules:
- if: $CI_PIPELINE_SOURCE == 'merge_request_event' || $CI_COMMIT_BRANCH == 'main' || $CI_COMMIT_BRANCH == 'develop' - !reference [.limit_pipelines, rules]
audit: audit:
stage: audit stage: audit
allow_failure: true
needs: [] needs: []
script: script:
- pnpm audit --prod - pnpm audit --prod
rules: rules:
- if: $CI_PIPELINE_SOURCE == 'merge_request_event' || $CI_COMMIT_BRANCH == 'develop'
allow_failure: true
- if: $CI_COMMIT_BRANCH == 'main' - if: $CI_COMMIT_BRANCH == 'main'
allow_failure: false allow_failure: false
- !reference [.limit_pipelines, rules]

View File

@@ -1,6 +1,6 @@
.limit_publishing: .limit_publish_pipelines:
- if: $CI_PIPELINE_SOURCE != "schedule" rules:
when: on_success - if: '($CI_COMMIT_BRANCH == "main" || $CI_COMMIT_BRANCH == "develop") && $CI_COMMIT_MESSAGE =~ /ci: publish release/ && $CI_PIPELINE_SOURCE != "schedule"'
deploy: deploy:
stage: publish stage: publish
@@ -12,7 +12,8 @@ deploy:
paths: paths:
- ./.deploy - ./.deploy
- ./frontend/app/www - ./frontend/app/www
rules: !reference [.limit_publishing] rules:
- !reference [.limit_publish_pipelines, rules]
publish image: publish image:
stage: publish stage: publish
@@ -23,14 +24,15 @@ publish image:
image: image:
name: gcr.io/kaniko-project/executor:v1.12.1-debug name: gcr.io/kaniko-project/executor:v1.12.1-debug
entrypoint: [""] entrypoint: [""]
variables:
PUBLISH_TAG: next
script: script:
- > - >
/kaniko/executor /kaniko/executor
--context "${CI_PROJECT_DIR}/${DEPLOY_DIR}" --context "${CI_PROJECT_DIR}/${DEPLOY_DIR}"
--dockerfile "${CI_PROJECT_DIR}/${DEPLOY_DIR}/Dockerfile" --dockerfile "${CI_PROJECT_DIR}/${DEPLOY_DIR}/Dockerfile"
--destination "${CI_REGISTRY_IMAGE}/${IMAGE_NAME}:$(grep -o '"version": "[^"]*' "${DEPLOY_DIR}/package.json" | cut -d'"' -f4)" --destination "${CI_REGISTRY_IMAGE}/${IMAGE_NAME}:$(grep -o '"version": "[^"]*' "${DEPLOY_DIR}/package.json" | cut -d'"' -f4)"
--destination "${CI_REGISTRY_IMAGE}/${IMAGE_NAME}:latest" --destination "${CI_REGISTRY_IMAGE}/${IMAGE_NAME}:${PUBLISH_TAG}"
rules: !reference [.limit_publishing]
parallel: parallel:
matrix: matrix:
- IMAGE_NAME: database - IMAGE_NAME: database
@@ -47,6 +49,11 @@ publish image:
DEPLOY_DIR: .deploy/minimal-plugin DEPLOY_DIR: .deploy/minimal-plugin
- IMAGE_NAME: app - IMAGE_NAME: app
DEPLOY_DIR: frontend/app DEPLOY_DIR: frontend/app
rules:
- if: $CI_COMMIT_BRANCH == 'main'
variables:
PUBLISH_TAG: latest
- !reference [.limit_publish_pipelines, rules]
publish packages: publish packages:
stage: publish stage: publish
@@ -54,18 +61,17 @@ publish packages:
variables: variables:
GIT_STRATEGY: clone GIT_STRATEGY: clone
GIT_DEPTH: 0 GIT_DEPTH: 0
PUBLISH_TAG: next
script: script:
- pnpm install - pnpm install
- pnpm build - pnpm build
- pnpm publish -r --publish-branch ${PUBLISH_BRANCH} --tag ${PUBLISH_TAG} --no-git-checks # TODO: Git checks... - pnpm config set '//registry.npmjs.org/:_authToken' "${NPM_AUTH_TOKEN}"
- pnpm publish -r --publish-branch ${CI_COMMIT_BRANCH} --tag ${PUBLISH_TAG} --no-git-checks # TODO: Git checks...
rules: rules:
- if: $CI_COMMIT_BRANCH == 'main' - if: $CI_COMMIT_BRANCH == 'main'
variables: variables:
PUBLISH_BRANCH: main
PUBLISH_TAG: latest PUBLISH_TAG: latest
- variables: - !reference [.limit_publish_pipelines, rules]
PUBLISH_BRANCH: $CI_COMMIT_BRANCH
PUBLISH_TAG: next
publish docs: publish docs:
stage: publish stage: publish
@@ -77,3 +83,6 @@ publish docs:
artifacts: artifacts:
paths: paths:
- public - public
rules:
- if: $CI_COMMIT_BRANCH == 'main'
- !reference [.limit_publish_pipelines, rules]

View File

@@ -1,6 +1,6 @@
.limit_base_image_publishing: .limit_scheduled_pipelines:
- if: $CI_PIPELINE_SOURCE == "schedule" && $CI_COMMIT_BRANCH == 'main' rules:
when: always - if: $CI_COMMIT_BRANCH == 'main' && $CI_PIPELINE_SOURCE == "schedule"
base image: base image:
image: docker image: docker
@@ -18,10 +18,9 @@ base image:
docker build docker build
-t "${CI_REGISTRY_IMAGE}/${IMAGE_NAME}:$(grep -o '"version": "[^"]*' "${DEPLOY_DIR}/package.json" | cut -d'"' -f4)" -t "${CI_REGISTRY_IMAGE}/${IMAGE_NAME}:$(grep -o '"version": "[^"]*' "${DEPLOY_DIR}/package.json" | cut -d'"' -f4)"
-t "${CI_REGISTRY_IMAGE}/${IMAGE_NAME}:latest" "${CI_PROJECT_DIR}/${DEPLOY_DIR}" && -t "${CI_REGISTRY_IMAGE}/${IMAGE_NAME}:latest" "${CI_PROJECT_DIR}/${DEPLOY_DIR}" &&
docker push "${CI_REGISTRY_IMAGE}/${IMAGE_NAME}" docker push "${CI_REGISTRY_IMAGE}/${IMAGE_NAME}" --all-tags
cache: {} # disable irrelevant cache for this job cache: {} # disable irrelevant cache for this job
before_script: [] # do not run irrelevant before script for this job before_script: [] # do not run irrelevant before script for this job
rules: !reference [.limit_base_image_publishing]
parallel: parallel:
matrix: matrix:
- IMAGE_NAME: node-base - IMAGE_NAME: node-base
@@ -30,4 +29,7 @@ base image:
DEPLOY_DIR: images/node-builder DEPLOY_DIR: images/node-builder
- IMAGE_NAME: app-builder - IMAGE_NAME: app-builder
DEPLOY_DIR: images/app-builder DEPLOY_DIR: images/app-builder
- IMAGE_NAME: app-cypress
DEPLOY_DIR: images/app-cypress
rules:
- !reference [.limit_scheduled_pipelines, rules]

View File

@@ -19,4 +19,4 @@ integration:
junit: junit:
- backend/backend/coverage/integration-report-junit.xml - backend/backend/coverage/integration-report-junit.xml
rules: rules:
- if: $CI_PIPELINE_SOURCE == 'merge_request_event' || $CI_COMMIT_BRANCH == 'main' || $CI_COMMIT_BRANCH == 'develop' - !reference [.limit_pipelines, rules]

View File

@@ -1,5 +1,15 @@
# @openstapps/backend # @openstapps/backend
## 3.0.0-next.4
### Patch Changes
- 23481d0d: Update to TypeScript 5.1.6
- Updated dependencies [23481d0d]
- @openstapps/core-tools@3.0.0-next.4
- @openstapps/logger@3.0.0-next.4
- @openstapps/core@3.0.0-next.4
## 3.0.0-next.0 ## 3.0.0-next.0
### Major Changes ### Major Changes

View File

@@ -1,7 +1,7 @@
{ {
"name": "@openstapps/backend", "name": "@openstapps/backend",
"description": "A reference implementation for a StApps backend", "description": "A reference implementation for a StApps backend",
"version": "3.0.0-next.0", "version": "3.0.0-next.4",
"private": true, "private": true,
"type": "module", "type": "module",
"license": "AGPL-3.0-only", "license": "AGPL-3.0-only",

View File

@@ -0,0 +1,7 @@
# @openstapps/database
## 3.0.0-next.4
### Patch Changes
- 23481d0d: Update to TypeScript 5.1.6

View File

@@ -1,6 +1,6 @@
{ {
"name": "@openstapps/database", "name": "@openstapps/database",
"version": "2.0.0", "version": "3.0.0-next.4",
"private": true, "private": true,
"files": [ "files": [
"config", "config",

View File

@@ -1,5 +1,13 @@
# @openstapps/proxy # @openstapps/proxy
## 3.0.0-next.4
### Patch Changes
- 23481d0d: Update to TypeScript 5.1.6
- Updated dependencies [23481d0d]
- @openstapps/logger@3.0.0-next.4
## 3.0.0-next.0 ## 3.0.0-next.0
### Major Changes ### Major Changes

View File

@@ -31,10 +31,11 @@ To Provide your own configuration file you can create a `default.json` file in t
## Status Codes ## Status Codes
- OutdatedVersions return a `HTTP 404` - Successfull reponses come with a `HTTP 200`
- ActiveVersions return a `HTTP 503` if currently unavailable or the given code by running backend-node
- Unsupported versions (not configured as outdated or active) return a `HTTP 404`
- No version header given returns a `HTTP 300` - No version header given returns a `HTTP 300`
- ActiveVersions return a `HTTP 503` if currently unavailable or the given code by running backend-node
- OutdatedVersions return a `HTTP 426`
- Unsupported versions (not configured as outdated or active) return a `HTTP 426`
**NOTE:** The default configuration expects the client to set a version header: `X-StApps-Version=<version of app>` **NOTE:** The default configuration expects the client to set a version header: `X-StApps-Version=<version of app>`

View File

@@ -14,9 +14,8 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
// ESM is not supported, and cts is not detected, so we use type-checked cjs instead.
/** @type {import('../src/common').ConfigFile} */ /** @type {import('../src/common').ConfigFile} */
const configFile = { module.exports = {
activeVersions: ['1\\.0\\.\\d+', '2\\.0\\.\\d+'], activeVersions: ['1\\.0\\.\\d+', '2\\.0\\.\\d+'],
hiddenRoutes: ['/bulk'], hiddenRoutes: ['/bulk'],
logFormat: 'default', logFormat: 'default',
@@ -31,5 +30,3 @@ const configFile = {
dhparam: '/etc/nginx/certs/dhparam.pem', dhparam: '/etc/nginx/certs/dhparam.pem',
}, },
}; };
export default configFile;

View File

@@ -19,14 +19,15 @@ location {{{ route }}} {
return 300 'You have to supply a client/app version via the X-StApps-Version header!'; return 300 'You have to supply a client/app version via the X-StApps-Version header!';
} }
# Version is unsupported or never existed # Version is unsupported by now or never existed (App/Client has to update)
if ($proxyurl = unsupported) { if ($proxyurl = unsupported) {
{{{ cors }}} {{{ cors }}}
return 404; return 426;
} }
# The version existed, but is outdated now (App should update) # The version existed, but is outdated now (App/Client should update)
if ($proxyurl = outdated) { if ($proxyurl = outdated) {
return 404; {{{ cors }}}
return 426;
} }
# The version is correct, but backend is not responding # The version is correct, but backend is not responding
if ($proxyurl = unavailable) { if ($proxyurl = unavailable) {

View File

@@ -1,7 +1,7 @@
{ {
"name": "@openstapps/proxy", "name": "@openstapps/proxy",
"description": "NGINX proxy that is dynamically configured by a Node.js script", "description": "NGINX proxy that is dynamically configured by a Node.js script",
"version": "3.0.0-next.0", "version": "3.0.0-next.4",
"private": true, "private": true,
"type": "module", "type": "module",
"license": "AGPL-3.0-only", "license": "AGPL-3.0-only",
@@ -34,10 +34,12 @@
"build": "tsup-node --dts", "build": "tsup-node --dts",
"build:docker": "docker build -t openstapps:proxy ../../.deploy/proxy", "build:docker": "docker build -t openstapps:proxy ../../.deploy/proxy",
"deploy": "pnpm --prod --filter=@openstapps/proxy deploy ../../.deploy/proxy", "deploy": "pnpm --prod --filter=@openstapps/proxy deploy ../../.deploy/proxy",
"dev": "tsup --watch --onSuccess \"pnpm run start\"",
"format": "prettier . -c --ignore-path ../../.gitignore", "format": "prettier . -c --ignore-path ../../.gitignore",
"format:fix": "prettier --write . --ignore-path ../../.gitignore", "format:fix": "prettier --write . --ignore-path ../../.gitignore",
"lint": "eslint --ext .ts src/", "lint": "eslint --ext .ts src/",
"lint:fix": "eslint --fix --ext .ts src/", "lint:fix": "eslint --fix --ext .ts src/",
"start": "node app.js",
"test": "c8 mocha" "test": "c8 mocha"
}, },
"dependencies": { "dependencies": {

View File

@@ -37,7 +37,7 @@ const delay = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
* Reads the container information from the docker socket and updates the nginx config if necessary * Reads the container information from the docker socket and updates the nginx config if necessary
*/ */
async function updateNginxConfig() { async function updateNginxConfig() {
const containers = await getContainers(); const containers = await getContainers(process.env.DOCKER_SOCKET);
const containerHash = containers const containerHash = containers
.map((container: ContainerInfo) => { .map((container: ContainerInfo) => {
@@ -78,4 +78,4 @@ async function updateNginxConfig() {
// start the process that checks the docker socket periodically // start the process that checks the docker socket periodically
// eslint-disable-next-line unicorn/prefer-top-level-await // eslint-disable-next-line unicorn/prefer-top-level-await
updateNginxConfig(); await updateNginxConfig();

View File

@@ -1,5 +1,11 @@
# @openstapps/backend-config # @openstapps/backend-config
## 3.0.0-next.4
### Patch Changes
- 23481d0d: Update to TypeScript 5.1.6
## 3.0.0-next.0 ## 3.0.0-next.0
### Major Changes ### Major Changes

View File

@@ -1,7 +1,7 @@
{ {
"name": "@openstapps/backend-config", "name": "@openstapps/backend-config",
"description": "Backend Configuration for OpenStApps", "description": "Backend Configuration for OpenStApps",
"version": "3.0.0-next.0", "version": "3.0.0-next.4",
"private": true, "private": true,
"type": "module", "type": "module",
"license": "GPL-3.0-only", "license": "GPL-3.0-only",

View File

@@ -1,5 +1,11 @@
# @openstapps/eslint-config # @openstapps/eslint-config
## 3.0.0-next.4
### Patch Changes
- 23481d0d: Update to TypeScript 5.1.6
## 3.0.0-next.0 ## 3.0.0-next.0
### Major Changes ### Major Changes

View File

@@ -1,7 +1,7 @@
{ {
"name": "@openstapps/eslint-config", "name": "@openstapps/eslint-config",
"description": "A collection of configuration base files for StApps projects. Just an (unused) experiment for now.", "description": "A collection of configuration base files for StApps projects. Just an (unused) experiment for now.",
"version": "3.0.0-next.0", "version": "3.0.0-next.4",
"type": "commonjs", "type": "commonjs",
"license": "GPL-3.0-only", "license": "GPL-3.0-only",
"repository": "git@gitlab.com:openstapps/eslint-config.git", "repository": "git@gitlab.com:openstapps/eslint-config.git",

View File

@@ -1,5 +1,11 @@
# @openstapps/prettier-config # @openstapps/prettier-config
## 3.0.0-next.4
### Patch Changes
- 23481d0d: Update to TypeScript 5.1.6
## 3.0.0-next.0 ## 3.0.0-next.0
### Major Changes ### Major Changes

View File

@@ -1,7 +1,7 @@
{ {
"name": "@openstapps/prettier-config", "name": "@openstapps/prettier-config",
"description": "StApps Prettier Config", "description": "StApps Prettier Config",
"version": "3.0.0-next.0", "version": "3.0.0-next.4",
"type": "module", "type": "module",
"license": "GPL-3.0-only", "license": "GPL-3.0-only",
"repository": "git@gitlab.com:openstapps/prettier-config.git", "repository": "git@gitlab.com:openstapps/prettier-config.git",

View File

@@ -1,5 +1,22 @@
# @openstapps/projectmanagement # @openstapps/projectmanagement
## 3.0.0-next.4
### Major Changes
- 11c9d742: Move images to separate packages
Removed builder image due to migration to Kaniko
### Patch Changes
- 4e4c7b5c: Update release configs
- 23481d0d: Update to TypeScript 5.1.6
- Updated dependencies [23481d0d]
- @openstapps/collection-utils@3.0.0-next.4
- @openstapps/gitlab-api@3.0.0-next.4
- @openstapps/logger@3.0.0-next.4
## 3.0.0-next.3 ## 3.0.0-next.3
### Patch Changes ### Patch Changes

View File

@@ -1,7 +1,7 @@
{ {
"name": "@openstapps/projectmanagement", "name": "@openstapps/projectmanagement",
"description": "Main documentation and scripts for maintenance.", "description": "Main documentation and scripts for maintenance.",
"version": "3.0.0-next.3", "version": "3.0.0-next.4",
"private": true, "private": true,
"type": "module", "type": "module",
"license": "GPL-3.0-only", "license": "GPL-3.0-only",

View File

@@ -1,5 +1,11 @@
# @openstapps/tsconfig # @openstapps/tsconfig
## 3.0.0-next.4
### Patch Changes
- 23481d0d: Update to TypeScript 5.1.6
## 3.0.0-next.0 ## 3.0.0-next.0
### Major Changes ### Major Changes

View File

@@ -1,7 +1,7 @@
{ {
"name": "@openstapps/tsconfig", "name": "@openstapps/tsconfig",
"description": "The tsconfig for the openstapps project", "description": "The tsconfig for the openstapps project",
"version": "3.0.0-next.0", "version": "3.0.0-next.4",
"type": "commonjs", "type": "commonjs",
"license": "GPL-3.0-only", "license": "GPL-3.0-only",
"repository": "git@gitlab.com:openstapps/eslint-config.git", "repository": "git@gitlab.com:openstapps/eslint-config.git",

View File

@@ -1,5 +1,15 @@
# @openstapps/minimal-connector # @openstapps/minimal-connector
## 3.0.0-next.4
### Patch Changes
- 23481d0d: Update to TypeScript 5.1.6
- Updated dependencies [23481d0d]
- @openstapps/logger@3.0.0-next.4
- @openstapps/core@3.0.0-next.4
- @openstapps/api@3.0.0-next.4
## 3.0.0-next.0 ## 3.0.0-next.0
### Major Changes ### Major Changes

View File

@@ -1,7 +1,7 @@
{ {
"name": "@openstapps/minimal-connector", "name": "@openstapps/minimal-connector",
"description": "This is a minimal connector which serves as an example", "description": "This is a minimal connector which serves as an example",
"version": "3.0.0-next.0", "version": "3.0.0-next.4",
"private": true, "private": true,
"type": "module", "type": "module",
"license": "GPL-3.0-only", "license": "GPL-3.0-only",

View File

@@ -0,0 +1,7 @@
# @openstapps/minimal-deployment
## 3.0.0-next.4
### Patch Changes
- 23481d0d: Update to TypeScript 5.1.6

View File

@@ -1,7 +1,7 @@
version: '3.7' version: '3.7'
services: services:
database: database:
image: registry.gitlab.com/openstapps/openstapps/database:2.0.0 image: registry.gitlab.com/openstapps/openstapps/database:3.0.0-next.4
volumes: volumes:
- ./database:/usr/share/elasticsearch/data - ./database:/usr/share/elasticsearch/data
expose: expose:
@@ -9,7 +9,7 @@ services:
restart: unless-stopped restart: unless-stopped
backend: backend:
image: registry.gitlab.com/openstapps/openstapps/backend:3.0.0-next.0 image: registry.gitlab.com/openstapps/openstapps/backend:3.0.0-next.4
environment: environment:
ES_ADDR: "http://database:9200" ES_ADDR: "http://database:9200"
NODE_CONFIG_ENV: "elasticsearch" NODE_CONFIG_ENV: "elasticsearch"
@@ -27,17 +27,17 @@ services:
- database - database
api: api:
image: registry.gitlab.com/openstapps/openstapps/api:3.0.0-next.0 image: registry.gitlab.com/openstapps/openstapps/api:3.0.0-next.4
links: links:
- "backend" - "backend"
minimal-connector: minimal-connector:
image: registry.gitlab.com/openstapps/minimal-connector:core-0.23 image: registry.gitlab.com/openstapps/openstapps/minimal-connector:3.0.0-next.4
container_name: minimal-connector-0.23 container_name: minimal-connector-0.23
command: ["http://backend:3000", "minimal-connector", "f-u"] command: ["http://backend:3000", "minimal-connector", "f-u"]
app: app:
image: registry.gitlab.com/openstapps/app/executable:core-0.23 image: registry.gitlab.com/openstapps/openstapps/app:3.0.0-next.4
expose: expose:
- 8100 - 8100
ports: ports:

View File

@@ -1,6 +1,6 @@
{ {
"name": "@openstapps/minimal-deployment", "name": "@openstapps/minimal-deployment",
"version": "2.0.0", "version": "3.0.0-next.4",
"private": true, "private": true,
"files": [ "files": [
"database", "database",

View File

@@ -1,5 +1,17 @@
# @openstapps/minimal-plugin # @openstapps/minimal-plugin
## 3.0.0-next.4
### Patch Changes
- 23481d0d: Update to TypeScript 5.1.6
- Updated dependencies [23481d0d]
- @openstapps/api-plugin@3.0.0-next.4
- @openstapps/core-tools@3.0.0-next.4
- @openstapps/logger@3.0.0-next.4
- @openstapps/core@3.0.0-next.4
- @openstapps/api@3.0.0-next.4
## 3.0.0-next.0 ## 3.0.0-next.0
### Major Changes ### Major Changes

View File

@@ -1,7 +1,7 @@
{ {
"name": "@openstapps/minimal-plugin", "name": "@openstapps/minimal-plugin",
"description": "Minimal Plugin", "description": "Minimal Plugin",
"version": "3.0.0-next.0", "version": "3.0.0-next.4",
"private": true, "private": true,
"type": "module", "type": "module",
"license": "GPL-3.0-only", "license": "GPL-3.0-only",

View File

@@ -15,8 +15,12 @@
buildToolsVersions = [ "${buildToolsVersion}" ]; buildToolsVersions = [ "${buildToolsVersion}" ];
platformVersions = [ "32" ]; platformVersions = [ "32" ];
}; };
cypress = prev.cypress.overrideAttrs(prev: { cypress = prev.cypress.overrideAttrs(cyPrev: rec {
version = "12.17.1"; version = "13.2.0";
src = prev.fetchzip {
url = "https://cdn.cypress.io/desktop/${version}/linux-x64/cypress.zip";
hash = "sha256-9o0nprGcJhudS1LNm+T7Vf0Dwd1RBauYKI+w1FBQ3ZM=";
};
}); });
}) })
]; ];

View File

@@ -8,7 +8,7 @@
"parserOptions": { "parserOptions": {
"ecmaVersion": 2020, "ecmaVersion": 2020,
"sourceType": "module", "sourceType": "module",
"project": ["tsconfig.json", "tsconfig.spec.json", "e2e/tsconfig.e2e.json"], "project": ["tsconfig.json", "tsconfig.spec.json", "cypress/tsconfig.json"],
"createDefaultProgram": true "createDefaultProgram": true
}, },
"extends": [ "extends": [

View File

@@ -1,9 +1,12 @@
e2e: e2e:
image: cypress/browsers:latest # https://hub.docker.com/r/cypress/browsers/tags/ image: registry.gitlab.com/openstapps/openstapps/app-cypress:node-18
stage: test stage: test
script: script:
- pnpm --filter=@openstapps/app install - pnpm --filter=@openstapps/app install
- pnpm --filter=@openstapps/app exec cypress install - pnpm --filter=@openstapps/app exec cypress install
- cd node_modules/.pnpm/re2*/node_modules/re2
- npm run install
- cd $CI_PROJECT_DIR
- pnpm test:integration:app - pnpm test:integration:app
artifacts: artifacts:
when: on_failure when: on_failure
@@ -19,4 +22,4 @@ e2e:
- BROWSER: chrome - BROWSER: chrome
- BROWSER: firefox - BROWSER: firefox
rules: rules:
- if: $CI_PIPELINE_SOURCE == 'merge_request_event' || $CI_COMMIT_BRANCH == 'main' || $CI_COMMIT_BRANCH == 'develop' - !reference [.limit_pipelines, rules]

View File

@@ -1,5 +1,29 @@
# @openstapps/app # @openstapps/app
## 3.0.0-next.4
### Major Changes
- 23481d0d: Update to Angular 16.1
### Minor Changes
- 23481d0d: Migrate to Ionic 7
- Migrate uses of `<ion-label>` with inputs to new syntax
- Fix infinite loop in schedule date picker (`datetime.confirm()` to `datetime.cancel()`)
### Patch Changes
- 23481d0d: Update to TypeScript 5.1.6
- bebee6b4: Migrate collection helpers to use @openstapps/collection-utils
- 107a7c5e: Migrate unit tests to karma-coverage and junit reports.
Fixes an issue where coverage reports would not be generated.
- Updated dependencies [23481d0d]
- @openstapps/collection-utils@3.0.0-next.4
- @openstapps/core@3.0.0-next.4
- @openstapps/api@3.0.0-next.4
## 3.0.0-next.0 ## 3.0.0-next.0
### Major Changes ### Major Changes

View File

@@ -42,3 +42,23 @@ The command `ionic cordova run ios` runs into the error `/platforms/ios/build/em
- Either use the command: `ionic cordova emulate ios -- --buildFlag="-UseModernBuildSystem=0"` - Either use the command: `ionic cordova emulate ios -- --buildFlag="-UseModernBuildSystem=0"`
- Or open the iOS project in Xcode and change build system in workspace settings to `Lagacy Build System`. Then the normal run command works also. - Or open the iOS project in Xcode and change build system in workspace settings to `Lagacy Build System`. Then the normal run command works also.
## Cypress
#### Problem
The browser doesn't open or the tests don't connect to a browser
#### Cause
Cypress was installed to a read-only location, see
[this issue](https://github.com/cypress-io/cypress/issues/18893).
This can be the case if you use NixOS.
#### Solution
Make sure the cypress folder is writable before each launch
```shell
chmod -R +rw ~/.config/Cypress
```

View File

@@ -182,6 +182,7 @@
"builder": "@cypress/schematic:cypress", "builder": "@cypress/schematic:cypress",
"options": { "options": {
"devServerTarget": "app:serve", "devServerTarget": "app:serve",
"liveReload": false,
"watch": true, "watch": true,
"headless": false "headless": false
}, },

View File

@@ -18,14 +18,18 @@
describe('dashboard', async function () { describe('dashboard', async function () {
describe('schedule section', function () { describe('schedule section', function () {
it('should lead to the schedule', function () { it('should lead to the week overview', function () {
cy.visit('/overview'); cy.visit('/overview');
cy.get('.schedule').contains('a', 'Stundenplan').click(); cy.get('.schedule')
cy.url().should('include', '/schedule/recurring'); .contains('a', /Wochen.*übersicht/)
.click();
cy.url().should('include', '/schedule/week-overview');
});
it('should lead to the calendar', function () {
cy.visit('/overview'); cy.visit('/overview');
cy.get('.schedule').contains('a', 'Kein Eintrag gefunden').click(); cy.get('.schedule').contains('a', 'Kein Eintrag gefunden').click();
cy.url().should('include', '/schedule/recurring'); cy.url().should('include', '/schedule/calendar');
}); });
// TODO: Reenable and stabilize tests // TODO: Reenable and stabilize tests

View File

@@ -0,0 +1,141 @@
describe('opening hours', () => {
beforeEach(function () {
cy.intercept('POST', 'https://mobile.server.uni-frankfurt.de/search', {
fixture: 'search/types/canteen/canteen-search-result.json',
}).as('search');
});
it('should specify relative closing time', () => {
cy.clock(new Date(2023, 9, 16, 15, 29), ['Date']);
cy.visit('/canteen');
cy.get('stapps-opening-hours')
.first()
.should('contain', 'Geöffnet')
.should('contain', 'Schließt heute um 22:00');
});
it('should specify relative opening time', () => {
cy.clock(new Date(2023, 9, 16, 6, 29), ['Date']);
cy.visit('/canteen');
cy.get('stapps-opening-hours')
.first()
.should('contain', 'Geschlossen')
.should('contain', 'Öffnet heute um 08:30');
});
it('should specify soon opening time', () => {
cy.clock(new Date(2023, 9, 16, 8, 0), ['Date']);
cy.visit('/canteen');
cy.get('stapps-opening-hours')
.first()
.should('contain', 'Geschlossen')
.should('contain', 'Öffnet in 30 Minuten');
});
it('should specify soon closing time', () => {
cy.clock(new Date(2023, 9, 16, 21, 30), ['Date']);
cy.visit('/canteen');
cy.get('stapps-opening-hours')
.first()
.should('contain', 'Geöffnet')
.should('contain', 'Schließt in 30 Minuten');
});
it('should update the soon closing time every minute', () => {
cy.clock(new Date(2023, 9, 16, 21, 30));
cy.visit('/canteen');
cy.tick(500);
cy.get('stapps-opening-hours')
.first()
.should('contain', 'Geöffnet')
.should('contain', 'Schließt in 30 Minuten');
cy.tick(60_000);
cy.tick(50);
cy.get('stapps-opening-hours')
.first()
.should('contain', 'Geöffnet')
.should('contain', 'Schließt in 29 Minuten');
});
it('should update the status when it changes', () => {
cy.clock(new Date(2023, 9, 16, 21, 59));
cy.visit('/canteen');
cy.tick(500);
cy.get('stapps-opening-hours')
.first()
.should('contain', 'Geöffnet')
.should('contain', 'Schließt in 1 Minute');
cy.tick(60_000);
cy.get('stapps-opening-hours')
.first()
.should('contain', 'Geschlossen')
.should('contain', 'Öffnet morgen um 08:30');
});
// This one takes long to execute!
it('should update as expected', () => {
cy.clock(new Date(2023, 9, 16, 20, 59));
cy.visit('/canteen');
cy.tick(500);
cy.get('stapps-opening-hours')
.first()
.should('contain', 'Geöffnet')
.should('contain', 'Schließt heute um 22:00');
cy.tick(60_000);
cy.get('stapps-opening-hours')
.first()
.should('contain', 'Geöffnet')
.should('contain', 'Schließt in 60 Minuten');
cy.tick(30 * 60_000);
cy.get('stapps-opening-hours')
.first()
.should('contain', 'Geöffnet')
.should('contain', 'Schließt in 30 Minuten');
cy.tick(30 * 60_000);
cy.get('stapps-opening-hours')
.first()
.should('contain', 'Geschlossen')
.should('contain', 'Öffnet morgen um 08:30');
cy.tick(9.5 * 60 * 60_000);
cy.get('stapps-opening-hours')
.first()
.should('contain', 'Geschlossen')
.should('contain', 'Öffnet in 60 Minuten');
cy.tick(30 * 60_000);
cy.get('stapps-opening-hours')
.first()
.should('contain', 'Geschlossen')
.should('contain', 'Öffnet in 30 Minuten');
cy.tick(30 * 60_000);
cy.get('stapps-opening-hours')
.first()
.should('contain', 'Geöffnet')
.should('contain', 'Schließt heute um 22:00');
// Long tick warps will cause network requests to time out
cy.get('@consoleError').invoke('resetHistory');
});
});

View File

@@ -31,36 +31,24 @@
// When a command from ./commands is ready to use, import with `import './commands'` syntax // When a command from ./commands is ready to use, import with `import './commands'` syntax
// import './commands'; // import './commands';
beforeEach(async function () { beforeEach(function () {
let databases: string[]; cy.wrap(
if (window.indexedDB.databases) { new Promise(resolve => {
databases = (await window.indexedDB.databases()).map(it => it.name); window.indexedDB.deleteDatabase('_ionicstorage').onsuccess = resolve;
console.log('Trying to clear all databases'); }),
} else { );
console.log("Browser doesn't support database enumeration, deleting just ionic storage");
databases = ['_ionicstorage'];
}
for (const database of databases) {
if (database) {
console.log(`Deleting database ${database}`);
await new Promise(resolve => (window.indexedDB.deleteDatabase(database).onsuccess = resolve));
console.log(`Deleted database ${database}`);
}
}
}); });
Cypress.on('window:before:load', window => { Cypress.on('window:before:load', window => {
// Fake that user is using its browser in german language // Fake that user is using its browser in German
Object.defineProperty(window.navigator, 'language', {value: 'de-DE'}); Object.defineProperty(window.navigator, 'language', {value: 'de-DE'});
Object.defineProperty(window.navigator, 'languages', [{value: 'de-DE'}]); Object.defineProperty(window.navigator, 'languages', [{value: 'de-DE'}]);
// Fail tests on console error cy.spy(window.console, 'error').as('consoleError');
cy.stub(window.console, 'error').callsFake(message => { });
// log out to the terminal
cy.now('task', 'error', message); afterEach(function () {
// log to Command Log and fail the test cy.get('@consoleError').should('not.have.been.called');
throw new Error(message);
});
}); });
Cypress.on('uncaught:exception', error => { Cypress.on('uncaught:exception', error => {

View File

@@ -1,7 +1,7 @@
{ {
"name": "@openstapps/app", "name": "@openstapps/app",
"description": "The generic app tailored to fulfill needs of German universities, written using Ionic Framework.", "description": "The generic app tailored to fulfill needs of German universities, written using Ionic Framework.",
"version": "3.0.0-next.0", "version": "3.0.0-next.4",
"private": true, "private": true,
"license": "GPL-3.0-only", "license": "GPL-3.0-only",
"author": "Karl-Philipp Wulfert <krlwlfrt@gmail.com>", "author": "Karl-Philipp Wulfert <krlwlfrt@gmail.com>",
@@ -63,6 +63,7 @@
"@awesome-cordova-plugins/core": "5.45.0", "@awesome-cordova-plugins/core": "5.45.0",
"@capacitor/app": "4.1.1", "@capacitor/app": "4.1.1",
"@capacitor/browser": "4.1.0", "@capacitor/browser": "4.1.0",
"@capacitor/clipboard": "4.1.0",
"@capacitor/core": "4.6.1", "@capacitor/core": "4.6.1",
"@capacitor/device": "4.1.0", "@capacitor/device": "4.1.0",
"@capacitor/dialog": "4.1.0", "@capacitor/dialog": "4.1.0",
@@ -84,11 +85,14 @@
"@ngx-translate/http-loader": "8.0.0", "@ngx-translate/http-loader": "8.0.0",
"@openid/appauth": "1.3.1", "@openid/appauth": "1.3.1",
"@openstapps/api": "workspace:*", "@openstapps/api": "workspace:*",
"@openstapps/core": "workspace:*",
"@openstapps/collection-utils": "workspace:*", "@openstapps/collection-utils": "workspace:*",
"@openstapps/core": "workspace:*",
"@transistorsoft/capacitor-background-fetch": "1.0.2", "@transistorsoft/capacitor-background-fetch": "1.0.2",
"@types/dom-view-transitions": "1.0.1",
"capacitor-secure-storage-plugin": "0.8.1", "capacitor-secure-storage-plugin": "0.8.1",
"cordova-plugin-calendar": "5.1.6", "cordova-plugin-calendar": "5.1.6",
"date-fns": "2.30.0",
"ngx-date-fns": "10.0.1",
"deepmerge": "4.3.1", "deepmerge": "4.3.1",
"form-data": "4.0.0", "form-data": "4.0.0",
"geojson": "0.5.0", "geojson": "0.5.0",
@@ -146,7 +150,7 @@
"@typescript-eslint/eslint-plugin": "5.60.1", "@typescript-eslint/eslint-plugin": "5.60.1",
"@typescript-eslint/parser": "5.60.1", "@typescript-eslint/parser": "5.60.1",
"cordova-res": "0.15.4", "cordova-res": "0.15.4",
"cypress": "12.17.1", "cypress": "13.2.0",
"eslint": "8.43.0", "eslint": "8.43.0",
"eslint-plugin-jsdoc": "46.4.2", "eslint-plugin-jsdoc": "46.4.2",
"eslint-plugin-prettier": "4.2.1", "eslint-plugin-prettier": "4.2.1",

View File

@@ -21,17 +21,13 @@ import {RouteReuseStrategy} from '@angular/router';
import {IonicModule, IonicRouteStrategy, Platform} from '@ionic/angular'; import {IonicModule, IonicRouteStrategy, Platform} from '@ionic/angular';
import {TranslateLoader, TranslateModule, TranslateService} from '@ngx-translate/core'; import {TranslateLoader, TranslateModule, TranslateService} from '@ngx-translate/core';
import {TranslateHttpLoader} from '@ngx-translate/http-loader'; import {TranslateHttpLoader} from '@ngx-translate/http-loader';
import moment from 'moment';
import 'moment/min/locales'; import 'moment/min/locales';
import {LoggerModule, NGXLogger, NgxLoggerLevel} from 'ngx-logger'; import {LoggerModule, NgxLoggerLevel} from 'ngx-logger';
import SwiperCore, {FreeMode, Navigation} from 'swiper'; import SwiperCore, {FreeMode, Navigation} from 'swiper';
import {environment} from '../environments/environment'; import {environment} from '../environments/environment';
import {AppRoutingModule} from './app-routing.module'; import {AppRoutingModule} from './app-routing.module';
import {AppComponent} from './app.component'; import {AppComponent} from './app.component';
import {CatalogModule} from './modules/catalog/catalog.module'; import {CatalogModule} from './modules/catalog/catalog.module';
import {ConfigModule} from './modules/config/config.module';
import {ConfigProvider} from './modules/config/config.provider';
import {DashboardModule} from './modules/dashboard/dashboard.module'; import {DashboardModule} from './modules/dashboard/dashboard.module';
import {DataModule} from './modules/data/data.module'; import {DataModule} from './modules/data/data.module';
import {HebisModule} from './modules/hebis/hebis.module'; import {HebisModule} from './modules/hebis/hebis.module';
@@ -40,11 +36,9 @@ import {MenuModule} from './modules/menu/menu.module';
import {NewsModule} from './modules/news/news.module'; import {NewsModule} from './modules/news/news.module';
import {ScheduleModule} from './modules/schedule/schedule.module'; import {ScheduleModule} from './modules/schedule/schedule.module';
import {SettingsModule} from './modules/settings/settings.module'; import {SettingsModule} from './modules/settings/settings.module';
import {SettingsProvider} from './modules/settings/settings.provider';
import {StorageModule} from './modules/storage/storage.module'; import {StorageModule} from './modules/storage/storage.module';
import {ThingTranslateModule} from './translation/thing-translate.module'; import {ThingTranslateModule} from './translation/thing-translate.module';
import {UtilModule} from './util/util.module'; import {UtilModule} from './util/util.module';
import {initLogger} from './_helpers/ts-logger';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations'; import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {AboutModule} from './modules/about/about.module'; import {AboutModule} from './modules/about/about.module';
import {FavoritesModule} from './modules/favorites/favorites.module'; import {FavoritesModule} from './modules/favorites/favorites.module';
@@ -54,78 +48,22 @@ import {DebugDataCollectorService} from './modules/data/debug-data-collector.ser
import {AuthModule} from './modules/auth/auth.module'; import {AuthModule} from './modules/auth/auth.module';
import {BackgroundModule} from './modules/background/background.module'; import {BackgroundModule} from './modules/background/background.module';
import {LibraryModule} from './modules/library/library.module'; import {LibraryModule} from './modules/library/library.module';
import {StorageProvider} from './modules/storage/storage.provider';
import {AssessmentsModule} from './modules/assessments/assessments.module'; import {AssessmentsModule} from './modules/assessments/assessments.module';
import {ServiceHandlerInterceptor} from './_helpers/service-handler.interceptor'; import {ServiceHandlerInterceptor} from './_helpers/service-handler.interceptor';
import {RoutingStackService} from './util/routing-stack.service';
import {SCSettingValue} from '@openstapps/core';
import {DefaultAuthService} from './modules/auth/default-auth.service';
import {PAIAAuthService} from './modules/auth/paia/paia-auth.service';
import {IonIconModule} from './util/ion-icon/ion-icon.module'; import {IonIconModule} from './util/ion-icon/ion-icon.module';
import {NavigationModule} from './modules/menu/navigation/navigation.module'; import {NavigationModule} from './modules/menu/navigation/navigation.module';
import {browserFactory, SimpleBrowser} from './util/browser.factory'; import {browserFactory, SimpleBrowser} from './util/browser.factory';
import {ConfigProvider} from './modules/config/config.provider';
import {SettingsProvider} from './modules/settings/settings.provider';
import {TranslateServiceWrapper} from './translation/translate-service-wrapper';
import {DefaultAuthService} from './modules/auth/default-auth.service';
import {PAIAAuthService} from './modules/auth/paia/paia-auth.service';
import {StorageProvider} from './modules/storage/storage.provider';
registerLocaleData(localeDe); registerLocaleData(localeDe);
SwiperCore.use([FreeMode, Navigation]); SwiperCore.use([FreeMode, Navigation]);
/**
* Initializes data needed on startup
* @param storageProvider provider of the saved data (using framework's storage)
* @param logger TODO
* @param settingsProvider provider of settings (e.g. language that has been set)
* @param configProvider TODO
* @param translateService TODO
* @param _routingStackService Just for init and to track the stack from the get go
*/
export function initializerFactory(
storageProvider: StorageProvider,
logger: NGXLogger,
settingsProvider: SettingsProvider,
configProvider: ConfigProvider,
translateService: TranslateService,
_routingStackService: RoutingStackService,
defaultAuthService: DefaultAuthService,
paiaAuthService: PAIAAuthService,
) {
return async () => {
initLogger(logger);
await storageProvider.init();
await configProvider.init();
await settingsProvider.init();
try {
if (configProvider.firstSession) {
// set language from browser
await settingsProvider.setSettingValue(
'profile',
'language',
translateService.getBrowserLang() as SCSettingValue,
);
}
const languageCode = (await settingsProvider.getValue('profile', 'language')) as string;
// this language will be used as a fallback when a translation isn't found in the current language
translateService.setDefaultLang('en');
translateService.use(languageCode);
moment.locale(languageCode);
await defaultAuthService.init();
await paiaAuthService.init();
} catch (error) {
logger.warn(error);
}
};
}
/**
* TODO
* @param http TODO
*/
export function createTranslateLoader(http: HttpClient) {
return new TranslateHttpLoader(http, './assets/i18n/', '.json');
}
/**
* TODO
*/
@NgModule({ @NgModule({
bootstrap: [AppComponent], bootstrap: [AppComponent],
declarations: [AppComponent], declarations: [AppComponent],
@@ -139,7 +77,6 @@ export function createTranslateLoader(http: HttpClient) {
BrowserAnimationsModule, BrowserAnimationsModule,
CatalogModule, CatalogModule,
CommonModule, CommonModule,
ConfigModule,
DashboardModule, DashboardModule,
DataModule, DataModule,
HebisModule, HebisModule,
@@ -163,7 +100,9 @@ export function createTranslateLoader(http: HttpClient) {
loader: { loader: {
deps: [HttpClient], deps: [HttpClient],
provide: TranslateLoader, provide: TranslateLoader,
useFactory: createTranslateLoader, useFactory(http: HttpClient) {
return new TranslateHttpLoader(http, './assets/i18n/', '.json');
},
}, },
}), }),
UtilModule, UtilModule,
@@ -173,6 +112,30 @@ export function createTranslateLoader(http: HttpClient) {
}), }),
], ],
providers: [ providers: [
{
provide: APP_INITIALIZER,
useFactory:
(...providers: Array<{beforeAppInit(): Promise<void>}>) =>
async () => {
for (const provider of providers) {
await provider.beforeAppInit();
}
},
// Declare initialization (order matters)
deps: [
StorageProvider,
ConfigProvider,
SettingsProvider,
TranslateService,
DefaultAuthService,
PAIAAuthService,
],
multi: true,
},
{
provide: TranslateService,
useClass: TranslateServiceWrapper,
},
{ {
provide: RouteReuseStrategy, provide: RouteReuseStrategy,
useClass: IonicRouteStrategy, useClass: IonicRouteStrategy,
@@ -186,21 +149,6 @@ export function createTranslateLoader(http: HttpClient) {
useFactory: browserFactory, useFactory: browserFactory,
deps: [Platform], deps: [Platform],
}, },
{
provide: APP_INITIALIZER,
multi: true,
deps: [
StorageProvider,
NGXLogger,
SettingsProvider,
ConfigProvider,
TranslateService,
RoutingStackService,
DefaultAuthService,
PAIAAuthService,
],
useFactory: initializerFactory,
},
{ {
provide: HTTP_INTERCEPTORS, provide: HTTP_INTERCEPTORS,
useClass: ServiceHandlerInterceptor, useClass: ServiceHandlerInterceptor,

View File

@@ -0,0 +1,10 @@
/**
* Services or providers implementing this interface
* must be added to the `APP_INITIALIZER` deps
*/
export interface BeforeAppInit {
/**
* Any logic that has to run before the app is initialized
*/
beforeAppInit(): Promise<void>;
}

View File

@@ -14,10 +14,9 @@
*/ */
import {Component, OnInit} from '@angular/core'; import {Component, OnInit} from '@angular/core';
import {ActivatedRoute} from '@angular/router'; import {ActivatedRoute} from '@angular/router';
import {SCAboutPage, SCAppConfiguration} from '@openstapps/core'; import {SCAboutPage} from '@openstapps/core';
import {ConfigProvider} from '../../config/config.provider';
import packageJson from '../../../../../package.json'; import packageJson from '../../../../../package.json';
import config from 'capacitor.config'; import {ConfigProvider} from '../../config/config.provider';
@Component({ @Component({
selector: 'about-page', selector: 'about-page',
@@ -27,15 +26,12 @@ import config from 'capacitor.config';
export class AboutPageComponent implements OnInit { export class AboutPageComponent implements OnInit {
content: SCAboutPage; content: SCAboutPage;
appName = config.appName;
version = packageJson.version; version = packageJson.version;
constructor(private readonly route: ActivatedRoute, private readonly configProvider: ConfigProvider) {} constructor(readonly route: ActivatedRoute, readonly config: ConfigProvider) {}
async ngOnInit() { ngOnInit() {
const route = this.route.snapshot.url.map(it => it.path).join('/'); const route = this.route.snapshot.url.map(it => it.path).join('/');
this.content = this.content = this.config.app.aboutPages[route] ?? {};
(this.configProvider.getValue('aboutPages') as SCAppConfiguration['aboutPages'])[route] ?? {};
} }
} }

View File

@@ -25,7 +25,7 @@
</ion-toolbar> </ion-toolbar>
</ion-header> </ion-header>
<ion-content parallax *ngIf="content"> <ion-content parallax *ngIf="content">
<ion-text>{{ appName }} v{{ version }}</ion-text> <ion-text>{{ config.app.name }} v{{ version }}</ion-text>
<div class="page-content"> <div class="page-content">
<about-page-content *ngFor="let element of content.content" [content]="element"></about-page-content> <about-page-content *ngFor="let element of content.content" [content]="element"></about-page-content>
</div> </div>

View File

@@ -19,7 +19,6 @@ import {FormsModule} from '@angular/forms';
import {IonicModule} from '@ionic/angular'; import {IonicModule} from '@ionic/angular';
import {TranslateModule} from '@ngx-translate/core'; import {TranslateModule} from '@ngx-translate/core';
import {ThingTranslateModule} from '../../translation/thing-translate.module'; import {ThingTranslateModule} from '../../translation/thing-translate.module';
import {ConfigProvider} from '../config/config.provider';
import {AboutPageComponent} from './about-page/about-page.component'; import {AboutPageComponent} from './about-page/about-page.component';
import {MarkdownModule} from 'ngx-markdown'; import {MarkdownModule} from 'ngx-markdown';
import {AboutPageContentComponent} from './about-page/about-page-content.component'; import {AboutPageContentComponent} from './about-page/about-page-content.component';
@@ -64,6 +63,5 @@ const settingsRoutes: Routes = [
ScrollingModule, ScrollingModule,
UtilModule, UtilModule,
], ],
providers: [ConfigProvider],
}) })
export class AboutModule {} export class AboutModule {}

View File

@@ -13,11 +13,12 @@
* this program. If not, see <https://www.gnu.org/licenses/>. * this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
import {Injectable} from '@angular/core'; import {Injectable} from '@angular/core';
import {ConfigProvider} from '../config/config.provider';
import {SCAssessment, SCUuid} from '@openstapps/core'; import {SCAssessment, SCUuid} from '@openstapps/core';
import {DefaultAuthService} from '../auth/default-auth.service'; import {DefaultAuthService} from '../auth/default-auth.service';
import {HttpClient} from '@angular/common/http'; import {HttpClient} from '@angular/common/http';
import {uniqBy, keyBy} from '@openstapps/collection-utils'; import {uniqBy, keyBy} from '@openstapps/collection-utils';
import {firstValueFrom} from 'rxjs';
import {ConfigProvider} from '../config/config.provider';
/** /**
* *
@@ -65,7 +66,7 @@ export class AssessmentsProvider {
cacheMaxAge = 15 * 60 * 1000; cacheMaxAge = 15 * 60 * 1000;
constructor( constructor(
readonly configProvider: ConfigProvider, readonly config: ConfigProvider,
readonly defaultAuth: DefaultAuthService, readonly defaultAuth: DefaultAuthService,
readonly http: HttpClient, readonly http: HttpClient,
) {} ) {}
@@ -91,21 +92,20 @@ export class AssessmentsProvider {
return this.cache; return this.cache;
} }
const url = this.configProvider.config.app.features.extern?.hisometry.url; const url = this.config.app.features.extern?.hisometry.url;
if (!url) throw new Error('Config lacks url for hisometry'); if (!url) throw new Error('Config lacks url for hisometry');
this.cache = this.http this.cache = firstValueFrom(
.get<{data: SCAssessment[]}>(`${url}/${this.assessmentPath}`, { this.http.get<{data: SCAssessment[]}>(`${url}/${this.assessmentPath}`, {
headers: { headers: {
Authorization: `Bearer ${accessToken ?? (await this.defaultAuth.getValidToken()).accessToken}`, Authorization: `Bearer ${accessToken ?? (await this.defaultAuth.getValidToken()).accessToken}`,
}, },
}) }),
.toPromise() ).then(it => {
.then(it => { this.cacheTimestamp = Date.now();
this.cacheTimestamp = Date.now();
return it?.data ?? []; return it?.data ?? [];
}); });
this.assessments = this.cache.then(toAssessmentMap); this.assessments = this.cache.then(toAssessmentMap);
return this.cache; return this.cache;

View File

@@ -17,7 +17,7 @@ import {Component, DestroyRef, inject, Input, OnInit, ViewChild} from '@angular/
import {ActivatedRoute} from '@angular/router'; import {ActivatedRoute} from '@angular/router';
import {AssessmentsProvider} from '../assessments.provider'; import {AssessmentsProvider} from '../assessments.provider';
import {DataDetailComponent, ExternalDataLoadEvent} from '../../data/detail/data-detail.component'; import {DataDetailComponent, ExternalDataLoadEvent} from '../../data/detail/data-detail.component';
import {NavController, ViewWillEnter} from '@ionic/angular'; import {NavController} from '@ionic/angular';
import {DataRoutingService} from '../../data/data-routing.service'; import {DataRoutingService} from '../../data/data-routing.service';
import {SCAssessment} from '@openstapps/core'; import {SCAssessment} from '@openstapps/core';
import {takeUntilDestroyed} from '@angular/core/rxjs-interop'; import {takeUntilDestroyed} from '@angular/core/rxjs-interop';
@@ -27,7 +27,7 @@ import {takeUntilDestroyed} from '@angular/core/rxjs-interop';
templateUrl: 'assessments-detail.html', templateUrl: 'assessments-detail.html',
styleUrls: ['assessments-detail.scss'], styleUrls: ['assessments-detail.scss'],
}) })
export class AssessmentsDetailComponent implements ViewWillEnter, OnInit { export class AssessmentsDetailComponent implements OnInit {
destroy$ = inject(DestroyRef); destroy$ = inject(DestroyRef);
constructor( constructor(
@@ -67,8 +67,4 @@ export class AssessmentsDetailComponent implements ViewWillEnter, OnInit {
event.resolve(this.item); event.resolve(this.item);
}); });
} }
async ionViewWillEnter() {
await this.detailComponent.ionViewWillEnter();
}
} }

View File

@@ -61,6 +61,7 @@ export class AssessmentsSimpleDataListComponent implements OnInit {
queryParams: { queryParams: {
token: this.activatedRoute.snapshot.queryParamMap.get('token'), token: this.activatedRoute.snapshot.queryParamMap.get('token'),
}, },
state: {item: thing},
}); });
}); });
} }

View File

@@ -71,6 +71,7 @@ export class AssessmentsPageComponent implements OnInit, AfterViewInit {
queryParams: { queryParams: {
token: this.activatedRoute.snapshot.queryParamMap.get('token'), token: this.activatedRoute.snapshot.queryParamMap.get('token'),
}, },
state: {item: thing},
}); });
}); });

View File

@@ -12,24 +12,18 @@
* You should have received a copy of the GNU General Public License along with * You should have received a copy of the GNU General Public License along with
* this program. If not, see <https://www.gnu.org/licenses/>. * this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
import {Injectable} from '@angular/core'; import {Injectable} from '@angular/core';
import {IPAIAAuthAction} from './paia/paia-auth-action'; import {IPAIAAuthAction} from './paia/paia-auth-action';
import {AuthActions, IAuthAction} from 'ionic-appauth'; import {AuthActions, IAuthAction} from 'ionic-appauth';
import {TranslateService} from '@ngx-translate/core'; import {TranslateService} from '@ngx-translate/core';
import {JSONPath} from 'jsonpath-plus'; import {JSONPath} from 'jsonpath-plus';
import { import {SCAuthorizationProviderType, SCUserConfiguration, SCUserConfigurationMap} from '@openstapps/core';
SCAuthorizationProvider,
SCAuthorizationProviderType,
SCUserConfiguration,
SCUserConfigurationMap,
} from '@openstapps/core';
import {ConfigProvider} from '../config/config.provider';
import {StorageProvider} from '../storage/storage.provider'; import {StorageProvider} from '../storage/storage.provider';
import {DefaultAuthService} from './default-auth.service'; import {DefaultAuthService} from './default-auth.service';
import {PAIAAuthService} from './paia/paia-auth.service'; import {PAIAAuthService} from './paia/paia-auth.service';
import {SimpleBrowser} from '../../util/browser.factory'; import {SimpleBrowser} from '../../util/browser.factory';
import {AlertController} from '@ionic/angular'; import {AlertController} from '@ionic/angular';
import {ConfigProvider} from '../config/config.provider';
const AUTH_ORIGIN_PATH = 'stapps.auth.origin_path'; const AUTH_ORIGIN_PATH = 'stapps.auth.origin_path';
@@ -37,23 +31,19 @@ const AUTH_ORIGIN_PATH = 'stapps.auth.origin_path';
providedIn: 'root', providedIn: 'root',
}) })
export class AuthHelperService { export class AuthHelperService {
userConfigurationMap: SCUserConfigurationMap; get userConfigurationMap(): SCUserConfigurationMap {
return this.config.auth.default!.endpoints.mapping;
}
constructor( constructor(
private translateService: TranslateService, private translateService: TranslateService,
private configProvider: ConfigProvider,
private storageProvider: StorageProvider, private storageProvider: StorageProvider,
private defaultAuth: DefaultAuthService, private defaultAuth: DefaultAuthService,
private paiaAuth: PAIAAuthService, private paiaAuth: PAIAAuthService,
private browser: SimpleBrowser, private browser: SimpleBrowser,
private alertController: AlertController, private alertController: AlertController,
) { private config: ConfigProvider,
this.userConfigurationMap = ( ) {}
this.configProvider.getAnyValue('auth') as {
default: SCAuthorizationProvider;
}
).default.endpoints.mapping;
}
public getAuthMessage(provider: SCAuthorizationProviderType, action: IAuthAction | IPAIAAuthAction) { public getAuthMessage(provider: SCAuthorizationProviderType, action: IAuthAction | IPAIAAuthAction) {
let message: string | undefined; let message: string | undefined;

View File

@@ -175,7 +175,7 @@ export abstract class AuthService implements IAuthService {
public async init() { public async init() {
this.setupAuthorizationNotifier(); this.setupAuthorizationNotifier();
this.loadTokenFromStorage(); await this.loadTokenFromStorage();
this.addActionObserver(this._actionHistory); this.addActionObserver(this._actionHistory);
this.addActionObserver(this._session); this.addActionObserver(this._session);
} }

View File

@@ -12,29 +12,26 @@
* You should have received a copy of the GNU General Public License along with * You should have received a copy of the GNU General Public License along with
* this program. If not, see <https://www.gnu.org/licenses/>. * this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
import { import {
AuthorizationRequestHandler, AuthorizationRequestHandler,
AuthorizationServiceConfiguration, AuthorizationServiceConfiguration,
JQueryRequestor, JQueryRequestor,
LocalStorageBackend, LocalStorageBackend,
Requestor,
StorageBackend,
TokenRequestHandler, TokenRequestHandler,
} from '@openid/appauth'; } from '@openid/appauth';
import {AuthActionBuilder, Browser, DefaultBrowser, EndSessionHandler, UserInfoHandler} from 'ionic-appauth'; import {AuthActionBuilder, DefaultBrowser, EndSessionHandler, UserInfoHandler} from 'ionic-appauth';
import {ConfigProvider} from '../config/config.provider';
import {SCAuthorizationProvider} from '@openstapps/core';
import {getClientConfig, getEndpointsConfig} from './auth.provider.methods'; import {getClientConfig, getEndpointsConfig} from './auth.provider.methods';
import {Injectable} from '@angular/core'; import {Injectable} from '@angular/core';
import {AuthService} from './auth.service'; import {AuthService} from './auth.service';
import {ConfigProvider} from '../config/config.provider';
import {BeforeAppInit} from '../../before-app-init';
const TOKEN_RESPONSE_KEY = 'token_response'; const TOKEN_RESPONSE_KEY = 'token_response';
@Injectable({ @Injectable({
providedIn: 'root', providedIn: 'root',
}) })
export class DefaultAuthService extends AuthService { export class DefaultAuthService extends AuthService implements BeforeAppInit {
public localConfiguration: AuthorizationServiceConfiguration; public localConfiguration: AuthorizationServiceConfiguration;
protected tokenHandler: TokenRequestHandler; protected tokenHandler: TokenRequestHandler;
@@ -45,13 +42,17 @@ export class DefaultAuthService extends AuthService {
protected endSessionHandler: EndSessionHandler; protected endSessionHandler: EndSessionHandler;
constructor( constructor(private config: ConfigProvider) {
protected browser: Browser = new DefaultBrowser(), super(new DefaultBrowser(), new LocalStorageBackend(), new JQueryRequestor());
protected storage: StorageBackend = new LocalStorageBackend(), }
protected requestor: Requestor = new JQueryRequestor(),
private readonly configProvider: ConfigProvider, async beforeAppInit() {
) { this.authConfig = getClientConfig('default', this.config.auth);
super(browser, storage, requestor); this.localConfiguration = new AuthorizationServiceConfiguration(
getEndpointsConfig('default', this.config.auth),
);
await super.init();
} }
get configuration(): Promise<AuthorizationServiceConfiguration> { get configuration(): Promise<AuthorizationServiceConfiguration> {
@@ -60,22 +61,6 @@ export class DefaultAuthService extends AuthService {
return Promise.resolve(this.localConfiguration); return Promise.resolve(this.localConfiguration);
} }
public async init() {
this.setupConfiguration();
this.setupAuthorizationNotifier();
await this.loadTokenFromStorage();
}
setupConfiguration() {
const authConfig = this.configProvider.getAnyValue('auth') as {
default: SCAuthorizationProvider;
};
this.authConfig = getClientConfig('default', authConfig);
this.localConfiguration = new AuthorizationServiceConfiguration(
getEndpointsConfig('default', authConfig),
);
}
public async signOut() { public async signOut() {
await this.revokeTokens().catch(error => { await this.revokeTokens().catch(error => {
this.notifyActionListers(AuthActionBuilder.SignOutFailed(error)); this.notifyActionListers(AuthActionBuilder.SignOutFailed(error));

View File

@@ -12,7 +12,6 @@
* You should have received a copy of the GNU General Public License along with * You should have received a copy of the GNU General Public License along with
* this program. If not, see <https://www.gnu.org/licenses/>. * this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
import { import {
AuthorizationError, AuthorizationError,
AuthorizationRequest, AuthorizationRequest,
@@ -47,10 +46,10 @@ import {PAIAAuthorizationResponse} from './paia-authorization-response';
import {PAIAAuthorizationNotifier} from './paia-authorization-notifier'; import {PAIAAuthorizationNotifier} from './paia-authorization-notifier';
import {PAIATokenResponse} from './paia-token-response'; import {PAIATokenResponse} from './paia-token-response';
import {IPAIAAuthAction, PAIAAuthActionBuilder} from './paia-auth-action'; import {IPAIAAuthAction, PAIAAuthActionBuilder} from './paia-auth-action';
import {SCAuthorizationProvider} from '@openstapps/core';
import {ConfigProvider} from '../../config/config.provider';
import {getClientConfig, getEndpointsConfig} from '../auth.provider.methods'; import {getClientConfig, getEndpointsConfig} from '../auth.provider.methods';
import {Injectable} from '@angular/core'; import {Injectable} from '@angular/core';
import {ConfigProvider} from '../../config/config.provider';
import {BeforeAppInit} from '../../../before-app-init';
const TOKEN_RESPONSE_KEY = 'paia_token_response'; const TOKEN_RESPONSE_KEY = 'paia_token_response';
const AUTH_EXPIRY_BUFFER = 10 * 60 * -1; // 10 minutes in seconds const AUTH_EXPIRY_BUFFER = 10 * 60 * -1; // 10 minutes in seconds
@@ -64,10 +63,8 @@ export interface IAuthService {
getValidToken(buffer?: number): Promise<PAIATokenResponse>; getValidToken(buffer?: number): Promise<PAIATokenResponse>;
} }
@Injectable({ @Injectable({providedIn: 'root'})
providedIn: 'root', export class PAIAAuthService implements BeforeAppInit {
})
export class PAIAAuthService {
private _authConfig?: IAuthConfig; private _authConfig?: IAuthConfig;
private _authSubject: AuthSubject = new AuthSubject(); private _authSubject: AuthSubject = new AuthSubject();
@@ -97,7 +94,7 @@ export class PAIAAuthService {
protected browser: Browser = new DefaultBrowser(), protected browser: Browser = new DefaultBrowser(),
protected storage: StorageBackend = new LocalStorageBackend(), protected storage: StorageBackend = new LocalStorageBackend(),
protected requestor: Requestor = new JQueryRequestor(), protected requestor: Requestor = new JQueryRequestor(),
private readonly configProvider: ConfigProvider, private config: ConfigProvider,
) { ) {
this.tokenHandler = new PAIATokenRequestHandler(requestor); this.tokenHandler = new PAIATokenRequestHandler(requestor);
this.userInfoHandler = new IonicUserInfoHandler(requestor); this.userInfoHandler = new IonicUserInfoHandler(requestor);
@@ -110,6 +107,16 @@ export class PAIAAuthService {
this.endSessionHandler = new IonicEndSessionHandler(browser); this.endSessionHandler = new IonicEndSessionHandler(browser);
} }
async beforeAppInit() {
this.authConfig = getClientConfig('paia', this.config.auth);
this.localConfiguration = new AuthorizationServiceConfiguration(
getEndpointsConfig('paia', this.config.auth),
);
this.setupAuthorizationNotifier();
await this.loadTokenFromStorage();
}
get token$(): Observable<PAIATokenResponse | undefined> { get token$(): Observable<PAIATokenResponse | undefined> {
return this._tokenSubject.asObservable(); return this._tokenSubject.asObservable();
} }
@@ -147,20 +154,6 @@ export class PAIAAuthService {
return Promise.resolve(this.localConfiguration); return Promise.resolve(this.localConfiguration);
} }
public async init() {
this.setupConfiguration();
this.setupAuthorizationNotifier();
await this.loadTokenFromStorage();
}
setupConfiguration() {
const authConfig = this.configProvider.getAnyValue('auth') as {
paia: SCAuthorizationProvider;
};
this.authConfig = getClientConfig('paia', authConfig);
this.localConfiguration = new AuthorizationServiceConfiguration(getEndpointsConfig('paia', authConfig));
}
protected notifyActionListers(action: IPAIAAuthAction) { protected notifyActionListers(action: IPAIAAuthAction) {
/* eslint-disable unicorn/no-useless-undefined */ /* eslint-disable unicorn/no-useless-undefined */
switch (action.action) { switch (action.action) {

View File

@@ -12,7 +12,6 @@
* You should have received a copy of the GNU General Public License along with * You should have received a copy of the GNU General Public License along with
* this program. If not, see <https://www.gnu.org/licenses/>. * this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
import {Calendar} from '@awesome-cordova-plugins/calendar/ngx'; import {Calendar} from '@awesome-cordova-plugins/calendar/ngx';
import {Injectable} from '@angular/core'; import {Injectable} from '@angular/core';
import {ICalEvent} from './ical/ical'; import {ICalEvent} from './ical/ical';
@@ -29,18 +28,18 @@ const RECURRENCE_PATTERNS: Partial<Record<unitOfTime.Diff, string | undefined>>
day: 'daily', day: 'daily',
}; };
@Injectable() @Injectable({providedIn: 'root'})
export class CalendarService { export class CalendarService {
goToDate = new Subject<number>(); goToDate = new Subject<number>();
goToDateClicked = this.goToDate.asObservable(); goToDateClicked = this.goToDate.asObservable();
calendarName = 'StApps'; get calendarName(): string {
return this.config.app.name ?? 'StApps';
}
// eslint-disable-next-line @typescript-eslint/no-empty-function // eslint-disable-next-line @typescript-eslint/no-empty-function
constructor(readonly calendar: Calendar, private readonly configProvider: ConfigProvider) { constructor(readonly calendar: Calendar, readonly config: ConfigProvider) {}
this.calendarName = (this.configProvider.getValue('name') as string) ?? 'StApps';
}
async createCalendar(): Promise<CalendarInfo | undefined> { async createCalendar(): Promise<CalendarInfo | undefined> {
await this.calendar.createCalendar({ await this.calendar.createCalendar({

View File

@@ -65,7 +65,7 @@ export class CatalogComponent implements OnInit {
.itemSelectListener() .itemSelectListener()
.pipe(takeUntilDestroyed()) .pipe(takeUntilDestroyed())
.subscribe(item => { .subscribe(item => {
void this.router.navigate(['data-detail', item.uid]); void this.router.navigate(['data-detail', item.uid], {state: {item}});
}); });
} }

View File

@@ -1,27 +0,0 @@
/*
* Copyright (C) 2019 StApps
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <https://www.gnu.org/licenses/>.
*/
import {NgModule} from '@angular/core';
import {DataModule} from '../data/data.module';
import {StorageModule} from '../storage/storage.module';
import {ConfigProvider} from './config.provider';
/**
* TODO
*/
@NgModule({
imports: [StorageModule, DataModule],
providers: [ConfigProvider],
})
export class ConfigModule {}

View File

@@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/ban-types */
/* /*
* Copyright (C) 2022 StApps * Copyright (C) 2022 StApps
* This program is free software: you can redistribute it and/or modify it * This program is free software: you can redistribute it and/or modify it
@@ -14,19 +15,17 @@
*/ */
import {Injectable} from '@angular/core'; import {Injectable} from '@angular/core';
import {Client} from '@openstapps/api'; import {Client} from '@openstapps/api';
import {SCAppConfiguration, SCIndexResponse} from '@openstapps/core';
import packageInfo from '@openstapps/core/package.json';
import {NGXLogger} from 'ngx-logger';
import {environment} from '../../../environments/environment';
import {StAppsWebHttpClient} from '../data/stapps-web-http-client.provider';
import {StorageProvider} from '../storage/storage.provider';
import { import {
ConfigFetchError, SCAppConfiguration,
ConfigInitError, SCAuthorizationProvider,
ConfigValueNotAvailable, SCBackendConfiguration,
SavedConfigNotAvailable, SCIndexResponse,
WrongConfigVersionInStorage, } from '@openstapps/core';
} from './errors'; import coreInfo from '@openstapps/core/package.json';
import {environment} from '../../../environments/environment';
import {StorageProvider} from '../storage/storage.provider';
import {BeforeAppInit} from '../../before-app-init';
import {StAppsWebHttpClient} from '../data/stapps-web-http-client.provider';
/** /**
* Key to store config in storage module * Key to store config in storage module
@@ -35,145 +34,55 @@ import {
*/ */
export const STORAGE_KEY_CONFIG = 'stapps.config'; export const STORAGE_KEY_CONFIG = 'stapps.config';
/**
* Provides configuration
*/
@Injectable({ @Injectable({
providedIn: 'root', providedIn: 'root',
}) })
export class ConfigProvider { export class ConfigProvider implements SCIndexResponse, BeforeAppInit {
/** private client: Client;
* Api client
*/
client: Client;
/** constructor(private storageProvider: StorageProvider, httpClient: StAppsWebHttpClient) {
* App configuration as IndexResponse this.client = new Client(httpClient, environment.backend_url, environment.backend_version);
*/ }
config: SCIndexResponse;
/** async beforeAppInit() {
* Version of the @openstapps/core package that app is using this.isFirstSession = !(await this.storageProvider.has(STORAGE_KEY_CONFIG));
*/ // Queue config update for next launch; don't block current launch
scVersion = packageInfo.version; const configUpdate = this.updateConfig();
console.log('Config update queued');
/** const config = await this.storageProvider
* First session indicator (config not found in storage) .get<SCIndexResponse>(STORAGE_KEY_CONFIG)
*/ .then(it => it ?? configUpdate);
firstSession = true;
/** Object.assign(this, config);
* Constructor, initialise api client
* @param storageProvider StorageProvider to load persistent configuration console.assert(
* @param swHttpClient Api client this.backend.SCVersion === coreInfo.version,
* @param logger An angular logger 'Wrong config version in storage.',
*/ 'Expected:',
constructor( coreInfo.version,
private readonly storageProvider: StorageProvider, 'Actual:',
swHttpClient: StAppsWebHttpClient, this.backend.SCVersion,
private readonly logger: NGXLogger, );
) {
this.client = new Client(swHttpClient, environment.backend_url, environment.backend_version);
} }
/** /**
* Fetches configuration from backend * Updates the config from remote
*/ */
async fetch(): Promise<SCIndexResponse> { async updateConfig(): Promise<SCIndexResponse> {
try { const config = await this.client.handshake(coreInfo.version);
return await this.client.handshake(this.scVersion);
} catch {
throw new ConfigFetchError();
}
}
/**
* Returns the value of an app configuration
* @param attribute requested attribute from app configuration
*/
public getValue(attribute: keyof SCAppConfiguration) {
if (this.config.app[attribute] !== undefined) {
return this.config.app[attribute];
}
throw new ConfigValueNotAvailable(attribute);
}
/**
* Returns a value of the configuration (not only app configuration)
* @param attribute requested attribute from the configuration
*/
public getAnyValue(attribute: keyof SCIndexResponse) {
if (this.config[attribute] !== undefined) {
return this.config[attribute];
}
throw new ConfigValueNotAvailable(attribute);
}
/**
* Initialises the ConfigProvider
* @throws ConfigInitError if no configuration could be loaded.
* @throws WrongConfigVersionInStorage if fetch failed and saved config has wrong SCVersion
*/
async init(): Promise<void> {
let loadError;
let fetchError;
// load saved configuration
try {
this.config = await this.loadLocal();
this.firstSession = false;
this.logger.log(`initialised configuration from storage`);
if (this.config.backend.SCVersion !== this.scVersion) {
loadError = new WrongConfigVersionInStorage(this.scVersion, this.config.backend.SCVersion);
}
} catch (error) {
loadError = error;
}
// fetch remote configuration from backend
try {
const fetchedConfig: SCIndexResponse = await this.fetch();
await this.set(fetchedConfig);
this.logger.log(`initialised configuration from remote`);
} catch (error) {
fetchError = error;
}
// check for occurred errors and throw them
if (loadError !== undefined && fetchError !== undefined) {
throw new ConfigInitError();
}
if (loadError !== undefined) {
this.logger.warn(loadError);
}
if (fetchError !== undefined) {
this.logger.warn(fetchError);
}
}
/**
* Returns saved configuration from StorageModule
* @throws SavedConfigNotAvailable if no configuration could be loaded
*/
async loadLocal(): Promise<SCIndexResponse> {
// get local configuration
if (await this.storageProvider.has(STORAGE_KEY_CONFIG)) {
return this.storageProvider.get<SCIndexResponse>(STORAGE_KEY_CONFIG);
}
throw new SavedConfigNotAvailable();
}
/**
* Saves the configuration from the provider
* @param config configuration to save
*/
async save(config: SCIndexResponse): Promise<void> {
await this.storageProvider.put(STORAGE_KEY_CONFIG, config); await this.storageProvider.put(STORAGE_KEY_CONFIG, config);
console.log(`Config updated`);
return config;
} }
/** app: SCAppConfiguration;
* Sets the configuration in the module and writes it into app storage
* @param config SCIndexResponse to set auth: {default?: SCAuthorizationProvider | undefined; paia?: SCAuthorizationProvider | undefined};
*/
async set(config: SCIndexResponse): Promise<void> { backend: SCBackendConfiguration;
this.config = config;
await this.save(this.config); isFirstSession: boolean;
}
} }

View File

@@ -1,65 +0,0 @@
/*
* Copyright (C) 2022 StApps
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <https://www.gnu.org/licenses/>.
*/
import {AppError} from '../../_helpers/errors';
/**
* Error that is thrown when fetching from backend fails
*/
export class ConfigFetchError extends AppError {
constructor() {
super('ConfigFetchError', 'App configuration could not be fetched!');
}
}
/**
* Error that is thrown when the ConfigProvider could be initialised
*/
export class ConfigInitError extends AppError {
constructor() {
super('ConfigInitError', 'App configuration could not be initialised!');
}
}
/**
* Error that is thrown when the requested config value is not available
*/
export class ConfigValueNotAvailable extends AppError {
constructor(valueKey: string) {
super('ConfigValueNotAvailable', `No attribute "${valueKey}" in config available!`);
}
}
/**
* Error that is thrown when no saved config is available
*/
export class SavedConfigNotAvailable extends AppError {
constructor() {
super('SavedConfigNotAvailable', 'No saved app configuration available.');
}
}
/**
* Error that is thrown when the SCVersion of the saved config is not compatible with the app
*/
export class WrongConfigVersionInStorage extends AppError {
constructor(correctVersion: string, savedVersion: string) {
super(
'WrongConfigVersionInStorage',
`The saved configs backend version ${savedVersion} ` +
`does not equal the configured backend version ${correctVersion} of the app.`,
);
}
}

View File

@@ -19,19 +19,20 @@
</ion-toolbar> </ion-toolbar>
</ion-header> </ion-header>
<div #schedule class="schedule"> <div #schedule class="schedule">
<a [routerLink]="['/schedule/recurring']"> <a [routerLink]="['/schedule/week-overview']">
<ion-icon size="40" weight="300" name="grid_view"></ion-icon> <ion-icon size="36" weight="300" name="calendar_month"></ion-icon>
<ion-label>{{ 'schedule.recurring' | translate }}</ion-label> <ion-label [innerHTML]="'schedule.recurring' | translate"></ion-label>
</a> </a>
<!-- Avoid structural directives here, they might interfere with the collapse animation --> <!-- Avoid structural directives here, they might interfere with the collapse animation -->
<a <a
[routerLink]="nextEvent?.event ? ['/data-detail', nextEvent!.event.uid] : ['/schedule/recurring']" [routerLink]="nextEvent ? ['/data-detail', nextEvent!.uid] : ['/schedule/calendar']"
[state]="{item: nextEvent}"
class="schedule-item-button" class="schedule-item-button"
> >
<ion-label>{{ 'dashboard.schedule.title' | translate }}</ion-label> <ion-label>{{ 'dashboard.schedule.title' | translate }}</ion-label>
<ion-label> <ion-label>
{{ {{
nextEvent?.event nextEvent
? (nextEvent!.dates | nextDateInList | amDateFormat : 'll, HH:mm') ? (nextEvent!.dates | nextDateInList | amDateFormat : 'll, HH:mm')
: ('dashboard.schedule.noEvent' | translate) : ('dashboard.schedule.noEvent' | translate)
}} }}

View File

@@ -117,6 +117,7 @@ ion-content {
ion-label { ion-label {
font-size: var(--font-size-xxs); font-size: var(--font-size-xxs);
font-weight: var(--font-weight-semi-bold); font-weight: var(--font-weight-semi-bold);
word-break: break-word;
} }
&:hover ::ng-deep stapps-icon { &:hover ::ng-deep stapps-icon {

View File

@@ -76,7 +76,7 @@ export class DashboardComponent implements OnInit, OnDestroy {
.itemSelectListener() .itemSelectListener()
.pipe(takeUntilDestroyed()) .pipe(takeUntilDestroyed())
.subscribe(item => { .subscribe(item => {
void this.router.navigate(['data-detail', item.uid]); void this.router.navigate(['data-detail', item.uid], {state: {item}});
}); });
} }

View File

@@ -18,7 +18,6 @@
<stapps-data-list-item <stapps-data-list-item
*ngFor="let dish of dishes" *ngFor="let dish of dishes"
[hideThumbnail]="true" [hideThumbnail]="true"
[favoriteButton]="false"
[item]="dish" [item]="dish"
appearance="square" appearance="square"
></stapps-data-list-item> ></stapps-data-list-item>

View File

@@ -42,6 +42,7 @@ export class ActionChipListComponent {
event: event:
item.type === SCThingType.AcademicEvent || item.type === SCThingType.AcademicEvent ||
(item.type === SCThingType.DateSeries && (item as SCDateSeries).dates.length > 0), (item.type === SCThingType.DateSeries && (item as SCDateSeries).dates.length > 0),
navigate: ('inPlace' in item && item.inPlace && 'geo' in item.inPlace) || 'geo' in item,
}; };
} }

View File

@@ -14,5 +14,6 @@
--> -->
<stapps-locate-action-chip *ngIf="applicable.locate" [item]="item"></stapps-locate-action-chip> <stapps-locate-action-chip *ngIf="applicable.locate" [item]="item"></stapps-locate-action-chip>
<stapps-navigate-action-chip *ngIf="applicable.navigate" [item]="$any(item)"></stapps-navigate-action-chip>
<!-- Add Event Chip needs to load data and should be the last --> <!-- Add Event Chip needs to load data and should be the last -->
<stapps-add-event-action-chip *ngIf="applicable.event" [item]="item"></stapps-add-event-action-chip> <stapps-add-event-action-chip *ngIf="applicable.event" [item]="item"></stapps-add-event-action-chip>

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright (C) 2021 StApps * Copyright (C) 2023 StApps
* This program is free software: you can redistribute it and/or modify it * This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free * under the terms of the GNU General Public License as published by the Free
* Software Foundation, version 3. * Software Foundation, version 3.
@@ -13,19 +13,23 @@
* this program. If not, see <https://www.gnu.org/licenses/>. * this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
import {Component, Input} from '@angular/core'; import {Component, Input} from '@angular/core';
import {SCPlace} from '@openstapps/core'; import {SCPlaceWithoutReferences, SCThings} from '@openstapps/core';
import {ModalController} from '@ionic/angular';
@Component({ @Component({
selector: 'app-map-single-modal', selector: 'stapps-navigate-action-chip',
templateUrl: './map-single.html', templateUrl: 'navigate-action-chip.html',
styleUrls: ['./map-single.scss'], styleUrls: ['navigate-action-chip.scss'],
}) })
export class MapSingleModalComponent { export class NavigateActionChipComponent {
/** place: SCPlaceWithoutReferences;
* The item to be shown
*/
@Input() item: SCPlace;
constructor(readonly modalController: ModalController) {} @Input({required: true}) set item(value: SCThings) {
if ('geo' in value) {
this.place = value;
} else if ('inPlace' in value && value.inPlace && 'geo' in value.inPlace) {
this.place = value.inPlace;
} else {
console.error('Invalid place', value);
}
}
} }

View File

@@ -1,5 +1,5 @@
<!-- <!--
~ Copyright (C) 2022 StApps ~ Copyright (C) 2023 StApps
~ This program is free software: you can redistribute it and/or modify it ~ This program is free software: you can redistribute it and/or modify it
~ under the terms of the GNU General Public License as published by the Free ~ under the terms of the GNU General Public License as published by the Free
~ Software Foundation, version 3. ~ Software Foundation, version 3.
@@ -12,15 +12,7 @@
~ You should have received a copy of the GNU General Public License along with ~ You should have received a copy of the GNU General Public License along with
~ this program. If not, see <https://www.gnu.org/licenses/>. ~ this program. If not, see <https://www.gnu.org/licenses/>.
--> -->
<ion-chip [color]="'primary'" [outline]="true" [geoNavigation]="place">
<ion-header translucent> <ion-icon name="directions"></ion-icon>
<ion-toolbar color="primary" mode="ios"> <ion-label>{{'map.directions.TITLE' | translate}}</ion-label>
<ion-title>{{ 'map.modals.single.TITLE' | translate }}</ion-title> </ion-chip>
<ion-buttons slot="end">
<ion-button (click)="modalController.dismiss()">{{ 'app.ui.CLOSE' | translate }}</ion-button>
</ion-buttons>
</ion-toolbar>
</ion-header>
<ion-content>
<stapps-data-detail-content [item]="$any(item)" [openAsModal]="true"></stapps-data-detail-content>
</ion-content>

View File

@@ -1,5 +1,5 @@
/* /*!
* Copyright (C) 2020 StApps * Copyright (C) 2023 StApps
* This program is free software: you can redistribute it and/or modify it * This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free * under the terms of the GNU General Public License as published by the Free
* Software Foundation, version 3. * Software Foundation, version 3.
@@ -12,8 +12,3 @@
* You should have received a copy of the GNU General Public License along with * You should have received a copy of the GNU General Public License along with
* this program. If not, see <https://www.gnu.org/licenses/>. * this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
import {NGXLogger} from 'ngx-logger';
export let logger: NGXLogger;
export const initLogger = (newLogger: NGXLogger) => (logger = newLogger);

View File

@@ -102,6 +102,8 @@ import {StappsRatingComponent} from './elements/rating.component';
import {DishCharacteristicsComponent} from './types/dish/dish-characteristics.component'; import {DishCharacteristicsComponent} from './types/dish/dish-characteristics.component';
import {SkeletonListComponent} from './list/skeleton-list.component'; import {SkeletonListComponent} from './list/skeleton-list.component';
import {CertificationsInDetailComponent} from './elements/certifications-in-detail.component'; import {CertificationsInDetailComponent} from './elements/certifications-in-detail.component';
import {GeoNavigationDirective} from '../map/geo-navigation.directive';
import {NavigateActionChipComponent} from './chips/data/navigate-action-chip.component';
/** /**
* Module for handling data * Module for handling data
@@ -110,6 +112,7 @@ import {CertificationsInDetailComponent} from './elements/certifications-in-deta
declarations: [ declarations: [
ActionChipListComponent, ActionChipListComponent,
AddEventActionChipComponent, AddEventActionChipComponent,
NavigateActionChipComponent,
EditEventSelectionComponent, EditEventSelectionComponent,
AddressDetailComponent, AddressDetailComponent,
CatalogDetailContentComponent, CatalogDetailContentComponent,
@@ -194,6 +197,7 @@ import {CertificationsInDetailComponent} from './elements/certifications-in-deta
TranslateModule.forChild(), TranslateModule.forChild(),
ThingTranslateModule.forChild(), ThingTranslateModule.forChild(),
UtilModule, UtilModule,
GeoNavigationDirective,
], ],
providers: [ providers: [
CoordinatedSearchProvider, CoordinatedSearchProvider,

View File

@@ -111,8 +111,8 @@ describe('DataDetailComponent', () => {
expect(DataDetailComponent.prototype.getItem).toHaveBeenCalledWith(sampleThing.uid, false); expect(DataDetailComponent.prototype.getItem).toHaveBeenCalledWith(sampleThing.uid, false);
}); });
it('should get a data item when the view is entered', () => { it('should get a data item when initialized', () => {
comp.ionViewWillEnter(); comp.ngOnInit();
expect(DataDetailComponent.prototype.getItem).toHaveBeenCalledWith(sampleThing.uid, false); expect(DataDetailComponent.prototype.getItem).toHaveBeenCalledWith(sampleThing.uid, false);
}); });
}); });

View File

@@ -12,9 +12,9 @@
* You should have received a copy of the GNU General Public License along with * You should have received a copy of the GNU General Public License along with
* this program. If not, see <https://www.gnu.org/licenses/>. * this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
import {Component, ContentChild, EventEmitter, Input, Output, TemplateRef} from '@angular/core'; import {Component, ContentChild, EventEmitter, Input, OnInit, Output, TemplateRef} from '@angular/core';
import {ActivatedRoute} from '@angular/router'; import {ActivatedRoute, Router} from '@angular/router';
import {ModalController, ViewWillEnter} from '@ionic/angular'; import {ModalController} from '@ionic/angular';
import {LangChangeEvent, TranslateService} from '@ngx-translate/core'; import {LangChangeEvent, TranslateService} from '@ngx-translate/core';
import {SCLanguageCode, SCSaveableThing, SCThings, SCUuid} from '@openstapps/core'; import {SCLanguageCode, SCSaveableThing, SCThings, SCUuid} from '@openstapps/core';
import {DataProvider, DataScope} from '../data.provider'; import {DataProvider, DataScope} from '../data.provider';
@@ -37,7 +37,7 @@ export interface ExternalDataLoadEvent {
styleUrls: ['data-detail.scss'], styleUrls: ['data-detail.scss'],
templateUrl: 'data-detail.html', templateUrl: 'data-detail.html',
}) })
export class DataDetailComponent implements ViewWillEnter { export class DataDetailComponent implements OnInit {
/** /**
* The associated item * The associated item
* *
@@ -84,21 +84,15 @@ export class DataDetailComponent implements ViewWillEnter {
return (thing as SCSaveableThing).data !== undefined; return (thing as SCSaveableThing).data !== undefined;
} }
/**
*
* @param route the route the page was accessed from
* @param dataProvider the data provider
* @param favoritesService the favorites provider
* @param modalController the modal controller
* @param translateService he translate provider
*/
constructor( constructor(
protected readonly route: ActivatedRoute, protected readonly route: ActivatedRoute,
router: Router,
private readonly dataProvider: DataProvider, private readonly dataProvider: DataProvider,
private readonly favoritesService: FavoritesService, private readonly favoritesService: FavoritesService,
readonly modalController: ModalController, readonly modalController: ModalController,
translateService: TranslateService, translateService: TranslateService,
) { ) {
this.inputItem = router.getCurrentNavigation()?.extras.state?.item;
this.language = translateService.currentLang as SCLanguageCode; this.language = translateService.currentLang as SCLanguageCode;
translateService.onLangChange.subscribe((event: LangChangeEvent) => { translateService.onLangChange.subscribe((event: LangChangeEvent) => {
this.language = event.lang as SCLanguageCode; this.language = event.lang as SCLanguageCode;
@@ -138,10 +132,7 @@ export class DataDetailComponent implements ViewWillEnter {
} }
} }
/** async ngOnInit() {
* Initialize
*/
async ionViewWillEnter() {
const uid = this.route.snapshot.paramMap.get('uid') || ''; const uid = this.route.snapshot.paramMap.get('uid') || '';
await this.getItem(uid ?? '', false); await this.getItem(uid ?? '', false);
// fallback to the saved item (from favorites) // fallback to the saved item (from favorites)

View File

@@ -37,32 +37,22 @@ export class DataPathComponent implements OnInit {
@Input() maxItems = 2; @Input() maxItems = 2;
@Input() set item(item: SCThings) { @Input() set item(item: SCThings) {
// eslint-disable-next-line unicorn/prefer-ternary
if (item.type === SCThingType.Catalog && item.superCatalogs) { if (item.type === SCThingType.Catalog && item.superCatalogs) {
this.path = new Promise(resolve => this.path = Promise.resolve([...item.superCatalogs!, item]);
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
resolve([...item.superCatalogs!, item]),
);
} else if (item.type === SCThingType.Assessment && item.superAssessments) { } else if (item.type === SCThingType.Assessment && item.superAssessments) {
this.path = new Promise(resolve => this.path = Promise.resolve([...item.superAssessments!, item]);
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
resolve([...item.superAssessments!, item]),
);
} else if ( } else if (
item.type === SCThingType.AcademicEvent && item.type === SCThingType.AcademicEvent &&
item.catalogs && item.catalogs &&
(item.catalogs.length === 1 || this.routeStack.lastDataDetail) (item.catalogs.length === 1 || this.routeStack.lastDataDetail)
) { ) {
const catalogWithoutReferences = item.catalogs[0];
const catalogPromise = (
item.catalogs.length === 1
? this.dataProvider.get(catalogWithoutReferences.uid, DataScope.Remote)
: this.routeStack.lastDataDetail
) as Promise<SCCatalog>;
this.path = new Promise(async resolve => { this.path = new Promise(async resolve => {
const catalog = await catalogPromise; const catalogWithoutReferences = item.catalogs![0];
const superCatalogs = catalog.superCatalogs; const catalog =
item.catalogs!.length === 1
? await this.dataProvider.get(catalogWithoutReferences.uid, DataScope.Remote)
: this.routeStack.lastDataDetail;
const superCatalogs = (catalog as SCCatalog).superCatalogs;
resolve( resolve(
superCatalogs superCatalogs

View File

@@ -30,9 +30,8 @@ export class OffersInListComponent {
@Input() set offers(it: Array<SCThingThatCanBeOfferedOffer<SCAcademicPriceGroup>>) { @Input() set offers(it: Array<SCThingThatCanBeOfferedOffer<SCAcademicPriceGroup>>) {
this._offers = it; this._offers = it;
this.price = it[0].prices?.default; this.price = it[0].prices?.default;
this.settingsProvider.getSetting('profile', 'group').then(group => { const group = this.settingsProvider.getSetting('profile', 'group');
this.price = it[0].prices?.[(group.value as string).replace(/s$/, '') as never]; this.price = it[0].prices?.[(group.value as string).replace(/s$/, '') as never];
});
const availabilities = new Set(it.map(offer => offer.availability)); const availabilities = new Set(it.map(offer => offer.availability));
this.soldOut = availabilities.has('out of stock') && availabilities.size === 1; this.soldOut = availabilities.has('out of stock') && availabilities.size === 1;

View File

@@ -1,3 +1,4 @@
/* eslint-disable unicorn/no-useless-undefined */
/* /*
* Copyright (C) 2023 StApps * Copyright (C) 2023 StApps
* This program is free software: you can redistribute it and/or modify it * This program is free software: you can redistribute it and/or modify it
@@ -12,60 +13,51 @@
* You should have received a copy of the GNU General Public License along with * You should have received a copy of the GNU General Public License along with
* this program. If not, see <https://www.gnu.org/licenses/>. * this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
import {Component, ElementRef, HostListener, Input} from '@angular/core'; import {ChangeDetectionStrategy, Component, ElementRef, HostListener, Input} from '@angular/core';
import {SCDish, SCRatingRequest, SCUuid} from '@openstapps/core'; import {SCDish, SCRatingRequest} from '@openstapps/core';
import {RatingProvider} from '../rating.provider'; import {RatingProvider} from '../rating.provider';
import {ratingAnimation} from './rating.animation'; import {ratingAnimation} from './rating.animation';
import {BehaviorSubject, filter, merge, mergeMap, of, ReplaySubject, withLatestFrom} from 'rxjs';
import {catchError, map} from 'rxjs/operators';
@Component({ @Component({
selector: 'stapps-rating', selector: 'stapps-rating',
templateUrl: 'rating.html', templateUrl: 'rating.html',
styleUrls: ['rating.scss'], styleUrls: ['rating.scss'],
animations: [ratingAnimation], animations: [ratingAnimation],
changeDetection: ChangeDetectionStrategy.OnPush,
}) })
export class StappsRatingComponent { export class StappsRatingComponent {
rate = false; performRating = new BehaviorSubject(false);
rated = false; userRating = new BehaviorSubject<number | undefined>(undefined);
canBeRated = false; dish = new ReplaySubject<SCDish>(1);
uid: SCUuid; wasAlreadyRated = merge(
this.dish.pipe(mergeMap(({uid}) => this.ratingProvider.hasRated(uid))),
this.userRating.pipe(
filter(it => it !== undefined),
withLatestFrom(this.dish),
mergeMap(([rating, {uid}]) => this.ratingProvider.rate(uid, rating as SCRatingRequest['rating'])),
map(() => true),
catchError(() => of(false)),
),
);
rating?: number; canBeRated = this.dish.pipe(mergeMap(dish => this.ratingProvider.canRate(dish)));
@Input() set item(value: SCDish) { @Input({required: true}) set item(value: SCDish) {
this.uid = value.uid; this.dish.next(value);
Promise.all([this.ratingProvider.canRate(value), this.ratingProvider.hasRated(this.uid)] as const).then(
([canRate, hasRated]) => {
this.canBeRated = canRate;
this.rated = hasRated;
},
);
} }
constructor(readonly elementRef: ElementRef, readonly ratingProvider: RatingProvider) {} constructor(readonly elementRef: ElementRef, readonly ratingProvider: RatingProvider) {}
async submitRating(rating: number) {
this.rating = rating;
try {
await this.ratingProvider.rate(this.uid, rating as SCRatingRequest['rating']);
this.rated = true;
} catch {
this.rating = undefined;
// allow change detection to catch up first
setTimeout(() => {
this.rate = false;
});
}
}
@HostListener('document:mousedown', ['$event']) @HostListener('document:mousedown', ['$event'])
clickOutside(event: MouseEvent) { clickOutside(event: MouseEvent) {
if (this.rating) return; if (this.userRating.value) return;
if (!this.elementRef.nativeElement.contains(event.target)) { if (!this.elementRef.nativeElement.contains(event.target)) {
this.rate = false; this.performRating.next(false);
} }
} }
} }

View File

@@ -14,19 +14,23 @@
--> -->
<ion-button <ion-button
*ngIf="canBeRated" *ngIf="canBeRated | async"
fill="clear" fill="clear"
(click)="$event.stopPropagation(); rate = true" (click)="$event.stopPropagation(); performRating.next(true)"
[disabled]="rated" [disabled]="wasAlreadyRated | async"
> >
<ion-icon slot="icon-only" color="medium" name="thumbs_up_down"></ion-icon> <ion-icon slot="icon-only" color="medium" name="thumbs_up_down"></ion-icon>
</ion-button> </ion-button>
<div class="rating-stars" *ngIf="rate && !rated" [@rating]="rating ? 'rated' : 'abandoned'"> <div
class="rating-stars"
*ngIf="(performRating | async) && (wasAlreadyRated | async) !== true"
[@rating]="(userRating | async) === undefined ? 'abandoned' : 'rated'"
>
<ion-icon <ion-icon
[class.rated-value]="rating === i" [class.rated-value]="(userRating | async) === i"
*ngFor="let i of [5, 4, 3, 2, 1]" *ngFor="let i of [5, 4, 3, 2, 1]"
(click)="$event.stopPropagation(); submitRating(i)" (click)="$event.stopPropagation(); userRating.next(i)"
slot="icon-only" slot="icon-only"
size="32" size="32"
color="medium" color="medium"

View File

@@ -38,6 +38,8 @@ export class DataListItemComponent {
@Input() listItemEndInteraction = true; @Input() listItemEndInteraction = true;
@Input() listItemChipInteraction = true;
@Input() lines = 'inset'; @Input() lines = 'inset';
@Input() forceHeight = false; @Input() forceHeight = false;

View File

@@ -43,7 +43,7 @@
<div> <div>
<ng-template [dataListItemHost]="item"></ng-template> <ng-template [dataListItemHost]="item"></ng-template>
<stapps-action-chip-list <stapps-action-chip-list
*ngIf="appearance !== 'square'" *ngIf="listItemChipInteraction && appearance !== 'square'"
slot="end" slot="end"
[item]="item" [item]="item"
></stapps-action-chip-list> ></stapps-action-chip-list>

View File

@@ -17,7 +17,7 @@ import {MapPosition} from '../../map/position.service';
import {SearchPageComponent} from './search-page.component'; import {SearchPageComponent} from './search-page.component';
import {Geolocation} from '@capacitor/geolocation'; import {Geolocation} from '@capacitor/geolocation';
import {BehaviorSubject} from 'rxjs'; import {BehaviorSubject} from 'rxjs';
import {pauseWhen} from '../../../util/pause-when'; import {pauseWhen} from '../../../util/rxjs/pause-when';
import {takeUntilDestroyed} from '@angular/core/rxjs-interop'; import {takeUntilDestroyed} from '@angular/core/rxjs-interop';
/** /**

View File

@@ -15,16 +15,9 @@
import {Component, DestroyRef, inject, Input, OnInit} from '@angular/core'; import {Component, DestroyRef, inject, Input, OnInit} from '@angular/core';
import {ActivatedRoute, Router} from '@angular/router'; import {ActivatedRoute, Router} from '@angular/router';
import {Keyboard} from '@capacitor/keyboard'; import {Keyboard} from '@capacitor/keyboard';
import {AlertController, AnimationBuilder, AnimationController} from '@ionic/angular'; import {AlertController, AnimationController} from '@ionic/angular';
import {Capacitor} from '@capacitor/core'; import {Capacitor} from '@capacitor/core';
import { import {SCFacet, SCSearchFilter, SCSearchQuery, SCSearchSort, SCThings} from '@openstapps/core';
SCFacet,
SCFeatureConfiguration,
SCSearchFilter,
SCSearchQuery,
SCSearchSort,
SCThings,
} from '@openstapps/core';
import {NGXLogger} from 'ngx-logger'; import {NGXLogger} from 'ngx-logger';
import {combineLatest, Subject} from 'rxjs'; import {combineLatest, Subject} from 'rxjs';
import {debounceTime, distinctUntilChanged, startWith} from 'rxjs/operators'; import {debounceTime, distinctUntilChanged, startWith} from 'rxjs/operators';
@@ -33,9 +26,9 @@ import {SettingsProvider} from '../../settings/settings.provider';
import {DataRoutingService} from '../data-routing.service'; import {DataRoutingService} from '../data-routing.service';
import {DataProvider} from '../data.provider'; import {DataProvider} from '../data.provider';
import {PositionService} from '../../map/position.service'; import {PositionService} from '../../map/position.service';
import {ConfigProvider} from '../../config/config.provider';
import {searchPageSwitchAnimation} from './search-page-switch-animation'; import {searchPageSwitchAnimation} from './search-page-switch-animation';
import {takeUntilDestroyed} from '@angular/core/rxjs-interop'; import {takeUntilDestroyed} from '@angular/core/rxjs-interop';
import {ConfigProvider} from '../../config/config.provider';
/** /**
* SearchPageComponent queries things and shows list of things as search results and filter as context menu * SearchPageComponent queries things and shows list of things as search results and filter as context menu
@@ -144,21 +137,8 @@ export class SearchPageComponent implements OnInit {
destroy$ = inject(DestroyRef); destroy$ = inject(DestroyRef);
routeAnimation: AnimationBuilder; routeAnimation = searchPageSwitchAnimation(inject(AnimationController));
/**
* Injects the providers and creates subscriptions
* @param alertController AlertController
* @param dataProvider DataProvider
* @param contextMenuService ContextMenuService
* @param settingsProvider SettingsProvider
* @param logger An angular logger
* @param dataRoutingService DataRoutingService
* @param router Router
* @param route ActivatedRoute
* @param positionService PositionService
* @param configProvider ConfigProvider
*/
constructor( constructor(
protected readonly alertController: AlertController, protected readonly alertController: AlertController,
protected dataProvider: DataProvider, protected dataProvider: DataProvider,
@@ -169,11 +149,8 @@ export class SearchPageComponent implements OnInit {
protected router: Router, protected router: Router,
private readonly route: ActivatedRoute, private readonly route: ActivatedRoute,
protected positionService: PositionService, protected positionService: PositionService,
private readonly configProvider: ConfigProvider, private readonly config: ConfigProvider,
animationController: AnimationController, ) {}
) {
this.routeAnimation = searchPageSwitchAnimation(animationController);
}
/** /**
* Fetches items with set query configuration * Fetches items with set query configuration
@@ -342,13 +319,12 @@ export class SearchPageComponent implements OnInit {
.pipe(takeUntilDestroyed(this.destroy$)) .pipe(takeUntilDestroyed(this.destroy$))
.subscribe(item => { .subscribe(item => {
if (this.itemRouting) { if (this.itemRouting) {
void this.router.navigate(['/data-detail', item.uid]); void this.router.navigate(['/data-detail', item.uid], {state: {item}});
} }
}); });
} }
try { try {
const features = this.configProvider.getValue('features') as SCFeatureConfiguration; this.isHebisAvailable = !!this.config.app.features.plugins?.['hebis-plugin']?.urlPath;
this.isHebisAvailable = !!features.plugins?.['hebis-plugin']?.urlPath;
} catch (error) { } catch (error) {
this.logger.error(error); this.logger.error(error);
} }

View File

@@ -61,7 +61,7 @@ export class SimpleDataListComponent implements OnInit {
.itemSelectListener() .itemSelectListener()
.pipe(takeUntilDestroyed(this.destroy$)) .pipe(takeUntilDestroyed(this.destroy$))
.subscribe(item => { .subscribe(item => {
void this.router.navigate(['/data-detail', item.uid]); void this.router.navigate(['/data-detail', item.uid], {state: {item}});
}); });
} }
} }

View File

@@ -13,16 +13,16 @@
~ this program. If not, see <https://www.gnu.org/licenses/>. ~ this program. If not, see <https://www.gnu.org/licenses/>.
--> -->
<ng-container *ngIf="items as items; else loading"> <ng-container *ngIf="items | async as items; else loading">
<ion-list> <ion-list>
<ng-container *ngIf="!listHeader; else header"></ng-container> <ng-container *ngIf="!listHeader; else header"></ng-container>
<ng-container *ngFor="let item of items | async"> <ng-container *ngFor="let item of items">
<ng-container <ng-container
*ngTemplateOutlet="listItemTemplateRef || defaultListItem; context: {$implicit: item}" *ngTemplateOutlet="listItemTemplateRef || defaultListItem; context: {$implicit: item}"
></ng-container> ></ng-container>
</ng-container> </ng-container>
</ion-list> </ion-list>
<ion-label class="empty-list-message" *ngIf="emptyListMessage && (items | async)?.length === 0" <ion-label class="empty-list-message" *ngIf="emptyListMessage && items.length === 0"
>{{ emptyListMessage }}</ion-label >{{ emptyListMessage }}</ion-label
> >
</ng-container> </ng-container>

View File

@@ -62,10 +62,8 @@ export class RatingProvider {
return new Date(today.getFullYear(), today.getMonth(), today.getDate()).toISOString(); return new Date(today.getFullYear(), today.getMonth(), today.getDate()).toISOString();
} }
private get userGroup(): Promise<SCUserGroup> { private get userGroup(): SCUserGroup {
return this.settingsProvider return (this.settingsProvider.getSetting('profile', 'group') as SCUserGroupSetting).value as SCUserGroup;
.getSetting('profile', 'group')
.then(it => (it as SCUserGroupSetting).value as SCUserGroup);
} }
private async getStoredRatings(): Promise<RatingStorage> { private async getStoredRatings(): Promise<RatingStorage> {

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