49 Commits

Author SHA1 Message Date
b330fb8141 fix dark mode css
Some checks failed
Angular Build / build (push) Has been cancelled
2026-04-27 23:53:51 +02:00
8b3647b023 dark mode
Some checks failed
Angular Build / build (push) Has been cancelled
2026-04-27 23:42:53 +02:00
5dffcf8cd2 fix css issues 2026-04-27 23:21:19 +02:00
e1aacf2707 RELEASE 2.0
Some checks failed
Angular Build / build (push) Has been cancelled
2026-04-27 23:02:36 +02:00
8c637addf5 fix monitor bg contrast
Some checks failed
Angular Build / build (push) Has been cancelled
2026-04-27 23:01:25 +02:00
e4bbe6e75c fix mobile buttons 2026-04-27 22:34:35 +02:00
30115da841 fix styling 2026-04-27 22:02:15 +02:00
8bfbe7b1cc fix linting
Some checks failed
Angular Build / build (push) Has been cancelled
2026-03-20 21:04:46 +01:00
893a13a8f2 fix linting
Some checks failed
Angular Build / build (push) Has been cancelled
2026-03-20 21:02:02 +01:00
d484239429 tokenized text search #2
Some checks failed
Angular Build / build (push) Has been cancelled
2026-03-20 20:51:17 +01:00
16776e2250 tokenized text search
Some checks failed
Angular Build / build (push) Has been cancelled
2026-03-20 20:44:59 +01:00
7fe4339ce4 fix bundle size
Some checks failed
Angular Build / build (push) Has been cancelled
2026-03-20 19:47:05 +01:00
5efd44e710 fix bundle size
Some checks failed
Angular Build / build (push) Has been cancelled
2026-03-20 19:43:50 +01:00
f2986dd420 fix guest component
Some checks failed
Angular Build / build (push) Has been cancelled
2026-03-20 19:14:59 +01:00
902f1e97ee CCLI Button
Some checks failed
Angular Build / build (push) Has been cancelled
2026-03-20 18:39:06 +01:00
c5fde72782 mobile view
Some checks failed
Angular Build / build (push) Has been cancelled
2026-03-20 18:33:07 +01:00
b5dde11ab1 gittea build #7
All checks were successful
Angular Build / build (push) Successful in 1m13s
2026-03-17 19:23:30 +01:00
733bf5cee4 gittea build #6
All checks were successful
Angular Build / build (push) Successful in 10m40s
2026-03-17 12:59:05 +01:00
e55036d0f7 gittea build #5
Some checks failed
Angular Build / build (push) Failing after 5m51s
2026-03-17 12:29:55 +01:00
80f5e86be5 gittea build #4
Some checks failed
Angular Build / build (push) Failing after 6m3s
2026-03-17 12:07:17 +01:00
2eaf311a09 gittea build #3
Some checks failed
Angular Build / build (push) Failing after 43s
2026-03-16 22:25:30 +01:00
377c3d14fa gittea build #2 2026-03-16 22:22:37 +01:00
4b4641e1b7 gittea build 2026-03-16 22:16:06 +01:00
97a299618a vitest implementation 2 2026-03-16 22:13:01 +01:00
ecb25ee322 vitest implementation 2026-03-16 18:38:46 +01:00
2173ad6abf sidemenu shows 2026-03-16 18:16:19 +01:00
3bd359ee9e sidemenu song list 2026-03-16 17:24:10 +01:00
Benjamin Ifland
f9516bbc4d fix angular json 2026-03-16 16:02:57 +01:00
e3203d0c38 fix login redirect 2026-03-15 22:54:52 +01:00
2406d41dcb fix tests 2026-03-15 22:33:06 +01:00
2d4f1ee314 fix linting 2026-03-15 22:23:58 +01:00
67884e4638 add song reporting 2026-03-15 22:23:11 +01:00
e4f829d0c8 fix template loop references 2026-03-15 13:33:36 +01:00
9bbabb18aa fix song header filter 2026-03-15 13:21:17 +01:00
ab535d48b9 optimize song usage 2026-03-15 13:19:20 +01:00
d907c89eb6 linting 2026-03-15 12:50:33 +01:00
Benjamin Ifland
dd68a6b21d fix lf lint rule 2026-03-13 09:48:27 +01:00
6280d04ee7 fix scroll position 2026-03-11 18:33:41 +01:00
196e8c80d8 global filter 2026-03-11 18:05:33 +01:00
c2bcac58b3 global filter 2026-03-11 17:56:17 +01:00
ce67fb4a34 fix show song header 2026-03-11 17:34:30 +01:00
3082ae1b55 fix show song header 2026-03-11 17:28:04 +01:00
0452ec55b2 validate chords #3 2026-03-11 17:13:17 +01:00
9f47f259c0 validate chords #2 2026-03-11 16:35:29 +01:00
ae4459f5ce validate chords 2026-03-11 16:18:36 +01:00
03fb395605 optimize drag'n'drop 2026-03-11 12:08:34 +01:00
68a257e2bd optimize shadows & paddings 2026-03-11 12:02:53 +01:00
2ac1156e20 optimize chords 2026-03-10 00:23:04 +01:00
7170e4a08e add unit tests 2026-03-10 00:05:15 +01:00
251 changed files with 11179 additions and 6018 deletions

View File

@@ -1,58 +1,32 @@
{ {
"root": true, "root": true,
"ignorePatterns": [ "ignorePatterns": ["projects/**/*"],
"projects/**/*"
],
"overrides": [ "overrides": [
{ {
"files": [ "files": ["*.ts"],
"*.ts" "extends": ["eslint:recommended", "plugin:@typescript-eslint/recommended", "plugin:@angular-eslint/recommended", "plugin:@angular-eslint/template/process-inline-templates"],
],
"parserOptions": {
"project": [
"tsconfig.json",
"e2e/tsconfig.json"
],
"createDefaultProgram": true
},
"extends": [
"plugin:@angular-eslint/recommended",
"plugin:@angular-eslint/template/process-inline-templates",
"eslint:recommended",
"plugin:@typescript-eslint/recommended",
"plugin:@typescript-eslint/recommended-requiring-type-checking",
"plugin:prettier/recommended"
],
"rules": { "rules": {
"@typescript-eslint/explicit-member-accessibility": "error",
"@angular-eslint/component-selector": [
"error",
{
"prefix": "app",
"style": "kebab-case",
"type": "element"
}
],
"@typescript-eslint/unbound-method": [
"off"
],
"@angular-eslint/directive-selector": [ "@angular-eslint/directive-selector": [
"error", "error",
{ {
"type": "attribute",
"prefix": "app", "prefix": "app",
"style": "camelCase", "style": "camelCase"
"type": "attribute" }
],
"@angular-eslint/component-selector": [
"error",
{
"type": "element",
"prefix": "app",
"style": "kebab-case"
} }
] ]
} }
}, },
{ {
"files": [ "files": ["*.html"],
"*.html" "extends": ["plugin:@angular-eslint/template/recommended", "plugin:@angular-eslint/template/accessibility"],
],
"extends": [
"plugin:@angular-eslint/template/recommended"
],
"rules": {} "rules": {}
} }
] ]

View File

@@ -0,0 +1,37 @@
name: Angular Build
on:
push:
branches:
- dev
jobs:
build:
runs-on: runner
container:
image: node:20-bullseye
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Install dependencies
run: npm ci -f
- name: Create firebase.ts
run: |
mkdir -p src/app
cat > src/environments/firebase.ts <<'EOF'
export const firebase = {
apiKey: "${{ secrets.FIREBASE_API_KEY }}",
authDomain: "${{ secrets.FIREBASE_AUTH_DOMAIN }}",
databaseURL: 'https://worshipgenerator.firebaseio.com',
projectId: "${{ secrets.FIREBASE_PROJECT_ID }}",
storageBucket: "${{ secrets.FIREBASE_STORAGE_BUCKET }}",
messagingSenderId: "${{ secrets.FIREBASE_MESSAGING_SENDER_ID }}",
appId: "${{ secrets.FIREBASE_APP_ID }}"
};
EOF
- name: Build Angular
run: npm run build

View File

@@ -5,6 +5,7 @@
"singleQuote": true, "singleQuote": true,
"quoteProps": "as-needed", "quoteProps": "as-needed",
"trailingComma": "es5", "trailingComma": "es5",
"endOfLine": "auto",
"bracketSpacing": false, "bracketSpacing": false,
"arrowParens": "avoid", "arrowParens": "avoid",
"jsxBracketSameLine": false, "jsxBracketSameLine": false,

View File

@@ -8,6 +8,14 @@ If `songUsage` needs to be rebuilt from all existing shows, log in with a user t
await window.wgeneratorAdmin.rebuildSongUsage() await window.wgeneratorAdmin.rebuildSongUsage()
``` ```
If the `songIds` index on shows needs to be backfilled for tooltip usage in song details, run:
```js
await window.wgeneratorAdmin.rebuildShowSongIds()
```
The command logs progress in the browser console while it runs and prints the final summary when finished.
The migration: The migration:
- resets `songUsage` for all users - resets `songUsage` for all users
@@ -16,4 +24,11 @@ The migration:
It returns a summary object with processed user, show and show-song counts. It returns a summary object with processed user, show and show-song counts.
The show index migration:
- scans all shows and all `shows/{id}/songs` entries
- writes the distinct `songIds` array to each show document
It returns a summary object with processed show and show-song counts.
This is intended as a manual one-off migration and is read-heavy by design. This is intended as a manual one-off migration and is read-heavy by design.

View File

@@ -15,8 +15,9 @@
"prefix": "app", "prefix": "app",
"architect": { "architect": {
"build": { "build": {
"builder": "@angular-devkit/build-angular:application", "builder": "@angular/build:application",
"options": { "options": {
"browser": "src/main.ts",
"outputPath": { "outputPath": {
"base": "dist/wgenerator" "base": "dist/wgenerator"
}, },
@@ -25,7 +26,7 @@
"src/polyfills.ts" "src/polyfills.ts"
], ],
"tsConfig": "tsconfig.app.json", "tsConfig": "tsconfig.app.json",
"aot": false, "inlineStyleLanguage": "less",
"assets": [ "assets": [
"src/browserconfig.xml", "src/browserconfig.xml",
"src/android-chrome-192x192.png", "src/android-chrome-192x192.png",
@@ -45,16 +46,11 @@
"src/styles/shadow.less" "src/styles/shadow.less"
], ],
"scripts": [], "scripts": [],
"extractLicenses": false,
"sourceMap": true,
"optimization": false,
"namedChunks": true,
"allowedCommonJsDependencies": [ "allowedCommonJsDependencies": [
"lodash", "lodash",
"docx", "docx",
"qrcode" "qrcode"
], ]
"browser": "src/main.ts"
}, },
"configurations": { "configurations": {
"production": { "production": {
@@ -64,59 +60,49 @@
"with": "src/environments/environment.prod.ts" "with": "src/environments/environment.prod.ts"
} }
], ],
"optimization": true,
"outputHashing": "all",
"sourceMap": false,
"namedChunks": false,
"aot": true,
"extractLicenses": true,
"budgets": [ "budgets": [
{ {
"type": "initial", "type": "initial",
"maximumWarning": "2mb", "maximumWarning": "500kB",
"maximumError": "5mb" "maximumError": "10MB"
}, },
{ {
"type": "anyComponentStyle", "type": "anyComponentStyle",
"maximumWarning": "6kb", "maximumWarning": "40kB",
"maximumError": "10kb" "maximumError": "80kB"
} }
], ],
"serviceWorker": "ngsw-config.json" "outputHashing": "all"
},
"development": {
"optimization": false,
"extractLicenses": false,
"sourceMap": true
} }
} },
"defaultConfiguration": "production"
}, },
"serve": { "serve": {
"builder": "@angular-devkit/build-angular:dev-server", "builder": "@angular/build:dev-server",
"options": {
"buildTarget": "wgenerator:build"
},
"configurations": { "configurations": {
"production": { "production": {
"buildTarget": "wgenerator:build:production" "buildTarget": "wgenerator:build:production"
},
"development": {
"buildTarget": "wgenerator:build:development"
} }
} },
}, "defaultConfiguration": "development"
"extract-i18n": {
"builder": "@angular-devkit/build-angular:extract-i18n",
"options": {
"buildTarget": "wgenerator:build"
}
}, },
"test": { "test": {
"builder": "@angular-devkit/build-angular:karma", "builder": "@angular/build:unit-test",
"options": { "options": {
"main": "src/test.ts", "runner": "vitest",
"polyfills": "src/polyfills.ts",
"tsConfig": "tsconfig.spec.json", "tsConfig": "tsconfig.spec.json",
"karmaConfig": "karma.conf.js", "setupFiles": [
"assets": [ "src/test-vitest.ts"
"src/favicon.ico",
"src/assets",
"src/manifest.webmanifest"
], ],
"styles": [], "runnerConfig": true
"scripts": []
} }
}, },
"lint": { "lint": {
@@ -127,58 +113,11 @@
"src/**/*.html" "src/**/*.html"
] ]
} }
},
"e2e": {
"builder": "@angular-devkit/build-angular:protractor",
"options": {
"protractorConfig": "e2e/protractor.conf.js",
"devServerTarget": "wgenerator:serve"
},
"configurations": {
"production": {
"devServerTarget": "wgenerator:serve:production"
}
}
} }
} }
} }
}, },
"cli": { "cli": {
"analytics": "4047dcd7-89f4-402f-958e-e365a5505c55", "analytics": false
"schematicCollections": [
"@angular-eslint/schematics"
]
},
"schematics": {
"@angular-eslint/schematics:application": {
"setParserOptionsProject": true
},
"@angular-eslint/schematics:library": {
"setParserOptionsProject": true
},
"@schematics/angular:component": {
"type": "component"
},
"@schematics/angular:directive": {
"type": "directive"
},
"@schematics/angular:service": {
"type": "service"
},
"@schematics/angular:guard": {
"typeSeparator": "."
},
"@schematics/angular:interceptor": {
"typeSeparator": "."
},
"@schematics/angular:module": {
"typeSeparator": "."
},
"@schematics/angular:pipe": {
"typeSeparator": "."
},
"@schematics/angular:resolver": {
"typeSeparator": "."
}
} }
} }

View File

@@ -1,32 +0,0 @@
// @ts-check
// Protractor configuration file, see link for more information
// https://github.com/angular/protractor/blob/master/lib/config.ts
const { SpecReporter } = require('jasmine-spec-reporter');
/**
* @type { import("protractor").Config }
*/
exports.config = {
allScriptsTimeout: 11000,
specs: [
'./src/**/*.e2e-spec.ts'
],
capabilities: {
browserName: 'chrome'
},
directConnect: true,
baseUrl: 'http://localhost:4200/',
framework: 'jasmine',
jasmineNodeOpts: {
showColors: true,
defaultTimeoutInterval: 30000,
print: function() {}
},
onPrepare() {
require('ts-node').register({
project: require('path').join(__dirname, './tsconfig.json')
});
jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } }));
}
};

View File

@@ -1,25 +0,0 @@
import {AppPage} from './app.po';
import {browser, logging} from 'protractor';
describe('workspace-project App', () => {
let page: AppPage;
beforeEach(() => {
page = new AppPage();
});
it('should display welcome message', () => {
void page.navigateTo();
void expect(page.getTitleText()).toEqual('wgenerator app is running!');
});
afterEach(async () => {
// Assert that there are no errors emitted from the browser
const logs = await browser.manage().logs().get(logging.Type.BROWSER);
void expect(logs).not.toContain(
jasmine.objectContaining({
level: logging.Level.SEVERE,
} as logging.Entry)
);
});
});

View File

@@ -1,11 +0,0 @@
import { browser, by, element } from 'protractor';
export class AppPage {
navigateTo() {
return browser.get(browser.baseUrl) as Promise<any>;
}
getTitleText() {
return element(by.css('app-root .content span')).getText() as Promise<string>;
}
}

View File

@@ -1,13 +0,0 @@
{
"extends": "../tsconfig.json",
"compilerOptions": {
"outDir": "../out-tsc/e2e",
"module": "commonjs",
"target": "es2018",
"types": [
"jasmine",
"jasminewd2",
"node"
]
}
}

View File

@@ -1,32 +0,0 @@
// Karma configuration file, see link for more information
// https://karma-runner.github.io/1.0/config/configuration-file.html
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine', '@angular-devkit/build-angular'],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'),
require('karma-coverage-istanbul-reporter'),
require('@angular-devkit/build-angular/plugins/karma')
],
client: {
clearContext: false // leave Jasmine Spec Runner output visible in browser
},
coverageIstanbulReporter: {
dir: require('path').join(__dirname, './coverage/wgenerator'),
reports: ['html', 'lcovonly', 'text-summary'],
fixWebpackSourcePaths: true
},
reporters: ['progress', 'kjhtml'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false,
restartOnFileChange: true
});
};

7495
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,10 +1,12 @@
{ {
"name": "wgenerator", "name": "wgenerator",
"version": "1.6", "version": "2.0",
"scripts": { "scripts": {
"start": "ng serve", "start": "ng serve",
"build": "ng build", "build": "ng build --configuration production",
"build:dev": "ng build --configuration development",
"deploy": "ng build --configuration production && firebase deploy", "deploy": "ng build --configuration production && firebase deploy",
"deploy-beta": "ng b && firebase hosting:channel:deploy beta",
"test": "ng test", "test": "ng test",
"lint": "ng lint --fix", "lint": "ng lint --fix",
"update": "ng update @angular/cdk @angular/cli @angular/core @angular/material && ncu -u && npm i && npm fix" "update": "ng update @angular/cdk @angular/cli @angular/core @angular/material && ncu -u && npm i && npm fix"
@@ -46,22 +48,16 @@
"@angular/cli": "^21.2.1", "@angular/cli": "^21.2.1",
"@angular/compiler-cli": "^21.2.2", "@angular/compiler-cli": "^21.2.2",
"@angular/language-service": "^21.2.2", "@angular/language-service": "^21.2.2",
"@types/jasmine": "~6.0.0",
"@types/jasminewd2": "~2.0.13",
"@typescript-eslint/eslint-plugin": "^8.57.0", "@typescript-eslint/eslint-plugin": "^8.57.0",
"@typescript-eslint/parser": "^8.57.0", "@typescript-eslint/parser": "^8.57.0",
"angular-eslint": "^21.3.1",
"eslint": "^9.39.4", "eslint": "^9.39.4",
"eslint-config-prettier": "^10.1.8", "eslint-config-prettier": "^10.1.8",
"eslint-plugin-prettier": "^5.5.5", "eslint-plugin-prettier": "^5.5.5",
"firebase-tools": "^15.9.1", "firebase-tools": "^15.9.1",
"jasmine-core": "~6.1.0", "jsdom": "^29.0.0",
"jasmine-spec-reporter": "~7.0.0",
"karma": "~6.4.4",
"karma-chrome-launcher": "~3.2.0",
"karma-coverage-istanbul-reporter": "~3.0.3",
"karma-jasmine": "~5.1.0",
"karma-jasmine-html-reporter": "^2.2.0",
"prettier": "^3.8.1", "prettier": "^3.8.1",
"typescript": "~5.9.3" "typescript": "~5.9.3",
"vitest": "^4.1.0"
} }
} }

View File

@@ -1,5 +1,9 @@
import {NgModule} from '@angular/core'; import {NgModule} from '@angular/core';
import {PreloadAllModules, RouterModule, Routes} from '@angular/router'; import {RouterModule, Routes} from '@angular/router';
import {FirebaseApp} from '@angular/fire/app';
import {provideStorage} from '@angular/fire/storage';
import {inject} from '@angular/core';
import {getStorage} from 'firebase/storage';
import {RoleGuard} from './widget-modules/guards/role.guard'; import {RoleGuard} from './widget-modules/guards/role.guard';
import {AuthGuard} from './widget-modules/guards/auth.guard'; import {AuthGuard} from './widget-modules/guards/auth.guard';
@@ -12,6 +16,7 @@ const routes: Routes = [
{ {
path: 'songs', path: 'songs',
loadChildren: () => import('./modules/songs/songs.module').then(m => m.SongsModule), loadChildren: () => import('./modules/songs/songs.module').then(m => m.SongsModule),
providers: [provideStorage(() => getStorage(inject(FirebaseApp)))],
canActivate: [AuthGuard, RoleGuard], canActivate: [AuthGuard, RoleGuard],
data: { data: {
requiredRoles: ['user'], requiredRoles: ['user'],
@@ -50,7 +55,6 @@ const routes: Routes = [
@NgModule({ @NgModule({
imports: [ imports: [
RouterModule.forRoot(routes, { RouterModule.forRoot(routes, {
preloadingStrategy: PreloadAllModules,
scrollPositionRestoration: 'enabled', scrollPositionRestoration: 'enabled',
// relativeLinkResolution: 'legacy', // relativeLinkResolution: 'legacy',
}), }),

View File

@@ -1,6 +1,5 @@
<app-navigation></app-navigation> <app-navigation></app-navigation>
<div [@fader]="o.isActivated ? o.activatedRoute : ''" class="content"> <div class="content">
<router-outlet #o="outlet"></router-outlet> <router-outlet></router-outlet>
</div> </div>

View File

@@ -1,13 +1,13 @@
import {TestBed, waitForAsync} from '@angular/core/testing'; import {TestBed} from '@angular/core/testing';
import {RouterTestingModule} from '@angular/router/testing'; import {RouterTestingModule} from '@angular/router/testing';
import {AppComponent} from './app.component'; import {AppComponent} from './app.component';
describe('AppComponent', () => { describe('AppComponent', () => {
beforeEach(waitForAsync(() => { beforeEach(async () => {
void TestBed.configureTestingModule({ await TestBed.configureTestingModule({
imports: [RouterTestingModule, AppComponent], imports: [RouterTestingModule, AppComponent],
}).compileComponents(); }).compileComponents();
})); });
it('should create the app', () => { it('should create the app', () => {
const fixture = TestBed.createComponent(AppComponent); const fixture = TestBed.createComponent(AppComponent);

View File

@@ -1,9 +1,8 @@
import {ChangeDetectionStrategy, Component, OnInit, inject} from '@angular/core'; import {ChangeDetectionStrategy, Component, OnInit, inject} from '@angular/core';
import {fader} from './animations'; import {fader} from './animations';
import {ScrollService} from './services/scroll.service';
import {register} from 'swiper/element/bundle';
import {RouterOutlet} from '@angular/router'; import {RouterOutlet} from '@angular/router';
import {NavigationComponent} from './widget-modules/components/application-frame/navigation/navigation.component'; import {NavigationComponent} from './widget-modules/components/application-frame/navigation/navigation.component';
import {ThemeService} from './services/theme/theme.service';
@Component({ @Component({
selector: 'app-root', selector: 'app-root',
@@ -14,18 +13,12 @@ import {NavigationComponent} from './widget-modules/components/application-frame
imports: [RouterOutlet, NavigationComponent], imports: [RouterOutlet, NavigationComponent],
}) })
export class AppComponent implements OnInit { export class AppComponent implements OnInit {
private scrollService = inject(ScrollService);
public constructor() { public constructor() {
register(); inject(ThemeService);
} }
public ngOnInit(): void { public ngOnInit(): void {
setTimeout(() => document.querySelector('#load-bg')?.classList.add('hidden'), 1000); setTimeout(() => document.querySelector('#load-bg')?.classList.add('hidden'), 1000);
setTimeout(() => document.querySelector('#load-bg')?.remove(), 5000); setTimeout(() => document.querySelector('#load-bg')?.remove(), 5000);
} }
public onScoll($event: {srcElement: {scrollTop: number}}): void {
this.scrollService.saveScrollPosition($event.srcElement.scrollTop);
}
} }

View File

@@ -1,4 +1,4 @@
import {ComponentFixture, TestBed, waitForAsync} from '@angular/core/testing'; import {ComponentFixture, TestBed} from '@angular/core/testing';
import {BrandComponent} from './brand.component'; import {BrandComponent} from './brand.component';
@@ -6,11 +6,11 @@ describe('BrandComponent', () => {
let component: BrandComponent; let component: BrandComponent;
let fixture: ComponentFixture<BrandComponent>; let fixture: ComponentFixture<BrandComponent>;
beforeEach(waitForAsync(() => { beforeEach(async () => {
void TestBed.configureTestingModule({ await TestBed.configureTestingModule({
imports: [BrandComponent], imports: [BrandComponent],
}).compileComponents(); }).compileComponents();
})); });
beforeEach(() => { beforeEach(() => {
fixture = TestBed.createComponent(BrandComponent); fixture = TestBed.createComponent(BrandComponent);

View File

@@ -1,13 +1,10 @@
<div class="frame"> <div class="frame">
<app-brand class="brand"></app-brand> <app-brand class="brand"></app-brand>
@if (user$ | async; as user) { @if (user$ | async; as user) {
<div class="text"> <div class="text">
<div class="welcome">WILLKOMMEN</div> <div class="welcome">WILLKOMMEN</div>
<div class="name">{{ user.name }}</div> <div class="name">{{ user.name }}</div>
<div class="roles"> <div class="roles">Es wurden noch keine Berechtigungen zugeteilt, bitte wende Dich an den Administrator!</div>
Es wurden noch keine Berechtigungen zugeteilt, bitte wende Dich an den </div>
Administrator!
</div>
</div>
} }
</div> </div>

View File

@@ -1,4 +1,4 @@
import {ComponentFixture, TestBed, waitForAsync} from '@angular/core/testing'; import {ComponentFixture, TestBed} from '@angular/core/testing';
import {NewUserComponent} from './new-user.component'; import {NewUserComponent} from './new-user.component';
@@ -6,11 +6,11 @@ describe('NewUserComponent', () => {
let component: NewUserComponent; let component: NewUserComponent;
let fixture: ComponentFixture<NewUserComponent>; let fixture: ComponentFixture<NewUserComponent>;
beforeEach(waitForAsync(() => { beforeEach(async () => {
void TestBed.configureTestingModule({ await TestBed.configureTestingModule({
imports: [NewUserComponent], imports: [NewUserComponent],
}).compileComponents(); }).compileComponents();
})); });
beforeEach(() => { beforeEach(() => {
fixture = TestBed.createComponent(NewUserComponent); fixture = TestBed.createComponent(NewUserComponent);

View File

@@ -1,4 +1,5 @@
import {TestBed} from '@angular/core/testing'; import {TestBed} from '@angular/core/testing';
import {Firestore} from '@angular/fire/firestore';
import {of} from 'rxjs'; import {of} from 'rxjs';
import {DbService} from 'src/app/services/db.service'; import {DbService} from 'src/app/services/db.service';
import {GuestShowDataService} from './guest-show-data.service'; import {GuestShowDataService} from './guest-show-data.service';
@@ -11,8 +12,9 @@ describe('GuestShowDataService', () => {
let colAddSpy: jasmine.Spy<() => Promise<{id: string}>>; let colAddSpy: jasmine.Spy<() => Promise<{id: string}>>;
let colSpy: jasmine.Spy; let colSpy: jasmine.Spy;
let dbServiceSpy: jasmine.SpyObj<DbService>; let dbServiceSpy: jasmine.SpyObj<DbService>;
let firestoreStub: Firestore;
beforeEach(() => { beforeEach(async () => {
docUpdateSpy = jasmine.createSpy('update').and.resolveTo(); docUpdateSpy = jasmine.createSpy('update').and.resolveTo();
docDeleteSpy = jasmine.createSpy('delete').and.resolveTo(); docDeleteSpy = jasmine.createSpy('delete').and.resolveTo();
docSpy = jasmine.createSpy('doc').and.returnValue({ docSpy = jasmine.createSpy('doc').and.returnValue({
@@ -26,9 +28,13 @@ describe('GuestShowDataService', () => {
dbServiceSpy.doc$.and.returnValue(of({id: 'guest-1'}) as never); dbServiceSpy.doc$.and.returnValue(of({id: 'guest-1'}) as never);
dbServiceSpy.doc.and.callFake(docSpy); dbServiceSpy.doc.and.callFake(docSpy);
dbServiceSpy.col.and.callFake(colSpy); dbServiceSpy.col.and.callFake(colSpy);
firestoreStub = {} as Firestore;
void TestBed.configureTestingModule({ await TestBed.configureTestingModule({
providers: [{provide: DbService, useValue: dbServiceSpy}], providers: [
{provide: DbService, useValue: dbServiceSpy},
{provide: Firestore, useValue: firestoreStub},
],
}); });
service = TestBed.inject(GuestShowDataService); service = TestBed.inject(GuestShowDataService);

View File

@@ -1,4 +1,5 @@
import {Injectable, inject} from '@angular/core'; import {EnvironmentInjector, Injectable, inject, runInInjectionContext} from '@angular/core';
import {doc, Firestore, getDoc} from '@angular/fire/firestore';
import {Observable} from 'rxjs'; import {Observable} from 'rxjs';
import {shareReplay} from 'rxjs/operators'; import {shareReplay} from 'rxjs/operators';
import {DbService} from 'src/app/services/db.service'; import {DbService} from 'src/app/services/db.service';
@@ -9,6 +10,8 @@ import {GuestShow} from './guest-show';
}) })
export class GuestShowDataService { export class GuestShowDataService {
private dbService = inject(DbService); private dbService = inject(DbService);
private firestore = inject(Firestore);
private environmentInjector = inject(EnvironmentInjector);
private collection = 'guest'; private collection = 'guest';
public list$: Observable<GuestShow[]> = this.dbService.col$<GuestShow>(this.collection).pipe( public list$: Observable<GuestShow[]> = this.dbService.col$<GuestShow>(this.collection).pipe(
@@ -19,6 +22,18 @@ export class GuestShowDataService {
); );
public read$: (id: string) => Observable<GuestShow | null> = (id: string): Observable<GuestShow | null> => this.dbService.doc$(`${this.collection}/${id}`); public read$: (id: string) => Observable<GuestShow | null> = (id: string): Observable<GuestShow | null> => this.dbService.doc$(`${this.collection}/${id}`);
public read: (id: string) => Promise<GuestShow | null> = async (id: string): Promise<GuestShow | null> => {
const snapshot = await runInInjectionContext(this.environmentInjector, () => getDoc(doc(this.firestore, `${this.collection}/${id}`)));
if (!snapshot.exists()) {
return null;
}
return {
id: snapshot.id,
...(snapshot.data() as Omit<GuestShow, 'id'>),
};
};
public update$: (id: string, data: Partial<GuestShow>) => Promise<void> = async (id: string, data: Partial<GuestShow>): Promise<void> => public update$: (id: string, data: Partial<GuestShow>) => Promise<void> = async (id: string, data: Partial<GuestShow>): Promise<void> =>
await this.dbService.doc(this.collection + '/' + id).update(data); await this.dbService.doc(this.collection + '/' + id).update(data);
public add: (data: Partial<GuestShow>) => Promise<string> = async (data: Partial<GuestShow>): Promise<string> => (await this.dbService.col(this.collection).add(data)).id; public add: (data: Partial<GuestShow>) => Promise<string> = async (data: Partial<GuestShow>): Promise<string> => (await this.dbService.col(this.collection).add(data)).id;

View File

@@ -2,20 +2,22 @@ import {TestBed} from '@angular/core/testing';
import {GuestShowDataService} from './guest-show-data.service'; import {GuestShowDataService} from './guest-show-data.service';
import {GuestShowService} from './guest-show.service'; import {GuestShowService} from './guest-show.service';
import {ShowService} from '../shows/services/show.service'; import {ShowService} from '../shows/services/show.service';
import {Show} from '../shows/services/show';
import {Song} from '../songs/services/song';
describe('GuestShowService', () => { describe('GuestShowService', () => {
let service: GuestShowService; let service: GuestShowService;
let guestShowDataServiceSpy: jasmine.SpyObj<GuestShowDataService>; let guestShowDataServiceSpy: jasmine.SpyObj<GuestShowDataService>;
let showServiceSpy: jasmine.SpyObj<ShowService>; let showServiceSpy: jasmine.SpyObj<ShowService>;
beforeEach(() => { beforeEach(async () => {
guestShowDataServiceSpy = jasmine.createSpyObj<GuestShowDataService>('GuestShowDataService', ['add', 'update$']); guestShowDataServiceSpy = jasmine.createSpyObj<GuestShowDataService>('GuestShowDataService', ['add', 'update$']);
showServiceSpy = jasmine.createSpyObj<ShowService>('ShowService', ['update$']); showServiceSpy = jasmine.createSpyObj<ShowService>('ShowService', ['update$']);
guestShowDataServiceSpy.add.and.resolveTo('share-1'); guestShowDataServiceSpy.add.and.resolveTo('share-1');
guestShowDataServiceSpy.update$.and.resolveTo(); guestShowDataServiceSpy.update$.and.resolveTo();
showServiceSpy.update$.and.resolveTo(); showServiceSpy.update$.and.resolveTo();
void TestBed.configureTestingModule({ await TestBed.configureTestingModule({
providers: [ providers: [
{provide: GuestShowDataService, useValue: guestShowDataServiceSpy}, {provide: GuestShowDataService, useValue: guestShowDataServiceSpy},
{provide: ShowService, useValue: showServiceSpy}, {provide: ShowService, useValue: showServiceSpy},
@@ -30,32 +32,41 @@ describe('GuestShowService', () => {
}); });
it('should create a new guest share, persist the generated shareId on the show and return the share url', async () => { it('should create a new guest share, persist the generated shareId on the show and return the share url', async () => {
const show = {id: 'show-1', showType: 'service-worship', date: new Date(), shareId: ''} as any; const show = {id: 'show-1', showType: 'service-worship', date: new Date(), shareId: ''} as unknown as Show;
const songs = [{id: 'song-1'}] as any; const songs = [{id: 'song-1'}] as unknown as Song[];
const expectedUrl = window.location.protocol + '//' + window.location.host + '/guest/share-1'; const expectedUrl = window.location.protocol + '//' + window.location.host + '/guest/share-1';
await expectAsync(service.share(show, songs)).toBeResolvedTo(expectedUrl); await expectAsync(service.share(show, songs)).toBeResolvedTo(expectedUrl);
expect(guestShowDataServiceSpy.add).toHaveBeenCalledWith({ const [addPayload] = guestShowDataServiceSpy.add.calls.mostRecent().args as [Record<string, unknown>];
showType: 'service-worship', expect(addPayload).toEqual(
date: show.date, jasmine.objectContaining({
songs, showType: 'service-worship',
}); date: show.date,
songs,
})
);
expect(addPayload['updatedAt']).toEqual(jasmine.any(Date));
expect(showServiceSpy.update$).toHaveBeenCalledWith('show-1', {shareId: 'share-1'}); expect(showServiceSpy.update$).toHaveBeenCalledWith('show-1', {shareId: 'share-1'});
}); });
it('should update an existing share and reuse its id in the returned url', async () => { it('should update an existing share and reuse its id in the returned url', async () => {
const show = {id: 'show-1', showType: 'service-worship', date: new Date(), shareId: 'share-9'} as any; const show = {id: 'show-1', showType: 'service-worship', date: new Date(), shareId: 'share-9'} as unknown as Show;
const songs = [{id: 'song-1'}] as any; const songs = [{id: 'song-1'}] as unknown as Song[];
const expectedUrl = window.location.protocol + '//' + window.location.host + '/guest/share-9'; const expectedUrl = window.location.protocol + '//' + window.location.host + '/guest/share-9';
await expectAsync(service.share(show, songs)).toBeResolvedTo(expectedUrl); await expectAsync(service.share(show, songs)).toBeResolvedTo(expectedUrl);
expect(guestShowDataServiceSpy.update$).toHaveBeenCalledWith('share-9', { const [shareId, updatePayload] = guestShowDataServiceSpy.update$.calls.mostRecent().args as [string, Record<string, unknown>];
showType: 'service-worship', expect(shareId).toBe('share-9');
date: show.date, expect(updatePayload).toEqual(
songs, jasmine.objectContaining({
}); showType: 'service-worship',
date: show.date,
songs,
})
);
expect(updatePayload['updatedAt']).toEqual(jasmine.any(Date));
expect(guestShowDataServiceSpy.add).not.toHaveBeenCalled(); expect(guestShowDataServiceSpy.add).not.toHaveBeenCalled();
expect(showServiceSpy.update$).not.toHaveBeenCalled(); expect(showServiceSpy.update$).not.toHaveBeenCalled();
}); });

View File

@@ -15,6 +15,7 @@ export class GuestShowService {
const data = { const data = {
showType: show.showType, showType: show.showType,
date: show.date, date: show.date,
updatedAt: new Date(),
songs: songs, songs: songs,
}; };
let shareId = show.shareId; let shareId = show.shareId;

View File

@@ -5,5 +5,6 @@ export interface GuestShow {
id: string; id: string;
showType: string; showType: string;
date: Timestamp; date: Timestamp;
updatedAt?: Timestamp | Date;
songs: Song[]; songs: Song[];
} }

View File

@@ -1,28 +1,29 @@
@if (show$|async; as show) { @if (showState$ | async; as state) { @if (state.status === 'loaded') {
<div class="page"> <div class="page">
<div class="title"> <div class="title">
<div class="left">{{ show.showType|showType }}</div> <div class="left">{{ state.show.showType | showType }}</div>
<div class="right">{{ show.date.toDate() | date: 'dd.MM.yyyy' }}</div> <div class="right">{{ state.show.date | date: 'dd.MM.yyyy' }}</div>
</div>
<div class="view">
<swiper-container scrollbar="true">
@for (song of show.songs; track trackBy(i, song); let i = $index) {
<swiper-slide
class="song-swipe">
<div class="song-title">{{ song.title }}</div>
<div class="legal">
@if (song.artist) {
<p>{{ song.artist }}</p>
}
</div>
<app-song-text
[text]="song.text"
></app-song-text>
</swiper-slide>
}
</swiper-container>
</div>
</div> </div>
} <div class="view">
<swiper-container scrollbar="true">
@for (song of state.show.songs; track song.id) {
<swiper-slide class="song-swipe">
<div class="song-title">{{ song.title }}</div>
<div class="legal">
@if (song.artist) {
<p>{{ song.artist }}</p>
}
</div>
<app-song-text [text]="song.text"></app-song-text>
</swiper-slide>
}
</swiper-container>
</div>
</div>
} @else if (state.status === 'loading') {
<div class="empty-state">Gastansicht wird geladen.</div>
} @else if (state.status === 'not-found') {
<div class="empty-state">Für diesen Link wurde keine Gastansicht gefunden.</div>
} @else {
<div class="empty-state">{{ state.message }}</div>
} }

View File

@@ -57,3 +57,13 @@ app-song-text {
margin-bottom: 50px; margin-bottom: 50px;
min-height: calc(100vh - 150px); min-height: calc(100vh - 150px);
} }
.empty-state {
color: var(--text-inverse);
display: flex;
justify-content: center;
align-items: center;
min-height: calc(100vh - 50px);
padding: 24px;
text-align: center;
}

View File

@@ -1,24 +1,97 @@
import {ComponentFixture, TestBed, waitForAsync} from '@angular/core/testing'; import {ComponentFixture, TestBed} from '@angular/core/testing';
import {ActivatedRoute} from '@angular/router';
import {BehaviorSubject, of} from 'rxjs';
import {GuestComponent} from './guest.component'; import {GuestComponent} from './guest.component';
import {GuestShowDataService} from './guest-show-data.service';
describe('GuestComponent', () => { describe('GuestComponent', () => {
let component: GuestComponent; let component: GuestComponent;
let fixture: ComponentFixture<GuestComponent>; let fixture: ComponentFixture<GuestComponent>;
let guestShowDataServiceSpy: jasmine.SpyObj<GuestShowDataService>;
let guestShowSubject: BehaviorSubject<unknown>;
beforeEach(waitForAsync(() => { beforeEach(async () => {
void TestBed.configureTestingModule({ guestShowSubject = new BehaviorSubject<unknown>({
id: 'guest-1',
showType: 'service-worship',
date: {
toDate: () => new Date('2026-03-20T00:00:00Z'),
},
songs: [
{
id: 'song-1',
title: 'Titel',
text: 'Text',
artist: 'Artist',
},
],
});
guestShowDataServiceSpy = jasmine.createSpyObj<GuestShowDataService>('GuestShowDataService', ['read', 'read$']);
guestShowDataServiceSpy.read.and.resolveTo({
id: 'guest-1',
showType: 'service-worship',
date: {
toDate: () => new Date('2026-03-20T00:00:00Z'),
},
songs: [
{
id: 'song-1',
title: 'Titel',
text: 'Text',
artist: 'Artist',
},
],
} as never);
guestShowDataServiceSpy.read$.and.returnValue(guestShowSubject.asObservable() as never);
await TestBed.configureTestingModule({
imports: [GuestComponent], imports: [GuestComponent],
providers: [
{provide: ActivatedRoute, useValue: {params: of({id: 'guest-1'})}},
{provide: GuestShowDataService, useValue: guestShowDataServiceSpy},
],
}).compileComponents(); }).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(GuestComponent); fixture = TestBed.createComponent(GuestComponent);
component = fixture.componentInstance; component = fixture.componentInstance;
fixture.detectChanges(); fixture.detectChanges();
await fixture.whenStable();
fixture.detectChanges();
}); });
it('should create', () => { it('should create', () => {
void expect(component).toBeTruthy(); expect(component).toBeTruthy();
});
it('should load and render the guest show', () => {
expect(guestShowDataServiceSpy.read).toHaveBeenCalledWith('guest-1');
expect(guestShowDataServiceSpy.read$).toHaveBeenCalledWith('guest-1');
expect(fixture.nativeElement.textContent).toContain('Titel');
expect(fixture.nativeElement.textContent).toContain('20.03.2026');
});
it('should update the rendered guest show when live data changes', async () => {
guestShowSubject.next({
id: 'guest-1',
showType: 'service-worship',
date: {
toDate: () => new Date('2026-03-21T00:00:00Z'),
},
songs: [
{
id: 'song-2',
title: 'Neuer Titel',
text: 'Neuer Text',
artist: 'Neue Artistin',
},
],
});
fixture.detectChanges();
await fixture.whenStable();
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('Neuer Titel');
expect(fixture.nativeElement.textContent).toContain('21.03.2026');
}); });
}); });

View File

@@ -1,12 +1,14 @@
import {Component, CUSTOM_ELEMENTS_SCHEMA, inject} from '@angular/core'; import {Component, CUSTOM_ELEMENTS_SCHEMA, inject} from '@angular/core';
import {AsyncPipe, DatePipe} from '@angular/common';
import {GuestShowDataService} from './guest-show-data.service'; import {GuestShowDataService} from './guest-show-data.service';
import {ActivatedRoute} from '@angular/router'; import {ActivatedRoute} from '@angular/router';
import {map, switchMap} from 'rxjs/operators'; import {catchError, map, switchMap} from 'rxjs/operators';
import {Song} from '../songs/services/song'; import {Song} from '../songs/services/song';
import {ConfigService} from '../../services/config.service';
import {AsyncPipe, DatePipe} from '@angular/common';
import {SongTextComponent} from '../../widget-modules/components/song-text/song-text.component'; import {SongTextComponent} from '../../widget-modules/components/song-text/song-text.component';
import {ShowTypePipe} from '../../widget-modules/pipes/show-type-translater/show-type.pipe'; import {ShowTypePipe} from '../../widget-modules/pipes/show-type-translater/show-type.pipe';
import {concat, from, Observable, of} from 'rxjs';
import {GuestShow} from './guest-show';
import {ensureSwiperElement} from '../../services/swiper-element';
@Component({ @Component({
selector: 'app-guest', selector: 'app-guest',
@@ -18,13 +20,89 @@ import {ShowTypePipe} from '../../widget-modules/pipes/show-type-translater/show
export class GuestComponent { export class GuestComponent {
private currentRoute = inject(ActivatedRoute); private currentRoute = inject(ActivatedRoute);
private service = inject(GuestShowDataService); private service = inject(GuestShowDataService);
private configService = inject(ConfigService);
public show$ = this.currentRoute.params.pipe( public constructor() {
void ensureSwiperElement();
}
public showState$: Observable<GuestShowState> = this.currentRoute.params.pipe(
map(param => param.id as string), map(param => param.id as string),
switchMap(id => this.service.read$(id)) switchMap(id =>
concat(
of<GuestShowState>({status: 'loading'}),
from(this.service.read(id)).pipe(
switchMap(show => {
const normalizedShow = this.normalizeShow(show);
if (!normalizedShow) {
return of<GuestShowState>({status: 'not-found'});
}
return concat(
of<GuestShowState>({status: 'loaded', show: normalizedShow}),
this.service.read$(id).pipe(
map(liveShow => this.normalizeShow(liveShow)),
map(liveShow => (liveShow ? ({status: 'loaded', show: liveShow} as GuestShowState) : ({status: 'not-found'} as GuestShowState))),
catchError(() => of<GuestShowState>({status: 'error', message: 'Live-Aktualisierung fehlgeschlagen.'}))
)
);
}),
catchError(() => of<GuestShowState>({status: 'error', message: 'Gastansicht konnte nicht geladen werden.'}))
)
)
)
); );
public config$ = this.configService.get$();
public trackBy = (index: number, show: Song) => show.id; public trackBy = (index: number, show: Song) => show.id;
private normalizeShow(show: GuestShow | null): GuestShowView | null {
if (!show) {
return null;
}
return {
...show,
date: this.toDate(show.date),
updatedAt: this.toDate(show.updatedAt ?? null),
songs: Array.isArray(show.songs) ? show.songs : [],
};
}
private toDate(value: unknown): Date | null {
if (value instanceof Date) {
return value;
}
if (typeof value === 'object' && value !== null) {
if (this.hasToDate(value)) {
return value.toDate();
}
if ('seconds' in value && typeof value.seconds === 'number') {
return new Date(value.seconds * 1000);
}
}
if (typeof value === 'string' || typeof value === 'number') {
const parsedDate = new Date(value);
return Number.isNaN(parsedDate.getTime()) ? null : parsedDate;
}
return null;
}
private hasToDate(value: object): value is FirestoreDateLike {
return 'toDate' in value && typeof value.toDate === 'function';
}
} }
interface GuestShowView extends Omit<GuestShow, 'date' | 'updatedAt'> {
date: Date | null;
updatedAt: Date | null;
}
type GuestShowState = {status: 'loading'} | {status: 'not-found'} | {status: 'error'; message: string} | {status: 'loaded'; show: GuestShowView};
type FirestoreDateLike = {
toDate: () => Date;
};

View File

@@ -1,27 +1,17 @@
@if (song) { @if (song) { @if (song.artist) {
@if (song.artist) { <p>{{ song.artist }}</p>
<p>{{ song.artist }}</p> } @if (song.label) {
<p>{{ song.label }}</p>
} @if (song.termsOfUse) {
<p class="terms-of-use">{{ song.termsOfUse }}</p>
} @if (song.origin) {
<p>{{ song.origin }}</p>
} @if (song.legalOwnerId) {
<div>
@if (song.legalOwner === 'CCLI' && config) {
<p>CCLI-Liednummer {{ song.legalOwnerId }}, CCLI-Lizenznummer {{ config.ccliLicenseId }}</p>
} @if (song.legalOwner !== 'CCLI') {
<p>Liednummer {{ song.legalOwnerId }}</p>
} }
@if (song.label) { </div>
<p>{{ song.label }}</p> } }
}
@if (song.termsOfUse) {
<p class="terms-of-use">{{ song.termsOfUse }}</p>
}
@if (song.origin) {
<p>{{ song.origin }}</p>
}
@if (song.legalOwnerId) {
<div>
@if (song.legalOwner === 'CCLI' && config) {
<p>
CCLI-Liednummer {{ song.legalOwnerId }}, CCLI-Lizenznummer
{{ config.ccliLicenseId }}
</p>
}
@if (song.legalOwner !== 'CCLI') {
<p>Liednummer {{ song.legalOwnerId }}</p>
}
</div>
}
}

View File

@@ -1,4 +1,4 @@
import {ComponentFixture, TestBed, waitForAsync} from '@angular/core/testing'; import {ComponentFixture, TestBed} from '@angular/core/testing';
import {LegalComponent} from './legal.component'; import {LegalComponent} from './legal.component';
@@ -6,11 +6,11 @@ describe('LegalComponent', () => {
let component: LegalComponent; let component: LegalComponent;
let fixture: ComponentFixture<LegalComponent>; let fixture: ComponentFixture<LegalComponent>;
beforeEach(waitForAsync(() => { beforeEach(async () => {
void TestBed.configureTestingModule({ await TestBed.configureTestingModule({
imports: [LegalComponent], imports: [LegalComponent],
}).compileComponents(); }).compileComponents();
})); });
beforeEach(() => { beforeEach(() => {
fixture = TestBed.createComponent(LegalComponent); fixture = TestBed.createComponent(LegalComponent);

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 13 KiB

After

Width:  |  Height:  |  Size: 14 KiB

View File

@@ -1,4 +1,4 @@
import {ComponentFixture, TestBed, waitForAsync} from '@angular/core/testing'; import {ComponentFixture, TestBed} from '@angular/core/testing';
import {LogoComponent} from './logo.component'; import {LogoComponent} from './logo.component';
@@ -6,11 +6,11 @@ describe('LogoComponent', () => {
let component: LogoComponent; let component: LogoComponent;
let fixture: ComponentFixture<LogoComponent>; let fixture: ComponentFixture<LogoComponent>;
beforeEach(waitForAsync(() => { beforeEach(async () => {
void TestBed.configureTestingModule({ await TestBed.configureTestingModule({
imports: [LogoComponent], imports: [LogoComponent],
}).compileComponents(); }).compileComponents();
})); });
beforeEach(() => { beforeEach(() => {
fixture = TestBed.createComponent(LogoComponent); fixture = TestBed.createComponent(LogoComponent);

View File

@@ -1,50 +1,43 @@
<div class="fullscreen background"></div> <div class="fullscreen background"></div>
@if (showType) { @if (showType) {
<div [style.font-size.px]="zoom" class="fullscreen background"> <div [style.font-size.px]="zoom" class="fullscreen background">
<div [class.visible]="presentationBackground==='blue'" class="bg-blue fullscreen bg-image"></div> <div [class.visible]="presentationBackground==='blue'" class="bg-blue fullscreen bg-image"></div>
<div [class.visible]="presentationBackground==='green'" class="bg-green fullscreen bg-image"></div> <div [class.visible]="presentationBackground==='green'" class="bg-green fullscreen bg-image"></div>
<div [class.visible]="presentationBackground==='leder'" class="bg-leder fullscreen bg-image"></div> <div [class.visible]="presentationBackground==='leder'" class="bg-leder fullscreen bg-image"></div>
<div [class.visible]="presentationBackground==='praise'" class="bg-praise fullscreen bg-image"></div> <div [class.visible]="presentationBackground==='praise'" class="bg-praise fullscreen bg-image"></div>
<div [class.visible]="presentationBackground==='bible'" class="bg-bible fullscreen bg-image"></div> <div [class.visible]="presentationBackground==='bible'" class="bg-bible fullscreen bg-image"></div>
<div <div
[@songSwitch]="songId" [@songSwitch]="songId"
[class.blur]="songId === 'title' || songId === 'dynamicText'" [class.blur]="songId === 'title' || songId === 'dynamicText'"
[class.hide]="songId !== 'title' && songId !== 'empty' && songId !== 'dynamicText'" [class.hide]="songId !== 'title' && songId !== 'empty' && songId !== 'dynamicText'"
[class.no-logo]="presentationBackground!=='none'" [class.no-logo]="presentationBackground!=='none'"
class="start fullscreen logo" class="start fullscreen logo"
> >
<app-logo></app-logo> <app-logo></app-logo>
</div>
@if (songId === 'title') {
<div @songSwitch class="start fullscreen">
<div>{{ showType | showType }}</div>
<div class="date">{{ date | date: "dd.MM.yyyy" }}</div>
</div>
}
@if (songId === 'dynamicText') {
<div @songSwitch class="start fullscreen dynamic-text">
<div>{{ presentationDynamicCaption }}</div>
<div class="date">{{ presentationDynamicText }}</div>
</div>
}
@if (song && songId !== 'title' && songId !== 'empty' && songId !== 'dynamicText') {
<app-song-text
[@songSwitch]="songId"
[fullscreen]="true"
[header]="song.title"
[index]="index??0"
[showComments]="false"
[showSwitch]="false"
[text]="song.text"
chordMode="hide"
></app-song-text>
}
@if (song && songId !== 'title' && songId !== 'empty' && songId !== 'dynamicText') {
<app-legal
[@songSwitch]="songId"
[config]="config$ | async"
[song]="song"
></app-legal>
}
</div> </div>
@if (songId === 'title') {
<div @songSwitch class="start fullscreen">
<div>{{ showType | showType }}</div>
<div class="date">{{ date | date: "dd.MM.yyyy" }}</div>
</div>
} @if (songId === 'dynamicText') {
<div @songSwitch class="start fullscreen dynamic-text">
<div>{{ presentationDynamicCaption }}</div>
<div class="date">{{ presentationDynamicText }}</div>
</div>
} @if (song && songId !== 'title' && songId !== 'empty' && songId !== 'dynamicText') {
<app-song-text
[@songSwitch]="songId"
[fullscreen]="true"
[header]="song.title"
[index]="index??0"
[showComments]="false"
[showSwitch]="false"
[text]="song.text"
chordMode="hide"
></app-song-text>
} @if (song && songId !== 'title' && songId !== 'empty' && songId !== 'dynamicText') {
<app-legal [@songSwitch]="songId" [config]="config$ | async" [song]="song"></app-legal>
}
</div>
} }

View File

@@ -36,7 +36,7 @@
filter: blur(10px); filter: blur(10px);
&.visible { &.visible {
opacity: 0.5; opacity: 0.7;
} }
} }
@@ -54,7 +54,7 @@
filter: blur(5px); filter: blur(5px);
&.visible { &.visible {
opacity: 0.4; opacity: 0.6;
} }
} }
@@ -63,7 +63,7 @@
filter: blur(8px); filter: blur(8px);
&.visible { &.visible {
opacity: 0.2; opacity: 0.4;
} }
} }
@@ -72,7 +72,7 @@
filter: blur(8px); filter: blur(8px);
&.visible { &.visible {
opacity: 0.2; opacity: 0.4;
} }
} }

View File

@@ -1,4 +1,4 @@
import {ComponentFixture, TestBed, waitForAsync} from '@angular/core/testing'; import {ComponentFixture, TestBed} from '@angular/core/testing';
import {MonitorComponent} from './monitor.component'; import {MonitorComponent} from './monitor.component';
@@ -6,11 +6,11 @@ describe('MonitorComponent', () => {
let component: MonitorComponent; let component: MonitorComponent;
let fixture: ComponentFixture<MonitorComponent>; let fixture: ComponentFixture<MonitorComponent>;
beforeEach(waitForAsync(() => { beforeEach(async () => {
void TestBed.configureTestingModule({ await TestBed.configureTestingModule({
imports: [MonitorComponent], imports: [MonitorComponent],
}).compileComponents(); }).compileComponents();
})); });
beforeEach(() => { beforeEach(() => {
fixture = TestBed.createComponent(MonitorComponent); fixture = TestBed.createComponent(MonitorComponent);

View File

@@ -43,6 +43,7 @@ export class MonitorComponent implements OnInit, OnDestroy {
public config$: Observable<Config | null>; public config$: Observable<Config | null>;
public presentationBackground: PresentationBackground = 'none'; public presentationBackground: PresentationBackground = 'none';
private destroy$ = new Subject<void>(); private destroy$ = new Subject<void>();
private songSwitchTimeoutId: ReturnType<typeof setTimeout> | null = null;
public constructor() { public constructor() {
const configService = this.configService; const configService = this.configService;
@@ -97,7 +98,10 @@ export class MonitorComponent implements OnInit, OnDestroy {
if (this.songId !== presentationSongId) { if (this.songId !== presentationSongId) {
this.songId = 'empty'; this.songId = 'empty';
} }
setTimeout(() => { if (this.songSwitchTimeoutId) {
clearTimeout(this.songSwitchTimeoutId);
}
this.songSwitchTimeoutId = setTimeout(() => {
this.songId = presentationSongId; this.songId = presentationSongId;
this.cRef.markForCheck(); this.cRef.markForCheck();
}, 600); }, 600);
@@ -113,6 +117,9 @@ export class MonitorComponent implements OnInit, OnDestroy {
} }
public ngOnDestroy(): void { public ngOnDestroy(): void {
if (this.songSwitchTimeoutId) {
clearTimeout(this.songSwitchTimeoutId);
}
this.destroy$.next(); this.destroy$.next();
this.destroy$.complete(); this.destroy$.complete();
} }

View File

@@ -1,23 +1,34 @@
@if (show) { <app-page-frame title="Präsentation" [withMenu]="false">
<div @fade> @if (show) {
<app-card [closeIcon]="faIcon" [heading]="show.showType | showType" <app-card [closeIcon]="faIcon"
[subheading]="show.date.toDate() | date:'dd.MM.yyyy'" closeLink="/presentation/select"> [heading]="show.showType | showType"
[subheading]="show.date.toDate() | date:'dd.MM.yyyy'"
closeLink="/presentation/select"
content>
@if (!progress) { @if (!progress) {
<div class="song"> <div class="song">
@if (show) { @if (show) {
<div class="song-parts"> <div class="song-parts">
<div <div
(click)="onSectionClick('title', -1, show.id)" (click)="onSectionClick('title', -1, show.id)"
(keydown.enter)="onSectionClick('title', -1, show.id)"
(keydown.space)="onSectionClick('title', -1, show.id)"
[class.active]="show.presentationSongId === 'title'" [class.active]="show.presentationSongId === 'title'"
class="song-part" class="song-part"
> role="button"
tabindex="0"
>
<div class="head">Veranstaltung</div> <div class="head">Veranstaltung</div>
</div> </div>
<div <div
(click)="onSectionClick('empty', -1, show.id)" (click)="onSectionClick('empty', -1, show.id)"
(keydown.enter)="onSectionClick('empty', -1, show.id)"
(keydown.space)="onSectionClick('empty', -1, show.id)"
[class.active]="show.presentationSongId === 'empty'" [class.active]="show.presentationSongId === 'empty'"
class="song-part" class="song-part"
> role="button"
tabindex="0"
>
<div class="head">Leer</div> <div class="head">Leer</div>
</div> </div>
</div> </div>
@@ -26,29 +37,35 @@
@for (song of presentationSongs; track trackBy($index, song)) { @for (song of presentationSongs; track trackBy($index, song)) {
<div class="song"> <div class="song">
@if (show) { @if (show) {
<div <div [class.active]="show.presentationSongId === song.id" class="title song-part">
[class.active]="show.presentationSongId === song.id" <div
class="title song-part" (click)="onSectionClick(song.id, -1, show.id)"
(keydown.enter)="onSectionClick(song.id, -1, show.id)"
(keydown.space)="onSectionClick(song.id, -1, show.id)"
class="head"
role="button"
tabindex="0"
> >
<div (click)="onSectionClick(song.id, -1, show.id)" class="head">
{{ song.title }} {{ song.title }}
</div> </div>
</div> </div>
} }
@if (show) { @if (show) {
<div class="song-parts"> <div class="song-parts">
@for (section of song.sections; track section; let i = $index) { @for (section of song.sections; track section.type + '-' + section.number + '-' + $index; let i = $index) {
<div <div
(click)="onSectionClick(song.id, i, show.id)" (click)="onSectionClick(song.id, i, show.id)"
[class.active]=" (keydown.enter)="onSectionClick(song.id, i, show.id)"
(keydown.space)="onSectionClick(song.id, i, show.id)"
[class.active]="
show.presentationSongId === song.id && show.presentationSongId === song.id &&
show.presentationSection === i show.presentationSection === i
" "
class="song-part" class="song-part"
> role="button"
<div class="head"> tabindex="0"
{{ section.type | sectionType }} {{ section.number + 1 }} >
</div> <div class="head">{{ section.type | sectionType }} {{ section.number + 1 }}</div>
<div class="fragment">{{ getFirstLine(section) }}</div> <div class="fragment">{{ getFirstLine(section) }}</div>
</div> </div>
} }
@@ -58,11 +75,15 @@
} }
<div class="song"> <div class="song">
@if (show) { @if (show) {
<div <div [class.active]="show.presentationSongId === 'dynamicText'" class="title song-part">
[class.active]="show.presentationSongId === 'dynamicText'" <div
class="title song-part" (click)="onSectionClick('dynamicText', -1, show.id)"
(keydown.enter)="onSectionClick('dynamicText', -1, show.id)"
(keydown.space)="onSectionClick('dynamicText', -1, show.id)"
class="head"
role="button"
tabindex="0"
> >
<div (click)="onSectionClick('dynamicText', -1, show.id)" class="head">
Freier Text Freier Text
</div> </div>
</div> </div>
@@ -70,28 +91,21 @@
<mat-form-field appearance="outline"> <mat-form-field appearance="outline">
<mat-label>Überschrift</mat-label> <mat-label>Überschrift</mat-label>
<input (ngModelChange)="onDynamicCaption($event, show.id)" [ngModel]="show.presentationDynamicCaption" <input (ngModelChange)="onDynamicCaption($event, show.id)" [ngModel]="show.presentationDynamicCaption"
autocomplete="off" id="dynamic-caption" autocomplete="off" id="dynamic-caption" matInput type="text" />
matInput
type="text">
</mat-form-field> </mat-form-field>
<mat-form-field appearance="outline"> <mat-form-field appearance="outline">
<mat-label>Text</mat-label> <mat-label>Text</mat-label>
<textarea (ngModelChange)="onDynamicText($event, show.id)" [ngModel]="show.presentationDynamicText" <textarea (ngModelChange)="onDynamicText($event, show.id)" [ngModel]="show.presentationDynamicText"
autocomplete="off" id="dynamic-text" autocomplete="off" id="dynamic-text" matInput></textarea>
matInput></textarea>
</mat-form-field> </mat-form-field>
</div> </div>
@if (show) { @if (show) {
<div class="div-bottom"> <div class="div-bottom">
<button class="btn-start-presentation" mat-button routerLink="/presentation/monitor"> <app-button [icon]="faDesktop" routerLink="/presentation/monitor">Präsentation starten</app-button>
<fa-icon [icon]="faDesktop"></fa-icon>
Präsentation starten
</button>
<mat-form-field appearance="outline"> <mat-form-field appearance="outline">
<mat-label>Hintergrund</mat-label> <mat-label>Hintergrund</mat-label>
<mat-select <mat-select (ngModelChange)="onBackground($event, show.id)" [ngModel]="show.presentationBackground">
(ngModelChange)="onBackground($event, show.id)"
[ngModel]="show.presentationBackground">
<mat-option value="none">kein Hintergrund</mat-option> <mat-option value="none">kein Hintergrund</mat-option>
<mat-option value="blue">Sternenhimmel</mat-option> <mat-option value="blue">Sternenhimmel</mat-option>
<mat-option value="green">Blätter</mat-option> <mat-option value="green">Blätter</mat-option>
@@ -100,29 +114,15 @@
<mat-option value="bible">Bibel</mat-option> <mat-option value="bible">Bibel</mat-option>
</mat-select> </mat-select>
</mat-form-field> </mat-form-field>
<mat-slider <mat-slider #slider [max]="100" [min]="10" [step]="2" class="zoom-slider" color="primary" ngDefaultControl
#slider ><input (ngModelChange)="onZoom($event, show.id)" [ngModel]="show.presentationZoom" matSliderThumb />
[max]="100"
[min]="10"
[step]="2"
class="zoom-slider"
color="primary"
ngDefaultControl
><input (ngModelChange)="onZoom($event, show.id)"
[ngModel]="show.presentationZoom"
matSliderThumb>
</mat-slider> </mat-slider>
</div> </div>
} }
@if (show) { @if (show) {
<app-add-song <app-add-song [addedLive]="true" [showSongs]="showSongs" [show]="show" [songs]="songs$|async"></app-add-song>
[addedLive]="true"
[showSongs]="showSongs"
[show]="show"
[songs]="songs$|async"
></app-add-song>
} }
} }
</app-card> </app-card>
</div> }
} </app-page-frame>

View File

@@ -1,4 +1,4 @@
import {ComponentFixture, TestBed, waitForAsync} from '@angular/core/testing'; import {ComponentFixture, TestBed} from '@angular/core/testing';
import {RemoteComponent} from './remote.component'; import {RemoteComponent} from './remote.component';
@@ -6,11 +6,11 @@ describe('RemoteComponent', () => {
let component: RemoteComponent; let component: RemoteComponent;
let fixture: ComponentFixture<RemoteComponent>; let fixture: ComponentFixture<RemoteComponent>;
beforeEach(waitForAsync(() => { beforeEach(async () => {
void TestBed.configureTestingModule({ await TestBed.configureTestingModule({
imports: [RemoteComponent], imports: [RemoteComponent],
}).compileComponents(); }).compileComponents();
})); });
beforeEach(() => { beforeEach(() => {
fixture = TestBed.createComponent(RemoteComponent); fixture = TestBed.createComponent(RemoteComponent);

View File

@@ -1,4 +1,4 @@
import {ChangeDetectionStrategy, ChangeDetectorRef, Component, OnDestroy, inject} from '@angular/core'; import {ChangeDetectionStrategy, ChangeDetectorRef, Component, inject, OnDestroy} from '@angular/core';
import {combineLatest, Subject} from 'rxjs'; import {combineLatest, Subject} from 'rxjs';
import {PresentationBackground, Show} from '../../shows/services/show'; import {PresentationBackground, Show} from '../../shows/services/show';
import {ShowSongService} from '../../shows/services/show-song.service'; import {ShowSongService} from '../../shows/services/show-song.service';
@@ -17,15 +17,15 @@ import {CardComponent} from '../../../widget-modules/components/card/card.compon
import {MatFormField, MatLabel} from '@angular/material/form-field'; import {MatFormField, MatLabel} from '@angular/material/form-field';
import {MatInput} from '@angular/material/input'; import {MatInput} from '@angular/material/input';
import {FormsModule, ReactiveFormsModule} from '@angular/forms'; import {FormsModule, ReactiveFormsModule} from '@angular/forms';
import {MatButton} from '@angular/material/button';
import {RouterLink} from '@angular/router'; import {RouterLink} from '@angular/router';
import {FaIconComponent} from '@fortawesome/angular-fontawesome';
import {MatSelect} from '@angular/material/select'; import {MatSelect} from '@angular/material/select';
import {MatOption} from '@angular/material/core'; import {MatOption} from '@angular/material/core';
import {MatSlider, MatSliderThumb} from '@angular/material/slider'; import {MatSlider, MatSliderThumb} from '@angular/material/slider';
import {AddSongComponent} from '../../../widget-modules/components/add-song/add-song.component'; import {AddSongComponent} from '../../../widget-modules/components/add-song/add-song.component';
import {ShowTypePipe} from '../../../widget-modules/pipes/show-type-translater/show-type.pipe'; import {ShowTypePipe} from '../../../widget-modules/pipes/show-type-translater/show-type.pipe';
import {SectionTypePipe} from '../../../widget-modules/pipes/section-type-translator/section-type.pipe'; import {SectionTypePipe} from '../../../widget-modules/pipes/section-type-translator/section-type.pipe';
import {PageFrameComponent} from '../../../widget-modules/components/sidebar/page-frame.component';
import {ButtonComponent} from '../../../widget-modules/components/button/button.component';
export interface PresentationSong { export interface PresentationSong {
id: string; id: string;
@@ -46,9 +46,7 @@ export interface PresentationSong {
MatInput, MatInput,
ReactiveFormsModule, ReactiveFormsModule,
FormsModule, FormsModule,
MatButton,
RouterLink, RouterLink,
FaIconComponent,
MatSelect, MatSelect,
MatOption, MatOption,
MatSlider, MatSlider,
@@ -58,6 +56,8 @@ export interface PresentationSong {
DatePipe, DatePipe,
ShowTypePipe, ShowTypePipe,
SectionTypePipe, SectionTypePipe,
PageFrameComponent,
ButtonComponent,
], ],
}) })
export class RemoteComponent implements OnDestroy { export class RemoteComponent implements OnDestroy {
@@ -87,12 +87,12 @@ export class RemoteComponent implements OnDestroy {
map(_ => _.currentShow), map(_ => _.currentShow),
filter((showId): showId is string => !!showId), filter((showId): showId is string => !!showId),
distinctUntilChanged(), distinctUntilChanged(),
takeUntil(this.destroy$) takeUntil(this.destroy$),
); );
const show$ = currentShowId$.pipe( const show$ = currentShowId$.pipe(
switchMap(showId => this.showService.read$(showId)), switchMap(showId => this.showService.read$(showId)),
takeUntil(this.destroy$) takeUntil(this.destroy$),
); );
const parsedSongs$ = currentShowId$.pipe( const parsedSongs$ = currentShowId$.pipe(
@@ -105,7 +105,7 @@ export class RemoteComponent implements OnDestroy {
sections: this.textRenderingService.parse(song.text, null, false), sections: this.textRenderingService.parse(song.text, null, false),
})), })),
})), })),
takeUntil(this.destroy$) takeUntil(this.destroy$),
); );
combineLatest([show$, parsedSongs$]) combineLatest([show$, parsedSongs$])
@@ -120,9 +120,11 @@ export class RemoteComponent implements OnDestroy {
}); });
this.presentationDynamicCaptionChanged$ this.presentationDynamicCaptionChanged$
.pipe(debounceTime(1000)) .pipe(debounceTime(1000), takeUntil(this.destroy$))
.subscribe(_ => void this.showService.update$(_.showId, {presentationDynamicCaption: _.presentationDynamicCaption})); .subscribe(_ => void this.showService.update$(_.showId, {presentationDynamicCaption: _.presentationDynamicCaption}));
this.presentationDynamicTextChanged$.pipe(debounceTime(1000)).subscribe(_ => void this.showService.update$(_.showId, {presentationDynamicText: _.presentationDynamicText})); this.presentationDynamicTextChanged$
.pipe(debounceTime(1000), takeUntil(this.destroy$))
.subscribe(_ => void this.showService.update$(_.showId, {presentationDynamicText: _.presentationDynamicText}));
} }
public trackBy(index: number, item: PresentationSong): string { public trackBy(index: number, item: PresentationSong): string {

View File

@@ -1,25 +1,24 @@
@if (shows$ | async; as shows) { <app-page-frame title="Präsentation" [withMenu]="false">
<div @fade> @if (shows$ | async; as shows) {
@if (visible) { <div @fade content>
<app-card heading="Bitte eine Veranstaltung auswählen"> @if (visible) {
@if (!shows.length) { <app-card heading="Bitte eine Veranstaltung auswählen">
<p> @if (!shows.length) {
Es ist derzeit keine Veranstaltung vorhanden <p>Es ist derzeit keine Veranstaltung vorhanden</p>
</p> }
} @if (shows.length > 0) {
@if (shows.length>0) { <div class="list">
<div class="list"> @for (show of shows; track show.id) {
@for (show of shows; track show) { <app-button (click)="selectShow(show)" class="full-width">
<button (click)="selectShow(show)" mat-stroked-button> <app-user-name [userId]="show.owner"></app-user-name>
<app-user-name [userId]="show.owner"></app-user-name> , {{ show.showType | showType }}, {{ show.date.toDate() | date: "dd.MM.yyyy" }}
, </app-button>
{{ show.showType | showType }},
{{ show.date.toDate() | date: "dd.MM.yyyy" }} }
</button> </div>
} }
</div> </app-card>
} }
</app-card> </div>
} }
</div> </app-page-frame>
}

View File

@@ -0,0 +1,69 @@
import {ComponentFixture, TestBed} from '@angular/core/testing';
import {Router} from '@angular/router';
import {firstValueFrom, of} from 'rxjs';
import {GlobalSettingsService} from '../../../services/global-settings.service';
import {ShowService} from '../../shows/services/show.service';
import {SelectComponent} from './select.component';
describe('SelectComponent', () => {
let component: SelectComponent;
let fixture: ComponentFixture<SelectComponent>;
let showServiceSpy: jasmine.SpyObj<ShowService>;
let globalSettingsServiceSpy: jasmine.SpyObj<GlobalSettingsService>;
let routerSpy: jasmine.SpyObj<Router>;
const createShow = (id: string, isoDate: string) => ({id, date: {toDate: () => new Date(isoDate)}});
beforeEach(async () => {
showServiceSpy = jasmine.createSpyObj<ShowService>('ShowService', ['list$', 'update$']);
globalSettingsServiceSpy = jasmine.createSpyObj<GlobalSettingsService>('GlobalSettingsService', ['set']);
routerSpy = jasmine.createSpyObj<Router>('Router', ['navigateByUrl']);
showServiceSpy.list$.and.returnValue(
of([createShow('older', '2025-12-15T00:00:00Z'), createShow('recent-a', '2026-03-01T00:00:00Z'), createShow('recent-b', '2026-02-20T00:00:00Z')]) as never
);
showServiceSpy.update$.and.resolveTo();
globalSettingsServiceSpy.set.and.resolveTo();
routerSpy.navigateByUrl.and.resolveTo(true);
await TestBed.configureTestingModule({
imports: [SelectComponent],
providers: [
{provide: ShowService, useValue: showServiceSpy},
{provide: GlobalSettingsService, useValue: globalSettingsServiceSpy},
{provide: Router, useValue: routerSpy},
],
}).compileComponents();
fixture = TestBed.createComponent(SelectComponent);
component = fixture.componentInstance;
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should become visible on init', () => {
component.ngOnInit();
expect(component.visible).toBeTrue();
});
it('should expose recent shows sorted descending by date', async () => {
const shows = await firstValueFrom(component.shows$);
expect(showServiceSpy.list$).toHaveBeenCalledWith(true);
expect(shows.map(show => show.id)).toEqual(['recent-a', 'recent-b']);
});
it('should persist the selected show, trigger presentation reset and navigate', async () => {
const show = {id: 'show-1'} as never;
component.visible = true;
await component.selectShow(show);
expect(component.visible).toBeFalse();
expect(globalSettingsServiceSpy.set).toHaveBeenCalledWith({currentShow: 'show-1'});
expect(showServiceSpy.update$).toHaveBeenCalledWith('show-1', {presentationSongId: 'title'});
expect(routerSpy.navigateByUrl).toHaveBeenCalledWith('/presentation/remote');
});
});

View File

@@ -1,4 +1,4 @@
import {Component, OnInit, inject} from '@angular/core'; import {Component, inject, OnInit} from '@angular/core';
import {map} from 'rxjs/operators'; import {map} from 'rxjs/operators';
import {ShowService} from '../../shows/services/show.service'; import {ShowService} from '../../shows/services/show.service';
import {Show} from '../../shows/services/show'; import {Show} from '../../shows/services/show';
@@ -7,16 +7,17 @@ import {Router} from '@angular/router';
import {fade} from '../../../animations'; import {fade} from '../../../animations';
import {AsyncPipe, DatePipe} from '@angular/common'; import {AsyncPipe, DatePipe} from '@angular/common';
import {CardComponent} from '../../../widget-modules/components/card/card.component'; import {CardComponent} from '../../../widget-modules/components/card/card.component';
import {MatButton} from '@angular/material/button';
import {UserNameComponent} from '../../../services/user/user-name/user-name.component'; import {UserNameComponent} from '../../../services/user/user-name/user-name.component';
import {ShowTypePipe} from '../../../widget-modules/pipes/show-type-translater/show-type.pipe'; import {ShowTypePipe} from '../../../widget-modules/pipes/show-type-translater/show-type.pipe';
import {PageFrameComponent} from '../../../widget-modules/components/sidebar/page-frame.component';
import {ButtonComponent} from '../../../widget-modules/components/button/button.component';
@Component({ @Component({
selector: 'app-select', selector: 'app-select',
templateUrl: './select.component.html', templateUrl: './select.component.html',
styleUrls: ['./select.component.less'], styleUrls: ['./select.component.less'],
animations: [fade], animations: [fade],
imports: [CardComponent, MatButton, UserNameComponent, AsyncPipe, DatePipe, ShowTypePipe], imports: [CardComponent, UserNameComponent, AsyncPipe, DatePipe, ShowTypePipe, PageFrameComponent, ButtonComponent],
}) })
export class SelectComponent implements OnInit { export class SelectComponent implements OnInit {
private showService = inject(ShowService); private showService = inject(ShowService);

View File

@@ -5,8 +5,8 @@ import {PresentationService} from './presentation.service';
describe('PresentationService', () => { describe('PresentationService', () => {
let service: PresentationService; let service: PresentationService;
beforeEach(() => { beforeEach(async () => {
void TestBed.configureTestingModule({}); await TestBed.configureTestingModule({});
service = TestBed.inject(PresentationService); service = TestBed.inject(PresentationService);
}); });

View File

@@ -3,7 +3,5 @@
</div> </div>
<div mat-dialog-actions> <div mat-dialog-actions>
<button [mat-dialog-close]="false" mat-button>Abbrechen</button> <button [mat-dialog-close]="false" mat-button>Abbrechen</button>
<button [mat-dialog-close]="true" cdkFocusInitial mat-button> <button [mat-dialog-close]="true" cdkFocusInitial mat-button>Archivieren</button>
Archivieren
</button>
</div> </div>

View File

@@ -0,0 +1,41 @@
<div mat-dialog-content>
<p>Bitte melde die in dieser Veranstaltung verwendeten CCLI-Titel. Die Meldung ist Teil der CCLI-Lizenz und sorgt
dafür, dass Songwriter und Verlage korrekt vergütet werden.</p>
<p>
Die Meldung erfolgt über
<a [href]="reportingUrl" rel="noreferrer" target="_blank">{{ reportingUrl }}</a>.
</p>
<div class="song-list">
<div class="list-head">
<div>Titel</div>
<div>CCLI-Nummer</div>
</div>
@for (song of data.songs; track song.title + song.ccliNumber) {
<div class="list-item">
<div>{{ song.title }}</div>
<div class="number-cell">
<span>{{ song.ccliNumber }}</span>
<a
(click)="markOpened(song.ccliNumber)"
[attr.aria-label]="'CCLI-Titel melden: ' + song.title"
[href]="getSongReportingUrl(song.ccliNumber)"
rel="noreferrer"
target="_blank"
class="btn-icon report-link"
>
<fa-icon [icon]="faOpen"></fa-icon>
</a>
@if (wasOpened(song.ccliNumber)) {
<fa-icon [icon]="faCheck" class="opened-check"></fa-icon>
}
</div>
</div>
}
</div>
</div>
<app-button-row>
<app-button (click)="dialogRef.close(false)" [icon]="faClose">Abbrechen</app-button>
<app-button (click)="dialogRef.close(true)" [icon]="faReport">Alle CCLI-Titel wurden gemeldet</app-button>
</app-button-row>

View File

@@ -0,0 +1,78 @@
.song-list {
width: 100%;
}
.list-head,
.list-item {
display: grid;
grid-template-columns: auto 180px;
gap: 0;
align-items: center;
border-bottom: 1px solid var(--overlay)
}
.list-head {
padding: 3px 10px;
color: var(--text-soft);
font-size: 0.85rem;
font-weight: 600;
}
.list-item {
padding: 3px 10px;
transition: var(--transition);
&:not(:last-child) {
border-bottom: 1px solid var(--divider)
}
}
.list-head > div,
.list-item > div {
display: flex;
align-items: center;
}
.number-cell {
display: flex;
align-items: center;
gap: 6px;
white-space: nowrap;
}
.report-link {
display: inline-flex;
align-items: center;
color: inherit;
text-decoration: none;
}
.opened-check {
color: var(--success);
font-size: 0.85rem;
}
@media screen and (max-width: 640px) {
.list-head,
.list-item {
grid-template-columns: 1fr;
gap: 4px;
}
.list-head {
display: none;
}
.list-item {
padding: 10px 16px;
}
.number-cell {
justify-content: flex-start;
}
}
app-button-row {
margin: 0 var(--gap-l) var(--gap-l);
}

View File

@@ -0,0 +1,40 @@
import {ComponentFixture, TestBed} from '@angular/core/testing';
import {MAT_DIALOG_DATA} from '@angular/material/dialog';
import {ReportDialogComponent} from './report-dialog.component';
describe('ReportDialogComponent', () => {
let component: ReportDialogComponent;
let fixture: ComponentFixture<ReportDialogComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [ReportDialogComponent],
providers: [
{
provide: MAT_DIALOG_DATA,
useValue: {songs: [{title: 'Amazing Grace', ccliNumber: '12345'}]},
},
],
}).compileComponents();
fixture = TestBed.createComponent(ReportDialogComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('create an instance', () => {
void expect(component).toBeTruthy();
});
it('should build direct reporting urls', () => {
expect(component.getSongReportingUrl('5770492')).toBe('https://reporting.ccli.com/search?s=5770492');
});
it('should mark numbers as opened locally', () => {
expect(component.wasOpened('12345')).toBeFalse();
component.markOpened('12345');
expect(component.wasOpened('12345')).toBeTrue();
});
});

View File

@@ -0,0 +1,47 @@
import {Component, inject} from '@angular/core';
import {MAT_DIALOG_DATA, MatDialogContent, MatDialogRef} from '@angular/material/dialog';
import {FaIconComponent} from '@fortawesome/angular-fontawesome';
import {faArrowUpRightFromSquare, faCheck, faCompactDisc, faXmark} from '@fortawesome/free-solid-svg-icons';
import {ButtonRowComponent} from '../../../../widget-modules/components/button-row/button-row.component';
import {ButtonComponent} from '../../../../widget-modules/components/button/button.component';
export interface ReportDialogSong {
title: string;
ccliNumber: string;
}
export interface ReportDialogData {
songs: ReportDialogSong[];
}
@Component({
selector: 'app-report-dialog',
imports: [MatDialogContent, FaIconComponent, ButtonRowComponent, ButtonComponent],
templateUrl: './report-dialog.component.html',
styleUrl: './report-dialog.component.less',
standalone: true,
})
export class ReportDialogComponent {
public readonly reportingUrl = 'https://reporting.ccli.com/search';
public readonly faOpen = faArrowUpRightFromSquare;
public readonly faCheck = faCheck;
public data = inject<ReportDialogData>(MAT_DIALOG_DATA);
public dialogRef = inject(MatDialogRef<ReportDialogComponent>);
public faReport = faCompactDisc;
public faClose = faXmark;
private readonly openedNumbers = new Set<string>();
public getSongReportingUrl(ccliNumber: string): string {
return `${this.reportingUrl}?s=${encodeURIComponent(ccliNumber)}`;
}
public markOpened(ccliNumber: string): void {
this.openedNumbers.add(ccliNumber);
}
public wasOpened(ccliNumber: string): boolean {
return this.openedNumbers.has(ccliNumber);
}
}

View File

@@ -1,13 +1,8 @@
<div mat-dialog-content> <div mat-dialog-content>
<a [href]="data.url">{{ data.url }}</a> <a [href]="data.url">{{ data.url }}</a>
<div [style.background-image]="'url('+qrCode+')'" alt="qrcode" class="qrcode"> <div [style.background-image]="'url('+qrCode+')'" alt="qrcode" class="qrcode"></div>
</div>
</div> </div>
<div mat-dialog-actions> <div mat-dialog-actions>
<button [mat-dialog-close]="true" cdkFocusInitial mat-button> <button [mat-dialog-close]="true" cdkFocusInitial mat-button>Schließen</button>
Schließen <button (click)="share()" mat-button>Teilen</button>
</button>
<button (click)="share()" mat-button>
Teilen
</button>
</div> </div>

View File

@@ -1,21 +1,34 @@
import {ComponentFixture, TestBed} from '@angular/core/testing'; import {ComponentFixture, TestBed} from '@angular/core/testing';
import {ShareDialogComponent} from './share-dialog.component'; import {ShareDialogComponent} from './share-dialog.component';
import QRCode from 'qrcode'; import {MAT_DIALOG_DATA} from '@angular/material/dialog';
describe('ShareDialogComponent', () => { describe('ShareDialogComponent', () => {
let component: ShareDialogComponent; let component: ShareDialogComponent;
let fixture: ComponentFixture<ShareDialogComponent>; let fixture: ComponentFixture<ShareDialogComponent>;
type ShareDialogComponentInternals = ShareDialogComponent & {
generateQrCode: () => Promise<string>;
};
beforeEach(async () => { beforeEach(async () => {
spyOn(QRCode, 'toDataURL').and.resolveTo('data:image/jpeg;base64,test');
await TestBed.configureTestingModule({ await TestBed.configureTestingModule({
imports: [ShareDialogComponent], imports: [ShareDialogComponent],
providers: [
{
provide: MAT_DIALOG_DATA,
useValue: {
url: 'https://example.com/guest/1',
show: {
showType: 'service-worship',
date: {toDate: () => new Date('2026-03-20T00:00:00Z')},
},
},
},
],
}).compileComponents(); }).compileComponents();
fixture = TestBed.createComponent(ShareDialogComponent); fixture = TestBed.createComponent(ShareDialogComponent);
component = fixture.componentInstance; component = fixture.componentInstance;
spyOn(component as ShareDialogComponentInternals, 'generateQrCode').and.resolveTo('data:image/jpeg;base64,test');
fixture.detectChanges(); fixture.detectChanges();
}); });

View File

@@ -1,7 +1,6 @@
import {Component, inject} from '@angular/core'; import {Component, inject} from '@angular/core';
import {MAT_DIALOG_DATA, MatDialogActions, MatDialogClose, MatDialogContent} from '@angular/material/dialog'; import {MAT_DIALOG_DATA, MatDialogActions, MatDialogClose, MatDialogContent} from '@angular/material/dialog';
import {MatButton} from '@angular/material/button'; import {MatButton} from '@angular/material/button';
import QRCode from 'qrcode';
import {ShowTypePipe} from '../../../../widget-modules/pipes/show-type-translater/show-type.pipe'; import {ShowTypePipe} from '../../../../widget-modules/pipes/show-type-translater/show-type.pipe';
import {Show} from '../../services/show'; import {Show} from '../../services/show';
@@ -19,26 +18,15 @@ export interface ShareDialogData {
export class ShareDialogComponent { export class ShareDialogComponent {
public data = inject<ShareDialogData>(MAT_DIALOG_DATA); public data = inject<ShareDialogData>(MAT_DIALOG_DATA);
public qrCode: string; public qrCode = '';
public constructor() { public constructor() {
const data = this.data; const data = this.data;
// eslint-disable-next-line @typescript-eslint/no-unsafe-call,@typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-assignment void this.generateQrCode(data.url).then(qrCode => (this.qrCode = qrCode));
QRCode.toDataURL(data.url, {
type: 'image/jpeg',
quality: 0.92,
width: 1280,
height: 1280,
color: {
dark: '#010414',
light: '#ffffff',
},
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-unsafe-return
}).then(_ => (this.qrCode = _));
} }
public async share() { public async share(): Promise<void> {
if (navigator.clipboard) await navigator.clipboard.writeText(this.data.url); if (navigator.clipboard) await navigator.clipboard.writeText(this.data.url);
if (navigator.share) if (navigator.share)
@@ -48,4 +36,18 @@ export class ShareDialogComponent {
url: this.data.url, url: this.data.url,
}); });
} }
private async generateQrCode(url: string): Promise<string> {
const {default: QRCode} = await import('qrcode');
return await QRCode.toDataURL(url, {
type: 'image/jpeg',
quality: 0.92,
width: 1280,
height: 1280,
color: {
dark: '#010414',
light: '#ffffff',
},
});
}
} }

View File

@@ -1,37 +1,33 @@
<div> <app-page-frame title="Veranstaltungen" [withMenu]="false">
<app-card [closeLink]="'/shows/'+form.value.id" heading="Veranstaltung ändern"> <div content>
<div [formGroup]="form" class="split"> <app-card [closeLink]="'/shows/'+form.value.id" heading="Veranstaltung ändern">
<mat-form-field appearance="outline"> <div [formGroup]="form" class="split">
<mat-label>Art der Veranstaltung</mat-label> <mat-form-field appearance="outline">
<mat-select formControlName="showType"> <mat-label>Art der Veranstaltung</mat-label>
<mat-optgroup label="öffentlich"> <mat-select formControlName="showType">
@for (key of showTypePublic; track key) { <mat-optgroup label="öffentlich">
<mat-option [value]="key">{{ @for (key of showTypePublic; track key) {
key | showType <mat-option [value]="key">{{ key | showType }}</mat-option>
}} }
</mat-option> </mat-optgroup>
} <mat-optgroup label="privat">
</mat-optgroup> @for (key of showTypePrivate; track key) {
<mat-optgroup label="privat"> <mat-option [value]="key">{{ key | showType }}</mat-option>
@for (key of showTypePrivate; track key) { }
<mat-option [value]="key">{{ </mat-optgroup>
key | showType </mat-select>
}} </mat-form-field>
</mat-option> <mat-form-field appearance="outline">
} <mat-label>Datum</mat-label>
</mat-optgroup> <input [matDatepicker]="picker" formControlName="date" matInput />
</mat-select> <mat-datepicker-toggle [for]="picker" matSuffix></mat-datepicker-toggle>
</mat-form-field> <mat-datepicker #picker touchUi></mat-datepicker>
<mat-form-field appearance="outline"> </mat-form-field>
<mat-label>Datum</mat-label> </div>
<input [matDatepicker]="picker" formControlName="date" matInput />
<mat-datepicker-toggle [for]="picker" matSuffix></mat-datepicker-toggle>
<mat-datepicker #picker touchUi></mat-datepicker>
</mat-form-field>
</div>
<app-button-row> <app-button-row>
<app-button (click)="onSave()" [icon]="faSave">Speichern</app-button> <app-button (click)="onSave()" [icon]="faSave">Speichern</app-button>
</app-button-row> </app-button-row>
</app-card> </app-card>
</div> </div>
</app-page-frame>

View File

@@ -0,0 +1,83 @@
import {ComponentFixture, TestBed} from '@angular/core/testing';
import {ActivatedRoute, Router} from '@angular/router';
import {Timestamp} from '@angular/fire/firestore';
import {of} from 'rxjs';
import {ShowDataService} from '../services/show-data.service';
import {ShowService} from '../services/show.service';
import {EditComponent} from './edit.component';
describe('EditComponent', () => {
let component: EditComponent;
let fixture: ComponentFixture<EditComponent>;
let showServiceSpy: jasmine.SpyObj<ShowService>;
let showDataServiceStub: Pick<ShowDataService, 'list$'>;
let routerSpy: jasmine.SpyObj<Router>;
const createDate = (isoDate: string) => ({toDate: () => new Date(isoDate)});
beforeEach(async () => {
showServiceSpy = jasmine.createSpyObj<ShowService>('ShowService', ['read$', 'update$']);
showDataServiceStub = {list$: of([]) as ShowDataService['list$']};
routerSpy = jasmine.createSpyObj<Router>('Router', ['navigateByUrl']);
showServiceSpy.read$.and.returnValue(
of({
id: 'show-1',
showType: 'service-worship',
date: createDate('2026-03-10T00:00:00Z'),
} as never)
);
showServiceSpy.update$.and.resolveTo();
routerSpy.navigateByUrl.and.resolveTo(true);
await TestBed.configureTestingModule({
imports: [EditComponent],
providers: [
{provide: ShowService, useValue: showServiceSpy},
{provide: ShowDataService, useValue: showDataServiceStub},
{provide: Router, useValue: routerSpy},
{provide: ActivatedRoute, useValue: {params: of({showId: 'show-1'})}},
],
}).compileComponents();
fixture = TestBed.createComponent(EditComponent);
component = fixture.componentInstance;
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should load the current show into the form on init', () => {
component.ngOnInit();
expect(showServiceSpy.read$).toHaveBeenCalledWith('show-1');
expect(component.form.value.id).toBe('show-1');
expect(component.form.value.showType).toBe('service-worship');
expect(component.form.value.date).toEqual(new Date('2026-03-10T00:00:00Z'));
});
it('should not save when the form is invalid', async () => {
component.form.setValue({id: null, date: null, showType: null});
await component.onSave();
expect(showServiceSpy.update$).not.toHaveBeenCalled();
expect(routerSpy.navigateByUrl).not.toHaveBeenCalled();
});
it('should update the show and navigate back to the detail page', async () => {
const date = new Date('2026-03-11T00:00:00Z');
const firestoreTimestamp = {seconds: 1} as never;
spyOn(Timestamp, 'fromDate').and.returnValue(firestoreTimestamp);
component.form.setValue({id: 'show-1', date, showType: 'home-group'});
await component.onSave();
expect(Timestamp.fromDate).toHaveBeenCalledWith(date);
expect(showServiceSpy.update$).toHaveBeenCalledWith('show-1', {
date: firestoreTimestamp,
showType: 'home-group',
} as never);
expect(routerSpy.navigateByUrl).toHaveBeenCalledWith('/shows/show-1');
});
});

View File

@@ -1,4 +1,4 @@
import {Component, OnInit, inject} from '@angular/core'; import {Component, inject, OnInit} from '@angular/core';
import {ShowDataService} from '../services/show-data.service'; import {ShowDataService} from '../services/show-data.service';
import {Observable, take} from 'rxjs'; import {Observable, take} from 'rxjs';
import {Show} from '../services/show'; import {Show} from '../services/show';
@@ -7,7 +7,7 @@ import {FormControl, FormGroup, ReactiveFormsModule, Validators} from '@angular/
import {ActivatedRoute, Router} from '@angular/router'; import {ActivatedRoute, Router} from '@angular/router';
import {faSave} from '@fortawesome/free-solid-svg-icons'; import {faSave} from '@fortawesome/free-solid-svg-icons';
import {map, switchMap} from 'rxjs/operators'; import {map, switchMap} from 'rxjs/operators';
import {Timestamp} from '@angular/fire/firestore'; import {Timestamp} from 'firebase/firestore';
import {CardComponent} from '../../../widget-modules/components/card/card.component'; import {CardComponent} from '../../../widget-modules/components/card/card.component';
import {MatFormField, MatLabel, MatSuffix} from '@angular/material/form-field'; import {MatFormField, MatLabel, MatSuffix} from '@angular/material/form-field';
import {MatSelect} from '@angular/material/select'; import {MatSelect} from '@angular/material/select';
@@ -18,6 +18,7 @@ import {MatDatepicker, MatDatepickerInput, MatDatepickerToggle} from '@angular/m
import {ButtonRowComponent} from '../../../widget-modules/components/button-row/button-row.component'; import {ButtonRowComponent} from '../../../widget-modules/components/button-row/button-row.component';
import {ButtonComponent} from '../../../widget-modules/components/button/button.component'; import {ButtonComponent} from '../../../widget-modules/components/button/button.component';
import {ShowTypePipe} from '../../../widget-modules/pipes/show-type-translater/show-type.pipe'; import {ShowTypePipe} from '../../../widget-modules/pipes/show-type-translater/show-type.pipe';
import {PageFrameComponent} from '../../../widget-modules/components/sidebar/page-frame.component';
@Component({ @Component({
selector: 'app-edit', selector: 'app-edit',
@@ -39,6 +40,7 @@ import {ShowTypePipe} from '../../../widget-modules/pipes/show-type-translater/s
ButtonRowComponent, ButtonRowComponent,
ButtonComponent, ButtonComponent,
ShowTypePipe, ShowTypePipe,
PageFrameComponent,
], ],
}) })
export class EditComponent implements OnInit { export class EditComponent implements OnInit {
@@ -70,7 +72,7 @@ export class EditComponent implements OnInit {
map(param => param as {showId: string}), map(param => param as {showId: string}),
map(param => param.showId), map(param => param.showId),
switchMap((showId: string) => this.showService.read$(showId)), switchMap((showId: string) => this.showService.read$(showId)),
take(1) take(1),
) )
.subscribe(show => { .subscribe(show => {
this.form.setValue({ this.form.setValue({
@@ -87,10 +89,15 @@ export class EditComponent implements OnInit {
return; return;
} }
await this.showService.update$(this.form.value.id, { const {id, date, showType} = this.form.getRawValue();
date: Timestamp.fromDate(this.form.value.date), if (!id || !date || !showType) {
showType: this.form.value.showType, return;
}
await this.showService.update$(id, {
date: Timestamp.fromDate(date),
showType,
} as Partial<Show>); } as Partial<Show>);
await this.router.navigateByUrl(`/shows/${this.form.value.id ?? ''}`); await this.router.navigateByUrl(`/shows/${id}`);
} }
} }

View File

@@ -2,4 +2,5 @@ export interface FilterValues {
time: number; time: number;
owner: string; owner: string;
showType: string; showType: string;
archived: boolean;
} }

View File

@@ -1,14 +1,10 @@
<div [formGroup]="filterFormGroup"> <div [formGroup]="filterFormGroup">
<div class="third"> <div class="third">
<mat-form-field appearance="outline"> <mat-form-field appearance="outline">
<mat-label>Zeitraum</mat-label> <mat-label>Zeitraum</mat-label>
<mat-select formControlName="time"> <mat-select formControlName="time">
@for (time of times; track time) { @for (time of times; track time) {
<mat-option [value]="time.key">{{ <mat-option [value]="time.key">{{ time.value }}</mat-option>
time.value
}}
</mat-option>
} }
</mat-select> </mat-select>
</mat-form-field> </mat-form-field>
@@ -16,12 +12,9 @@
<mat-form-field appearance="outline"> <mat-form-field appearance="outline">
<mat-label>Ersteller</mat-label> <mat-label>Ersteller</mat-label>
<mat-select formControlName="owner"> <mat-select formControlName="owner">
<mat-option [value]="null">Alle</mat-option> <mat-option value="">Alle</mat-option>
@for (owner of owners; track owner) { @for (owner of owners; track owner) {
<mat-option [value]="owner.key">{{ <mat-option [value]="owner.key">{{ owner.value }}</mat-option>
owner.value
}}
</mat-option>
} }
</mat-select> </mat-select>
</mat-form-field> </mat-form-field>
@@ -29,27 +22,21 @@
<mat-form-field appearance="outline"> <mat-form-field appearance="outline">
<mat-label>Art der Veranstaltung</mat-label> <mat-label>Art der Veranstaltung</mat-label>
<mat-select formControlName="showType"> <mat-select formControlName="showType">
<mat-option [value]="null">Alle</mat-option> <mat-option value="">Alle</mat-option>
<mat-optgroup label="öffentlich"> <mat-optgroup label="öffentlich">
@for (key of showTypePublic; track key) { @for (key of showTypePublic; track key) {
<mat-option [value]="key">{{ <mat-option [value]="key">{{ key | showType }}</mat-option>
key | showType
}}
</mat-option>
} }
</mat-optgroup> </mat-optgroup>
<mat-optgroup label="privat"> <mat-optgroup label="privat">
@for (key of showTypePrivate; track key) { @for (key of showTypePrivate; track key) {
<mat-option [value]="key">{{ <mat-option [value]="key">{{ key | showType }}</mat-option>
key | showType
}}
</mat-option>
} }
</mat-optgroup> </mat-optgroup>
</mat-select> </mat-select>
</mat-form-field> </mat-form-field>
<mat-checkbox formControlName="archived">Archiviert</mat-checkbox>
</div> </div>
<i>Anzahl der Suchergebnisse: {{ shows?.length ?? 0 }}</i> <!-- <i>Anzahl der Suchergebnisse: {{ shows?.length ?? 0 }}</i>-->
</div> </div>

View File

@@ -1,5 +1,14 @@
.third { .third,
display: grid; div[formGroup] {
grid-template-columns: 1fr 1fr 1fr; display: flex;
column-gap: 20px; flex-direction: column;
gap: 12px;
}
.third {
gap: 0;
}
:host ::ng-deep .mat-mdc-form-field {
width: 100%;
} }

View File

@@ -1,7 +1,7 @@
import {Component, Input, inject} from '@angular/core'; import {Component, DestroyRef, inject, Input} from '@angular/core';
import {KeyValue} from '@angular/common'; import {KeyValue} from '@angular/common';
import {ActivatedRoute, Router} from '@angular/router'; import {takeUntilDestroyed} from '@angular/core/rxjs-interop';
import {ReactiveFormsModule, UntypedFormBuilder, UntypedFormGroup} from '@angular/forms'; import {FormBuilder, FormControl, FormGroup, ReactiveFormsModule} from '@angular/forms';
import {FilterValues} from './filter-values'; import {FilterValues} from './filter-values';
import {Show} from '../../services/show'; import {Show} from '../../services/show';
import {ShowService} from '../../services/show.service'; import {ShowService} from '../../services/show.service';
@@ -9,60 +9,71 @@ import {distinctUntilChanged, map, switchMap} from 'rxjs/operators';
import {combineLatest, Observable, of} from 'rxjs'; import {combineLatest, Observable, of} from 'rxjs';
import {dynamicSort, onlyUnique} from '../../../../services/filter.helper'; import {dynamicSort, onlyUnique} from '../../../../services/filter.helper';
import {UserService} from '../../../../services/user/user.service'; import {UserService} from '../../../../services/user/user.service';
import {FilterStoreService} from '../../../../services/filter-store.service';
import {MatFormField, MatLabel} from '@angular/material/form-field'; import {MatFormField, MatLabel} from '@angular/material/form-field';
import {MatSelect} from '@angular/material/select'; import {MatSelect} from '@angular/material/select';
import {MatOptgroup, MatOption} from '@angular/material/core'; import {MatOptgroup, MatOption} from '@angular/material/core';
import {ShowTypePipe} from '../../../../widget-modules/pipes/show-type-translater/show-type.pipe'; import {ShowTypePipe} from '../../../../widget-modules/pipes/show-type-translater/show-type.pipe';
import {MatCheckbox} from '@angular/material/checkbox';
@Component({ @Component({
selector: 'app-filter', selector: 'app-filter',
templateUrl: './filter.component.html', templateUrl: './filter.component.html',
styleUrls: ['./filter.component.less'], styleUrls: ['./filter.component.less'],
imports: [ReactiveFormsModule, MatFormField, MatLabel, MatSelect, MatOption, MatOptgroup, ShowTypePipe], imports: [ReactiveFormsModule, MatFormField, MatLabel, MatSelect, MatOption, MatOptgroup, ShowTypePipe, MatCheckbox],
}) })
export class FilterComponent { export class FilterComponent {
private router = inject(Router);
private showService = inject(ShowService);
private userService = inject(UserService);
@Input() public route = '/shows/';
@Input() public shows: Show[] = []; @Input() public shows: Show[] = [];
public showTypePublic = ShowService.SHOW_TYPE_PUBLIC; public showTypePublic = ShowService.SHOW_TYPE_PUBLIC;
public showTypePrivate = ShowService.SHOW_TYPE_PRIVATE; public showTypePrivate = ShowService.SHOW_TYPE_PRIVATE;
public filterFormGroup: FormGroup<{
public filterFormGroup: UntypedFormGroup; time: FormControl<number>;
owner: FormControl<string | null>;
showType: FormControl<string | null>;
archived: FormControl<boolean>;
}>;
public times: KeyValue<number, string>[] = [ public times: KeyValue<number, string>[] = [
{key: 1, value: 'letzter Monat'}, {key: 1, value: 'letzter Monat'},
{key: 3, value: 'letztes Quartal'}, {key: 3, value: 'letztes Quartal'},
{key: 12, value: 'letztes Jahr'}, {key: 12, value: 'letztes Jahr'},
{key: 99999, value: 'alle'}, {key: 99999, value: 'alle'},
]; ];
public owners: {key: string; value: string}[] = []; public owners: {key: string; value: string}[] = [];
private showService = inject(ShowService);
private userService = inject(UserService);
private filterStore = inject(FilterStoreService);
private destroyRef = inject(DestroyRef);
public constructor() { public constructor() {
const activatedRoute = inject(ActivatedRoute); const fb = inject(FormBuilder);
const fb = inject(UntypedFormBuilder);
this.filterFormGroup = fb.group({ this.filterFormGroup = fb.group({
time: 1, time: fb.nonNullable.control(1),
owner: null, owner: fb.control<string | null>(null),
showType: null, showType: fb.control<string | null>(null),
archived: fb.nonNullable.control(false),
}); });
activatedRoute.queryParams.subscribe(params => { this.filterStore.showFilter$.pipe(takeUntilDestroyed(this.destroyRef)).subscribe(filterValues => {
const filterValues = params as FilterValues; this.filterFormGroup.patchValue(
if (filterValues.time) this.filterFormGroup.controls.time.setValue(+filterValues.time); {
this.filterFormGroup.controls.owner.setValue(filterValues.owner ?? null, {emitEvent: false}); time: filterValues.time,
this.filterFormGroup.controls.showType.setValue(filterValues.showType ?? null, {emitEvent: false}); owner: filterValues.owner || null,
showType: filterValues.showType || null,
archived: !!filterValues.archived,
},
{emitEvent: false}
);
}); });
this.filterFormGroup.controls.time.valueChanges.subscribe(_ => void this.filerValueChanged('time', _ as number)); this.filterFormGroup.controls.time.valueChanges.pipe(takeUntilDestroyed(this.destroyRef)).subscribe(value => this.filterValueChanged('time', value));
this.filterFormGroup.controls.owner.valueChanges.subscribe(_ => void this.filerValueChanged('owner', _ as string)); this.filterFormGroup.controls.owner.valueChanges.pipe(takeUntilDestroyed(this.destroyRef)).subscribe(value => this.filterValueChanged('owner', value ?? ''));
this.filterFormGroup.controls.showType.valueChanges.subscribe(_ => void this.filerValueChanged('showType', _ as string)); this.filterFormGroup.controls.showType.valueChanges.pipe(takeUntilDestroyed(this.destroyRef)).subscribe(value => this.filterValueChanged('showType', value ?? ''));
this.filterFormGroup.controls.archived.valueChanges.pipe(takeUntilDestroyed(this.destroyRef)).subscribe(value => this.filterValueChanged('archived', value));
this.owners$().subscribe(owners => (this.owners = owners)); this.owners$()
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe(owners => (this.owners = owners));
} }
public owners$ = (): Observable<{key: string; value: string}[]> => { public owners$ = (): Observable<{key: string; value: string}[]> => {
@@ -83,26 +94,20 @@ export class FilterComponent {
this.userService.getUserbyId$(ownerId).pipe( this.userService.getUserbyId$(ownerId).pipe(
map(user => ({ map(user => ({
key: ownerId, key: ownerId,
value: user?.name, value: user?.name ?? ownerId,
})) }))
) )
) )
); );
}), }),
map(owners => { map(owners => owners.sort(dynamicSort<{key: string; value: string}>('value'))),
return owners.sort(dynamicSort('value'));
}),
distinctUntilChanged((left, right) => this.sameOwners(left, right)), distinctUntilChanged((left, right) => this.sameOwners(left, right)),
map(_ => _ as {key: string; value: string}[]) map(owners => owners as {key: string; value: string}[])
); );
}; };
private async filerValueChanged<T>(key: string, value: T): Promise<void> { private filterValueChanged<T>(key: keyof FilterValues, value: T): void {
const route = this.router.createUrlTree([this.route], { this.filterStore.updateShowFilter({[key]: value} as Partial<FilterValues>);
queryParams: {[key]: value || null},
queryParamsHandling: 'merge',
});
await this.router.navigateByUrl(route);
} }
private sameOwners(left: {key: string; value: string}[], right: {key: string; value: string}[]): boolean { private sameOwners(left: {key: string; value: string}[], right: {key: string; value: string}[]): boolean {

View File

@@ -1,9 +1,14 @@
@if (show) { @if (show) {
<div class="list-item"> <div class="list-item">
<div>{{ show.date.toDate() | date: "dd.MM.yyyy" }}</div> <div class="date">{{ show.date.toDate() | date: "dd.MM.yyyy" }}</div>
<div> <div class="user">
<app-user-name [userId]="show.owner"></app-user-name> <app-user-name [userId]="show.owner"></app-user-name>
</div> </div>
<div>{{ show.showType | showType }}</div> <div class="show-type">{{ show.showType | showType }}</div>
<div class="badge">
@if (showStatusBadge) {
<app-badge [type]="showStatusBadgeType">{{ showStatusBadge }}</app-badge>
}
</div>
</div> </div>
} }

View File

@@ -1,7 +1,16 @@
.list-item { .list-item {
padding: 5px 20px; padding: 5px 20px;
display: grid; display: grid;
grid-template-columns: 100px 150px auto; grid-template-columns: 100px 150px auto 160px;
grid-template-areas: "date user show-type badge";
@media screen and (max-width: 860px) {
grid-template-columns: 1fr 1fr 1fr;
grid-template-rows: auto auto;
grid-template-areas: "date user badge" ". show-type badge";
row-gap: 3px;
}
min-height: 21px; min-height: 21px;
& > div { & > div {
@@ -16,6 +25,23 @@
background: var(--hover-background); background: var(--hover-background);
color: var(--text); color: var(--text);
} }
.date {
grid-area: date;
}
.user {
grid-area: user;
}
.show-type {
grid-area: show-type;
}
.badge {
grid-area: badge;
justify-content: end;
}
} }
.number { .number {

View File

@@ -1,24 +1,45 @@
import {ComponentFixture, TestBed, waitForAsync} from '@angular/core/testing'; import {ComponentFixture, TestBed} from '@angular/core/testing';
import {BehaviorSubject, of} from 'rxjs';
import {ListItemComponent} from './list-item.component'; import {ListItemComponent} from './list-item.component';
import {UserService} from '../../../../services/user/user.service';
describe('ListItemComponent', () => { describe('ListItemComponent', () => {
let component: ListItemComponent; let component: ListItemComponent;
let fixture: ComponentFixture<ListItemComponent>; let fixture: ComponentFixture<ListItemComponent>;
beforeEach(waitForAsync(() => { beforeEach(async () => {
void TestBed.configureTestingModule({ await TestBed.configureTestingModule({
imports: [ListItemComponent], imports: [ListItemComponent],
providers: [
{
provide: UserService,
useValue: {
user$: new BehaviorSubject<unknown>({id: 'user-1'}).asObservable(),
userId$: new BehaviorSubject<string | null>('user-1').asObservable(),
loggedIn$: () => of(true),
getUserbyId$: () => of({name: 'Benjamin'}),
},
},
],
}).compileComponents(); }).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(ListItemComponent); fixture = TestBed.createComponent(ListItemComponent);
component = fixture.componentInstance; component = fixture.componentInstance;
fixture.detectChanges();
}); });
it('should create', () => { it('should create', () => {
void expect(component).toBeTruthy(); void expect(component).toBeTruthy();
}); });
it('should render a status badge when provided', () => {
component.show = {date: {toDate: () => new Date('2026-03-15')} as never, owner: 'user-1', showType: 'misc-private'} as never;
component.showStatusBadge = 'nicht gemeldet';
component.showStatusBadgeType = 'error';
fixture.detectChanges();
const badge = fixture.nativeElement.querySelector('app-badge .badge');
expect(badge?.textContent?.trim()).toBe('nicht gemeldet');
expect(badge?.className).toContain('error');
});
}); });

View File

@@ -3,13 +3,16 @@ import {Show} from '../../services/show';
import {DatePipe} from '@angular/common'; import {DatePipe} from '@angular/common';
import {UserNameComponent} from '../../../../services/user/user-name/user-name.component'; import {UserNameComponent} from '../../../../services/user/user-name/user-name.component';
import {ShowTypePipe} from '../../../../widget-modules/pipes/show-type-translater/show-type.pipe'; import {ShowTypePipe} from '../../../../widget-modules/pipes/show-type-translater/show-type.pipe';
import {BadgeComponent, BadgeType} from '../../../../widget-modules/components/badge/badge.component';
@Component({ @Component({
selector: 'app-list-item', selector: 'app-list-item',
templateUrl: './list-item.component.html', templateUrl: './list-item.component.html',
styleUrls: ['./list-item.component.less'], styleUrls: ['./list-item.component.less'],
imports: [UserNameComponent, DatePipe, ShowTypePipe], imports: [UserNameComponent, DatePipe, ShowTypePipe, BadgeComponent],
}) })
export class ListItemComponent { export class ListItemComponent {
@Input() public show: Show | null = null; @Input() public show: Show | null = null;
@Input() public showStatusBadge: string | null = null;
@Input() public showStatusBadgeType: BadgeType = 'none';
} }

View File

@@ -1,42 +1,45 @@
<div> @if (showSidebar$ | async) {
<!-- <app-list-header *appRole="['leader']"></app-list-header>--> <app-page-frame title="Veranstaltungen">
<app-list-header *appRole="['leader']"> <div class="sidebar-content" sidebar>
@if (shows$ | async; as shows) { <app-filter [shows]="(publicShows$ | async) ?? []"></app-filter>
<app-filter [shows]="publicShows$ | async"></app-filter> </div>
} <div content>
</app-list-header> @if (privateShows$ | async; as privateShows) {
<app-card [padding]="false" heading="Meine Veranstaltungen">
<ng-container *appRole="['leader']"> @for (show of privateShows; track trackBy($index, show)) {
@if (privateShows$ | async; as shows) {
@if (shows.length > 0) {
<app-card
[padding]="false"
heading="Meine Veranstaltungen"
>
@for (show of shows | sortBy: 'desc':'date'; track show) {
<app-list-item <app-list-item
[routerLink]="show.id" [routerLink]="show.id"
[showStatusBadgeType]="show.archived ? 'warn' : show.published ? 'error' : 'none'"
[showStatusBadge]="show.archived ? 'archiviert' : show.published ? 'nicht gemeldet' : 'unveröffentlicht'"
[show]="show" [show]="show"
></app-list-item> ></app-list-item>
} }
<div *appRole="['leader']" class="list-action">
<app-button [fullWidth]="true" [icon]="faNewShow" routerLink="new">Neue Veranstaltung anlegen</app-button>
</div>
</app-card>
}
@if (publicShows$ | async; as shows) {
@if (shows.length > 0) {
<app-card [padding]="false" heading="Veröffentlichte Veranstaltungen">
@for (show of shows; track trackBy($index, show)) {
<app-list-item [routerLink]="show.id" [show]="show"></app-list-item>
}
</app-card>
}
}
</div>
</app-page-frame>
} @else {
<div>
@if (publicShows$ | async; as shows) {
@if (shows.length > 0) {
<app-card [padding]="false" heading="Veröffentlichte Veranstaltungen">
@for (show of shows; track trackBy($index, show)) {
<app-list-item [routerLink]="show.id" [show]="show"></app-list-item>
}
</app-card> </app-card>
} }
} }
</ng-container> </div>
}
@if (publicShows$ | async; as shows) {
@if (shows.length > 0) {
<app-card
[padding]="false"
heading="Veröffentlichte Veranstaltungen"
>
@for (show of shows | sortBy: 'desc':'date'; track trackBy($index, show)) {
<app-list-item
[routerLink]="show.id"
[show]="show"
></app-list-item>
}
</app-card>
}
}
</div>

View File

@@ -0,0 +1,7 @@
.sidebar-content {
padding: 20px;
}
.list-action {
margin: 10px 20px;
}

View File

@@ -1,24 +1,106 @@
import {ComponentFixture, TestBed, waitForAsync} from '@angular/core/testing'; import {ComponentFixture, TestBed} from '@angular/core/testing';
import {BehaviorSubject, firstValueFrom, of} from 'rxjs';
import {skip, take} from 'rxjs/operators';
import {ListComponent} from './list.component'; import {ListComponent} from './list.component';
import {ShowService} from '../services/show.service';
import {UserService} from '../../../services/user/user.service';
import {FilterStoreService} from '../../../services/filter-store.service';
describe('ListComponent', () => { describe('ListComponent', () => {
let component: ListComponent; let component: ListComponent;
let fixture: ComponentFixture<ListComponent>; let fixture: ComponentFixture<ListComponent>;
let shows$: BehaviorSubject<unknown[]>;
let user$: BehaviorSubject<unknown>;
const createShow = (overrides: Record<string, unknown>) => ({
archived: false,
date: {toDate: () => new Date('2026-03-01')},
...overrides,
});
beforeEach(waitForAsync(() => { beforeEach(async () => {
void TestBed.configureTestingModule({ shows$ = new BehaviorSubject<unknown[]>([]);
user$ = new BehaviorSubject<unknown>({id: 'user-1'});
await TestBed.configureTestingModule({
imports: [ListComponent], imports: [ListComponent],
providers: [
{
provide: ShowService,
useValue: {
list$: () => shows$.asObservable(),
listPublicSince$: () => of([]),
},
},
{
provide: UserService,
useValue: {
user$: user$.asObservable(),
loggedIn$: () => of(true),
getUserbyId$: () => of({name: 'Benjamin'}),
},
},
FilterStoreService,
],
}).compileComponents(); }).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(ListComponent); fixture = TestBed.createComponent(ListComponent);
component = fixture.componentInstance; component = fixture.componentInstance;
fixture.detectChanges();
}); });
it('should create', () => { it('should create', () => {
void expect(component).toBeTruthy(); void expect(component).toBeTruthy();
}); });
it('should list own drafts and pending published shows in my shows', async () => {
shows$.next([
createShow({id: 'draft-own', owner: 'user-1', published: false, reportedType: null}),
createShow({id: 'pending-own', owner: 'user-1', published: true, reportedType: 'pending', date: {toDate: () => new Date('2026-03-02')}}),
createShow({id: 'reported-own', owner: 'user-1', published: true, reportedType: 'reported', date: {toDate: () => new Date('2026-03-03')}}),
createShow({id: 'draft-other', owner: 'user-2', published: false, reportedType: null, date: {toDate: () => new Date('2026-03-04')}}),
] as never);
const shows = await firstValueFrom(component.privateShows$);
expect(shows.map(show => show.id)).toEqual(['pending-own', 'draft-own']);
});
it('should ignore show filters for my shows', async () => {
const filterStore = TestBed.inject(FilterStoreService);
filterStore.updateShowFilter({time: 0, showType: 'service-worship'});
shows$.next([
createShow({id: 'older-draft', owner: 'user-1', published: false, reportedType: null, showType: 'misc-private', date: {toDate: () => new Date('2025-01-01')}}),
createShow({id: 'pending-own', owner: 'user-1', published: true, reportedType: 'pending', showType: 'home-group', date: {toDate: () => new Date('2026-03-05')}}),
] as never);
const shows = await firstValueFrom(component.privateShows$);
expect(shows.map(show => show.id)).toEqual(['pending-own', 'older-draft']);
});
it('should hide archived own shows until archived filter is enabled', async () => {
const filterStore = TestBed.inject(FilterStoreService);
shows$.next([
createShow({id: 'draft-own', owner: 'user-1', published: false, reportedType: null, date: {toDate: () => new Date('2026-03-02')}}),
createShow({id: 'archived-own', owner: 'user-1', published: true, archived: true, reportedType: 'reported', date: {toDate: () => new Date('2026-03-03')}}),
] as never);
const initialShows = await firstValueFrom(component.privateShows$.pipe(take(1)));
expect(initialShows.map(show => show.id)).toEqual(['draft-own']);
const updatedShowsPromise = firstValueFrom(component.privateShows$.pipe(skip(1), take(1)));
filterStore.updateShowFilter({archived: true});
const updatedShows = await updatedShowsPromise;
expect(updatedShows.map(show => show.id)).toEqual(['archived-own', 'draft-own']);
});
it('should sort public shows by date descending', async () => {
const filterStore = TestBed.inject(FilterStoreService);
filterStore.updateShowFilter({time: 99999});
shows$.next([
createShow({id: 'old-public', owner: 'user-2', published: true, archived: false, date: {toDate: () => new Date('2026-01-01')}}),
createShow({id: 'new-public', owner: 'user-3', published: true, archived: false, date: {toDate: () => new Date('2026-03-10')}}),
createShow({id: 'mid-public', owner: 'user-4', published: true, archived: false, date: {toDate: () => new Date('2026-02-05')}}),
] as never);
const shows = await firstValueFrom(component.publicShows$.pipe(take(1)));
expect(shows.map(show => show.id)).toEqual(['new-public', 'mid-public', 'old-public']);
});
}); });

View File

@@ -4,65 +4,88 @@ import {Show} from '../services/show';
import {fade} from '../../../animations'; import {fade} from '../../../animations';
import {ShowService} from '../services/show.service'; import {ShowService} from '../services/show.service';
import {FilterValues} from './filter/filter-values'; import {FilterValues} from './filter/filter-values';
import {ActivatedRoute, RouterLink} from '@angular/router'; import {RouterLink} from '@angular/router';
import {map, switchMap} from 'rxjs/operators'; import {map, switchMap} from 'rxjs/operators';
import {RoleDirective} from '../../../services/user/role.directive'; import {FilterStoreService} from '../../../services/filter-store.service';
import {ListHeaderComponent} from '../../../widget-modules/components/list-header/list-header.component';
import {AsyncPipe} from '@angular/common'; import {AsyncPipe} from '@angular/common';
import {FilterComponent} from './filter/filter.component'; import {FilterComponent} from './filter/filter.component';
import {CardComponent} from '../../../widget-modules/components/card/card.component'; import {CardComponent} from '../../../widget-modules/components/card/card.component';
import {ListItemComponent} from './list-item/list-item.component'; import {ListItemComponent} from './list-item/list-item.component';
import {SortByPipe} from '../../../widget-modules/pipes/sort-by/sort-by.pipe'; import {UserService} from '../../../services/user/user.service';
import {PageFrameComponent} from '../../../widget-modules/components/sidebar/page-frame.component';
import {ButtonComponent} from '../../../widget-modules/components/button/button.component';
import {faPlus} from '@fortawesome/free-solid-svg-icons';
import {RoleDirective} from '../../../services/user/role.directive';
@Component({ @Component({
selector: 'app-list', selector: 'app-list',
templateUrl: './list.component.html', templateUrl: './list.component.html',
styleUrls: ['./list.component.less'], styleUrls: ['./list.component.less'],
animations: [fade], animations: [fade],
imports: [RoleDirective, ListHeaderComponent, FilterComponent, CardComponent, ListItemComponent, RouterLink, AsyncPipe, SortByPipe], imports: [FilterComponent, CardComponent, ListItemComponent, RouterLink, AsyncPipe, PageFrameComponent, ButtonComponent, RoleDirective],
}) })
export class ListComponent { export class ListComponent {
public faNewShow = faPlus;
private filterStore = inject(FilterStoreService);
public filter$ = this.filterStore.showFilter$;
public lastMonths$ = this.filter$.pipe(map((filterValues: FilterValues) => filterValues.time || 1));
public owner$ = this.filter$.pipe(map((filterValues: FilterValues) => filterValues.owner));
public showType$ = this.filter$.pipe(map((filterValues: FilterValues) => filterValues.showType));
public archived$ = this.filter$.pipe(map((filterValues: FilterValues) => !!filterValues.archived));
private showService = inject(ShowService); private showService = inject(ShowService);
private activatedRoute = inject(ActivatedRoute);
public lastMonths$ = this.activatedRoute.queryParams.pipe(
map(params => {
const filterValues = params as FilterValues;
if (!filterValues?.time) return 1;
return +filterValues.time;
})
);
public owner$ = this.activatedRoute.queryParams.pipe(
map(params => {
const filterValues = params as FilterValues;
return filterValues?.owner;
})
);
public showType$ = this.activatedRoute.queryParams.pipe(
map(params => {
const filterValues = params as FilterValues;
return filterValues?.showType;
})
);
public shows$ = this.showService.list$(); public shows$ = this.showService.list$();
public privateShows$ = this.showService.list$().pipe(map(show => show.filter(_ => !_.published)));
public queriedPublicShows$ = this.lastMonths$.pipe(switchMap(lastMonths => this.showService.listPublicSince$(lastMonths)));
public fallbackPublicShows$ = combineLatest([this.shows$, this.lastMonths$]).pipe( public fallbackPublicShows$ = combineLatest([this.shows$, this.lastMonths$]).pipe(
map(([shows, lastMonths]) => { map(([shows, lastMonths]) => {
const startDate = new Date(); return shows.filter(show => show.published && !show.archived).filter(show => this.matchesTimeFilter(show, lastMonths));
startDate.setHours(0, 0, 0, 0); }),
startDate.setDate(startDate.getDate() - lastMonths * 30);
return shows.filter(show => show.published && !show.archived && show.date.toDate() >= startDate);
})
); );
public ownShows$ = this.showService.list$(false, true);
public queriedPublicShows$ = this.lastMonths$.pipe(switchMap(lastMonths => this.showService.listPublicSince$(lastMonths)));
public publicShows$ = combineLatest([this.queriedPublicShows$, this.fallbackPublicShows$, this.owner$, this.showType$]).pipe( public publicShows$ = combineLatest([this.queriedPublicShows$, this.fallbackPublicShows$, this.owner$, this.showType$]).pipe(
map(([queriedShows, fallbackShows, owner, showType]) => { map(([queriedShows, fallbackShows, owner, showType]) => {
const shows = queriedShows.length > 0 || fallbackShows.length === 0 ? queriedShows : fallbackShows; const shows = queriedShows.length > 0 || fallbackShows.length === 0 ? queriedShows : fallbackShows;
return shows.filter(show => !owner || show.owner === owner).filter(show => !showType || show.showType === showType); return this.sortShowsByDateDesc(shows.filter(show => !owner || show.owner === owner).filter(show => !showType || show.showType === showType));
}) }),
); );
private userService = inject(UserService);
public privateShows$ = combineLatest([this.ownShows$, this.userService.user$, this.archived$]).pipe(
map(([shows, user, showArchived]) =>
shows.filter(show => {
if (show.owner !== user?.id) {
return false;
}
if (show.archived) {
return showArchived;
}
return !show.published || show.reportedType === 'pending';
}),
),
map(shows => this.sortShowsByDateDesc(shows)),
);
public showSidebar$ = this.userService.user$.pipe(map(user => this.hasSidebarAccess(user?.role)));
public trackBy = (index: number, show: unknown) => (show as Show).id; public trackBy = (index: number, show: unknown) => (show as Show).id;
private matchesTimeFilter(show: Show, lastMonths: number): boolean {
const startDate = new Date();
startDate.setHours(0, 0, 0, 0);
startDate.setDate(startDate.getDate() - lastMonths * 30);
return show.date.toDate() >= startDate;
}
private sortShowsByDateDesc(shows: Show[]): Show[] {
return [...shows].sort((left, right) => right.date.toDate().getTime() - left.date.toDate().getTime());
}
private hasSidebarAccess(role: string | null | undefined): boolean {
if (!role) {
return false;
}
const roles = role.split(';').map(item => item.trim());
return roles.includes('admin') || roles.includes('leader');
}
} }

View File

@@ -1,37 +1,33 @@
<div> <app-page-frame title="Veranstaltungen" [withMenu]="false">
<app-card closeLink="/shows" heading="Neue Veranstaltung"> <div content>
<div [formGroup]="form" class="split"> <app-card closeLink="/shows" heading="Neue Veranstaltung">
<mat-form-field appearance="outline"> <div [formGroup]="form" class="split">
<mat-label>Art der Veranstaltung</mat-label> <mat-form-field appearance="outline">
<mat-select formControlName="showType"> <mat-label>Art der Veranstaltung</mat-label>
<mat-optgroup label="öffentlich"> <mat-select formControlName="showType">
@for (key of showTypePublic; track key) { <mat-optgroup label="öffentlich">
<mat-option [value]="key">{{ @for (key of showTypePublic; track key) {
key | showType <mat-option [value]="key">{{ key | showType }}</mat-option>
}} }
</mat-option> </mat-optgroup>
} <mat-optgroup label="privat">
</mat-optgroup> @for (key of showTypePrivate; track key) {
<mat-optgroup label="privat"> <mat-option [value]="key">{{ key | showType }}</mat-option>
@for (key of showTypePrivate; track key) { }
<mat-option [value]="key">{{ </mat-optgroup>
key | showType </mat-select>
}} </mat-form-field>
</mat-option> <mat-form-field appearance="outline">
} <mat-label>Datum</mat-label>
</mat-optgroup> <input [matDatepicker]="picker" formControlName="date" matInput />
</mat-select> <mat-datepicker-toggle [for]="picker" matSuffix></mat-datepicker-toggle>
</mat-form-field> <mat-datepicker #picker touchUi></mat-datepicker>
<mat-form-field appearance="outline"> </mat-form-field>
<mat-label>Datum</mat-label> </div>
<input [matDatepicker]="picker" formControlName="date" matInput />
<mat-datepicker-toggle [for]="picker" matSuffix></mat-datepicker-toggle>
<mat-datepicker #picker touchUi></mat-datepicker>
</mat-form-field>
</div>
<app-button-row> <app-button-row>
<app-button (click)="onSave()" [icon]="faSave">Anlegen</app-button> <app-button (click)="onSave()" [icon]="faSave">Anlegen</app-button>
</app-button-row> </app-button-row>
</app-card> </app-card>
</div> </div>
</app-page-frame>

View File

@@ -1,4 +1,4 @@
import {ComponentFixture, TestBed, waitForAsync} from '@angular/core/testing'; import {ComponentFixture, TestBed} from '@angular/core/testing';
import {NewComponent} from './new.component'; import {NewComponent} from './new.component';
@@ -6,11 +6,11 @@ describe('NewComponent', () => {
let component: NewComponent; let component: NewComponent;
let fixture: ComponentFixture<NewComponent>; let fixture: ComponentFixture<NewComponent>;
beforeEach(waitForAsync(() => { beforeEach(async () => {
void TestBed.configureTestingModule({ await TestBed.configureTestingModule({
imports: [NewComponent], imports: [NewComponent],
}).compileComponents(); }).compileComponents();
})); });
beforeEach(() => { beforeEach(() => {
fixture = TestBed.createComponent(NewComponent); fixture = TestBed.createComponent(NewComponent);

View File

@@ -1,9 +1,9 @@
import {Component, OnInit, inject} from '@angular/core'; import {Component, inject, OnInit} from '@angular/core';
import {ShowDataService} from '../services/show-data.service'; import {ShowDataService} from '../services/show-data.service';
import {Observable} from 'rxjs'; import {Observable} from 'rxjs';
import {Show} from '../services/show'; import {Show} from '../services/show';
import {ShowService} from '../services/show.service'; import {ShowService} from '../services/show.service';
import {ReactiveFormsModule, UntypedFormControl, UntypedFormGroup, Validators} from '@angular/forms'; import {FormControl, FormGroup, ReactiveFormsModule, Validators} from '@angular/forms';
import {Router} from '@angular/router'; import {Router} from '@angular/router';
import {faSave} from '@fortawesome/free-solid-svg-icons'; import {faSave} from '@fortawesome/free-solid-svg-icons';
import {CardComponent} from '../../../widget-modules/components/card/card.component'; import {CardComponent} from '../../../widget-modules/components/card/card.component';
@@ -16,6 +16,7 @@ import {MatDatepicker, MatDatepickerInput, MatDatepickerToggle} from '@angular/m
import {ButtonRowComponent} from '../../../widget-modules/components/button-row/button-row.component'; import {ButtonRowComponent} from '../../../widget-modules/components/button-row/button-row.component';
import {ButtonComponent} from '../../../widget-modules/components/button/button.component'; import {ButtonComponent} from '../../../widget-modules/components/button/button.component';
import {ShowTypePipe} from '../../../widget-modules/pipes/show-type-translater/show-type.pipe'; import {ShowTypePipe} from '../../../widget-modules/pipes/show-type-translater/show-type.pipe';
import {PageFrameComponent} from '../../../widget-modules/components/sidebar/page-frame.component';
@Component({ @Component({
selector: 'app-new', selector: 'app-new',
@@ -37,6 +38,7 @@ import {ShowTypePipe} from '../../../widget-modules/pipes/show-type-translater/s
ButtonRowComponent, ButtonRowComponent,
ButtonComponent, ButtonComponent,
ShowTypePipe, ShowTypePipe,
PageFrameComponent,
], ],
}) })
export class NewComponent implements OnInit { export class NewComponent implements OnInit {
@@ -46,9 +48,9 @@ export class NewComponent implements OnInit {
public shows$: Observable<Show[]>; public shows$: Observable<Show[]>;
public showTypePublic = ShowService.SHOW_TYPE_PUBLIC; public showTypePublic = ShowService.SHOW_TYPE_PUBLIC;
public showTypePrivate = ShowService.SHOW_TYPE_PRIVATE; public showTypePrivate = ShowService.SHOW_TYPE_PRIVATE;
public form: UntypedFormGroup = new UntypedFormGroup({ public form = new FormGroup({
date: new UntypedFormControl(null, Validators.required), date: new FormControl<Date | null>(null, Validators.required),
showType: new UntypedFormControl(null, Validators.required), showType: new FormControl<string | null>(null, Validators.required),
}); });
public faSave = faSave; public faSave = faSave;
@@ -68,7 +70,11 @@ export class NewComponent implements OnInit {
return; return;
} }
const id = await this.showService.new$(this.form.value as Partial<Show>); const {date, showType} = this.form.getRawValue();
const id = await this.showService.new$({
date,
showType,
} as unknown as Partial<Show>);
await this.router.navigateByUrl(`/shows/${id ?? ''}`); await this.router.navigateByUrl(`/shows/${id ?? ''}`);
} }
} }

View File

@@ -1,16 +1,77 @@
import {TestBed} from '@angular/core/testing'; import {TestBed} from '@angular/core/testing';
import {DocxService} from './docx.service'; import {DocxService} from './docx.service';
describe('DocxService', () => { describe('DocxService', () => {
let service: DocxService; let service: DocxService;
type PreparedData = {
show: {
showType: string;
date: {toDate: () => Date};
};
songs: unknown[];
user: {name: string};
config: {ccliLicenseId: string};
};
type DocxModuleLike = {
Packer: {toBlob: (document: unknown) => Promise<Blob>};
};
type DocxServiceInternals = DocxService & {
prepareData: (showId: string) => Promise<PreparedData | null>;
renderTitle: (docx: unknown, title: string) => unknown[];
renderSongs: (docx: unknown, songs: unknown[], options: unknown, config: unknown) => unknown[];
prepareNewDocument: (docx: unknown, data: unknown, options?: unknown, sections?: unknown) => unknown;
saveAs: (blob: Blob, name: string) => void;
loadDocx: () => Promise<DocxModuleLike>;
};
beforeEach(() => { beforeEach(async () => {
void TestBed.configureTestingModule({}); await TestBed.configureTestingModule({});
service = TestBed.inject(DocxService); service = TestBed.inject(DocxService);
}); });
it('should be created', () => { it('should be created', () => {
void expect(service).toBeTruthy(); void expect(service).toBeTruthy();
}); });
it('should not try to save a document when the required data cannot be prepared', async () => {
const serviceInternals = service as DocxServiceInternals;
const prepareDataSpy = spyOn(serviceInternals, 'prepareData').and.resolveTo(null);
const saveAsSpy = spyOn(serviceInternals, 'saveAs');
await service.create('show-1');
expect(prepareDataSpy).toHaveBeenCalledWith('show-1');
expect(saveAsSpy).not.toHaveBeenCalled();
});
it('should build and save a docx file when all data is available', async () => {
const blob = new Blob(['docx']);
const docxModule: DocxModuleLike = {
Packer: {
toBlob: jasmine.createSpy('toBlob').and.resolveTo(blob),
},
};
const serviceInternals = service as DocxServiceInternals;
const prepareDataSpy = spyOn(serviceInternals, 'prepareData').and.resolveTo({
show: {
showType: 'service-worship',
date: {toDate: () => new Date('2026-03-10T00:00:00Z')},
},
songs: [],
user: {name: 'Benjamin'},
config: {ccliLicenseId: '12345'},
});
spyOn(serviceInternals, 'loadDocx').and.resolveTo(docxModule);
spyOn(serviceInternals, 'renderTitle').and.returnValue([]);
spyOn(serviceInternals, 'renderSongs').and.returnValue([]);
const prepareNewDocumentSpy = spyOn(serviceInternals, 'prepareNewDocument').and.returnValue({doc: true});
const saveAsSpy = spyOn(serviceInternals, 'saveAs');
await service.create('show-1', {copyright: true});
expect(prepareDataSpy).toHaveBeenCalledWith('show-1');
expect(prepareNewDocumentSpy).toHaveBeenCalled();
expect(docxModule.Packer.toBlob).toHaveBeenCalledWith({doc: true} as never);
expect(saveAsSpy).toHaveBeenCalledWith(blob, jasmine.stringMatching(/\.docx$/));
});
}); });

View File

@@ -1,5 +1,4 @@
import {Injectable, inject} from '@angular/core'; import {Injectable, inject} from '@angular/core';
import {Document, HeadingLevel, ISectionOptions, Packer, Paragraph} from 'docx';
import {ShowService} from './show.service'; import {ShowService} from './show.service';
import {ShowTypePipe} from '../../../widget-modules/pipes/show-type-translater/show-type.pipe'; import {ShowTypePipe} from '../../../widget-modules/pipes/show-type-translater/show-type.pipe';
import {ShowSongService} from './show-song.service'; import {ShowSongService} from './show-song.service';
@@ -17,6 +16,11 @@ import {LineType} from '../../songs/services/line-type';
import {Line} from '../../songs/services/line'; import {Line} from '../../songs/services/line';
import {firstValueFrom} from 'rxjs'; import {firstValueFrom} from 'rxjs';
type DocxModule = typeof import('docx');
type DocxDocument = import('docx').Document;
type DocxParagraph = import('docx').Paragraph;
type DocxSectionOptions = import('docx').ISectionOptions;
export interface DownloadOptions { export interface DownloadOptions {
copyright?: boolean; copyright?: boolean;
chordMode?: ChordMode; chordMode?: ChordMode;
@@ -35,13 +39,14 @@ export class DocxService {
public async create(showId: string, options: DownloadOptions = {}): Promise<void> { public async create(showId: string, options: DownloadOptions = {}): Promise<void> {
const data = await this.prepareData(showId); const data = await this.prepareData(showId);
if (!data) return; if (!data) return;
const docx = await this.loadDocx();
const {show, songs, user, config} = data; const {show, songs, user, config} = data;
const type = new ShowTypePipe().transform(show.showType); const type = new ShowTypePipe().transform(show.showType);
const title = `${type} ${show.date.toDate().toLocaleDateString()}`; const title = `${type} ${show.date.toDate().toLocaleDateString()}`;
const paragraphs = [...this.renderTitle(title), ...this.renderSongs(songs, options, config)]; const paragraphs = [...this.renderTitle(docx, title), ...this.renderSongs(docx, songs, options, config)];
const sections: ISectionOptions[] = [ const sections: DocxSectionOptions[] = [
{ {
properties: { properties: {
page: { page: {
@@ -51,16 +56,16 @@ export class DocxService {
children: paragraphs, children: paragraphs,
}, },
]; ];
const document = this.prepareNewDocument(type, user.name, options, sections); const document = this.prepareNewDocument(docx, type, user.name, options, sections);
const blob = await Packer.toBlob(document); const blob = await docx.Packer.toBlob(document);
// saveAs from FileSaver will download the file // saveAs from FileSaver will download the file
this.saveAs(blob, `${title}.docx`); this.saveAs(blob, `${title}.docx`);
} }
private prepareNewDocument(type: string, name: string, options: DownloadOptions, sections: ISectionOptions[]): Document { private prepareNewDocument(docx: DocxModule, type: string, name: string, options: DownloadOptions, sections: DocxSectionOptions[]): DocxDocument {
return new Document({ return new docx.Document({
creator: name, creator: name,
title: type, title: type,
description: '... mit Beschreibung', description: '... mit Beschreibung',
@@ -91,32 +96,33 @@ export class DocxService {
} }
private renderSongs( private renderSongs(
docx: DocxModule,
songs: { songs: {
showSong: ShowSong; showSong: ShowSong;
sections: Section[]; sections: Section[];
}[], }[],
options: DownloadOptions, options: DownloadOptions,
config: Config config: Config
): Paragraph[] { ): DocxParagraph[] {
return songs.reduce((p: Paragraph[], song) => [...p, ...this.renderSong(song.showSong, song.showSong, song.sections, options, config)], []); return songs.reduce((p: DocxParagraph[], song) => [...p, ...this.renderSong(docx, song.showSong, song.showSong, song.sections, options, config)], []);
} }
private renderSong(showSong: ShowSong, song: Song, sections: Section[], options: DownloadOptions, config: Config): Paragraph[] { private renderSong(docx: DocxModule, showSong: ShowSong, song: Song, sections: Section[], options: DownloadOptions, config: Config): DocxParagraph[] {
const songTitle = this.renderSongTitle(song); const songTitle = this.renderSongTitle(docx, song);
const copyright = this.renderCopyright(song, options, config); const copyright = this.renderCopyright(docx, song, options, config);
const songText = this.renderSongText(sections, options?.chordMode ?? showSong.chordMode); const songText = this.renderSongText(docx, sections, options?.chordMode ?? showSong.chordMode);
return copyright ? [songTitle, copyright, ...songText] : [songTitle, ...songText]; return copyright ? [songTitle, copyright, ...songText] : [songTitle, ...songText];
} }
private renderSongText(sections: Section[], chordMode: ChordMode): Paragraph[] { private renderSongText(docx: DocxModule, sections: Section[], chordMode: ChordMode): DocxParagraph[] {
return sections.reduce((p: Paragraph[], section) => [...p, ...this.renderSection(section, chordMode)], []); return sections.reduce((p: DocxParagraph[], section) => [...p, ...this.renderSection(docx, section, chordMode)], []);
} }
private renderSongTitle(song: Song): Paragraph { private renderSongTitle(docx: DocxModule, song: Song): DocxParagraph {
return new Paragraph({ return new docx.Paragraph({
text: song.title, text: song.title,
heading: HeadingLevel.HEADING_2, heading: docx.HeadingLevel.HEADING_2,
thematicBreak: true, thematicBreak: true,
spacing: { spacing: {
before: 200, before: 200,
@@ -124,7 +130,7 @@ export class DocxService {
}); });
} }
private renderCopyright(song: Song, options: DownloadOptions, config: Config): Paragraph | null { private renderCopyright(docx: DocxModule, song: Song, options: DownloadOptions, config: Config): DocxParagraph | null {
if (!options?.copyright) { if (!options?.copyright) {
return null; return null;
} }
@@ -135,13 +141,13 @@ export class DocxService {
const origin = song.origin ? song.origin + ', ' : ''; const origin = song.origin ? song.origin + ', ' : '';
const licence = song.legalOwner === 'CCLI' ? 'CCLI-Liednummer: ' + song.legalOwnerId + ', CCLI-Lizenz: ' + config.ccliLicenseId : 'CCLI-Liednummer: ' + song.legalOwnerId; const licence = song.legalOwner === 'CCLI' ? 'CCLI-Liednummer: ' + song.legalOwnerId + ', CCLI-Lizenz: ' + config.ccliLicenseId : 'CCLI-Liednummer: ' + song.legalOwnerId;
return new Paragraph({ return new docx.Paragraph({
text: artist + label + termsOfUse + origin + licence, text: artist + label + termsOfUse + origin + licence,
style: 'licence', style: 'licence',
}); });
} }
private renderSection(section: Section, chordMode: ChordMode): Paragraph[] { private renderSection(docx: DocxModule, section: Section, chordMode: ChordMode): DocxParagraph[] {
return section.lines return section.lines
.filter(line => { .filter(line => {
if (line.type === LineType.text) { if (line.type === LineType.text) {
@@ -156,22 +162,22 @@ export class DocxService {
return section.number === 0; return section.number === 0;
} }
}) })
.map((line, i) => this.renderLine(line, i === 0)); .map((line, i) => this.renderLine(docx, line, i === 0));
} }
private renderLine(line: Line, isFirstLine: boolean): Paragraph { private renderLine(docx: DocxModule, line: Line, isFirstLine: boolean): DocxParagraph {
const spacing = isFirstLine ? {before: 200} : {}; const spacing = isFirstLine ? {before: 200} : {};
return new Paragraph({ return new docx.Paragraph({
text: line.text, text: line.text,
style: 'songtext', style: 'songtext',
spacing, spacing,
}); });
} }
private renderTitle(type: string): Paragraph[] { private renderTitle(docx: DocxModule, type: string): DocxParagraph[] {
const songTitle = new Paragraph({ const songTitle = new docx.Paragraph({
text: type, text: type,
heading: HeadingLevel.HEADING_1, heading: docx.HeadingLevel.HEADING_1,
thematicBreak: true, thematicBreak: true,
}); });
@@ -232,4 +238,8 @@ export class DocxService {
document.body.removeChild(a); document.body.removeChild(a);
}, 1000); }, 1000);
} }
private loadDocx(): Promise<DocxModule> {
return import('docx');
}
} }

View File

@@ -1,6 +1,6 @@
import {TestBed} from '@angular/core/testing'; import {TestBed} from '@angular/core/testing';
import {firstValueFrom, of, Subject} from 'rxjs'; import {firstValueFrom, of, Subject} from 'rxjs';
import {skip, take} from 'rxjs/operators'; import {take} from 'rxjs/operators';
import {DbService} from '../../../services/db.service'; import {DbService} from '../../../services/db.service';
import {ShowDataService} from './show-data.service'; import {ShowDataService} from './show-data.service';
@@ -13,7 +13,7 @@ describe('ShowDataService', () => {
let colSpy: jasmine.Spy; let colSpy: jasmine.Spy;
let dbServiceSpy: jasmine.SpyObj<DbService>; let dbServiceSpy: jasmine.SpyObj<DbService>;
beforeEach(() => { beforeEach(async () => {
shows$ = new Subject<Array<{id: string; date: {toMillis: () => number}; archived?: boolean}>>(); shows$ = new Subject<Array<{id: string; date: {toMillis: () => number}; archived?: boolean}>>();
docUpdateSpy = jasmine.createSpy('update').and.resolveTo(); docUpdateSpy = jasmine.createSpy('update').and.resolveTo();
docSpy = jasmine.createSpy('doc').and.returnValue({update: docUpdateSpy}); docSpy = jasmine.createSpy('doc').and.returnValue({update: docUpdateSpy});
@@ -25,7 +25,7 @@ describe('ShowDataService', () => {
dbServiceSpy.doc.and.callFake(docSpy); dbServiceSpy.doc.and.callFake(docSpy);
dbServiceSpy.col.and.callFake(colSpy); dbServiceSpy.col.and.callFake(colSpy);
void TestBed.configureTestingModule({ await TestBed.configureTestingModule({
providers: [{provide: DbService, useValue: dbServiceSpy}], providers: [{provide: DbService, useValue: dbServiceSpy}],
}); });
@@ -76,11 +76,7 @@ describe('ShowDataService', () => {
}); });
it('should request only published recent shows and filter archived entries', async () => { it('should request only published recent shows and filter archived entries', async () => {
const publicShows$ = of([ const publicShows$ = of([{id: 'show-1', archived: false}, {id: 'show-2', archived: true}, {id: 'show-3'}]);
{id: 'show-1', archived: false},
{id: 'show-2', archived: true},
{id: 'show-3'},
]);
dbServiceSpy.col$.and.returnValue(publicShows$ as never); dbServiceSpy.col$.and.returnValue(publicShows$ as never);
const result = await firstValueFrom(service.listPublicSince$(3)); const result = await firstValueFrom(service.listPublicSince$(3));

View File

@@ -24,12 +24,15 @@ export class ShowDataService {
public listRaw$ = () => this.dbService.col$<Show>(this.collection); public listRaw$ = () => this.dbService.col$<Show>(this.collection);
public listPublicSince$(lastMonths: number): Observable<Show[]> { public listPublicSince$(lastMonths: number): Observable<Show[]> {
const startDate = new Date(); const queryConstraints: QueryConstraint[] = [where('published', '==', true), orderBy('date', 'desc')];
startDate.setHours(0, 0, 0, 0);
startDate.setDate(startDate.getDate() - lastMonths * 30);
const startTimestamp = Timestamp.fromDate(startDate);
const queryConstraints: QueryConstraint[] = [where('published', '==', true), where('date', '>=', startTimestamp), orderBy('date', 'desc')]; if (lastMonths < 99999) {
const startDate = new Date();
startDate.setHours(0, 0, 0, 0);
startDate.setDate(startDate.getDate() - lastMonths * 30);
const startTimestamp = Timestamp.fromDate(startDate);
queryConstraints.splice(1, 0, where('date', '>=', startTimestamp));
}
return this.dbService.col$<Show>(this.collection, queryConstraints).pipe( return this.dbService.col$<Show>(this.collection, queryConstraints).pipe(
map(shows => shows.filter(show => !show.archived)), map(shows => shows.filter(show => !show.archived)),

View File

@@ -12,7 +12,7 @@ describe('ShowSongDataService', () => {
let colSpy: jasmine.Spy; let colSpy: jasmine.Spy;
let dbServiceSpy: jasmine.SpyObj<DbService>; let dbServiceSpy: jasmine.SpyObj<DbService>;
beforeEach(() => { beforeEach(async () => {
docUpdateSpy = jasmine.createSpy('update').and.resolveTo(); docUpdateSpy = jasmine.createSpy('update').and.resolveTo();
docDeleteSpy = jasmine.createSpy('delete').and.resolveTo(); docDeleteSpy = jasmine.createSpy('delete').and.resolveTo();
docSpy = jasmine.createSpy('doc').and.returnValue({ docSpy = jasmine.createSpy('doc').and.returnValue({
@@ -27,7 +27,7 @@ describe('ShowSongDataService', () => {
dbServiceSpy.doc.and.callFake(docSpy); dbServiceSpy.doc.and.callFake(docSpy);
dbServiceSpy.col.and.callFake(colSpy); dbServiceSpy.col.and.callFake(colSpy);
void TestBed.configureTestingModule({ await TestBed.configureTestingModule({
providers: [{provide: DbService, useValue: dbServiceSpy}], providers: [{provide: DbService, useValue: dbServiceSpy}],
}); });

View File

@@ -0,0 +1,60 @@
import {TestBed} from '@angular/core/testing';
import {of} from 'rxjs';
import {ShowDataService} from './show-data.service';
import {ShowSongDataService} from './show-song-data.service';
import {ShowSongIndexService} from './show-song-index.service';
import {UserSessionService} from '../../../services/user/user-session.service';
import {User} from '../../../services/user/user';
describe('ShowSongIndexService', () => {
let service: ShowSongIndexService;
let showDataServiceSpy: jasmine.SpyObj<ShowDataService>;
let showSongDataServiceSpy: jasmine.SpyObj<ShowSongDataService>;
let sessionSpy: jasmine.SpyObj<UserSessionService>;
beforeEach(async () => {
showDataServiceSpy = jasmine.createSpyObj<ShowDataService>('ShowDataService', ['listRaw$', 'update']);
showSongDataServiceSpy = jasmine.createSpyObj<ShowSongDataService>('ShowSongDataService', ['list$']);
sessionSpy = jasmine.createSpyObj<UserSessionService>('UserSessionService', ['update$'], {
user$: of({id: 'admin-1', name: 'Admin', role: 'admin', chordMode: 'onlyFirst', songUsage: {}} as User),
});
showDataServiceSpy.listRaw$.and.returnValue(of([{id: 'show-1'}, {id: 'show-2'}] as never) as unknown as ReturnType<ShowDataService['listRaw$']>);
showDataServiceSpy.update.and.resolveTo();
showSongDataServiceSpy.list$.and.callFake((showId: string) => {
if (showId === 'show-1') {
return of([{songId: 'song-1'}, {songId: 'song-2'}, {songId: 'song-1'}] as never) as never;
}
return of([{songId: 'song-3'}] as never) as never;
});
await TestBed.configureTestingModule({
providers: [
{provide: ShowDataService, useValue: showDataServiceSpy},
{provide: ShowSongDataService, useValue: showSongDataServiceSpy},
{provide: UserSessionService, useValue: sessionSpy},
],
});
service = TestBed.inject(ShowSongIndexService);
});
it('should rebuild the distinct songIds index for all shows', async () => {
await expectAsync(service.rebuildShowSongIds()).toBeResolvedTo({
showsProcessed: 2,
showSongsProcessed: 4,
});
expect(showDataServiceSpy.update).toHaveBeenCalledWith('show-1', {songIds: ['song-1', 'song-2']});
expect(showDataServiceSpy.update).toHaveBeenCalledWith('show-2', {songIds: ['song-3']});
});
it('should reject index rebuilds for non-admin users', async () => {
Object.defineProperty(sessionSpy, 'user$', {
value: of({id: 'user-1', name: 'User', role: 'leader', chordMode: 'onlyFirst', songUsage: {}} as User),
});
await expectAsync(service.rebuildShowSongIds()).toBeRejectedWithError('Admin role required to rebuild show song ids.');
});
});

View File

@@ -0,0 +1,65 @@
import {Injectable, inject} from '@angular/core';
import {firstValueFrom} from 'rxjs';
import {take} from 'rxjs/operators';
import {ShowDataService} from './show-data.service';
import {ShowSongDataService} from './show-song-data.service';
import {UserSessionService} from '../../../services/user/user-session.service';
export interface ShowSongIndexMigrationResult {
showsProcessed: number;
showSongsProcessed: number;
}
export interface MigrationProgress {
processed: number;
total: number;
showId: string;
showSongsProcessed: number;
}
@Injectable({
providedIn: 'root',
})
export class ShowSongIndexService {
private session = inject(UserSessionService);
private showDataService = inject(ShowDataService);
private showSongDataService = inject(ShowSongDataService);
public async rebuildShowSongIds(onProgress?: (progress: MigrationProgress) => void): Promise<ShowSongIndexMigrationResult> {
const currentUser = await firstValueFrom(this.session.user$.pipe(take(1)));
if (!currentUser || !this.hasAdminRole(currentUser.role)) {
throw new Error('Admin role required to rebuild show song ids.');
}
const shows = await firstValueFrom(this.showDataService.listRaw$());
let showSongsProcessed = 0;
let processed = 0;
for (const show of shows) {
const showSongs = await firstValueFrom(this.showSongDataService.list$(show.id));
const songIds = [...new Set(showSongs.map(showSong => showSong.songId).filter(Boolean))];
showSongsProcessed += showSongs.length;
await this.showDataService.update(show.id, {songIds});
processed += 1;
onProgress?.({
processed,
total: shows.length,
showId: show.id,
showSongsProcessed,
});
}
return {
showsProcessed: shows.length,
showSongsProcessed,
};
}
private hasAdminRole(role: string | null | undefined): boolean {
if (!role) {
return false;
}
return role.split(';').includes('admin');
}
}

View File

@@ -5,6 +5,10 @@ import {UserService} from '../../../services/user/user.service';
import {ShowService} from './show.service'; import {ShowService} from './show.service';
import {ShowSongDataService} from './show-song-data.service'; import {ShowSongDataService} from './show-song-data.service';
import {ShowSongService} from './show-song.service'; import {ShowSongService} from './show-song.service';
import {ShowSong} from './show-song';
import {Song} from '../../songs/services/song';
import {Show} from './show';
import {User} from '../../../services/user/user';
describe('ShowSongService', () => { describe('ShowSongService', () => {
let service: ShowSongService; let service: ShowSongService;
@@ -12,13 +16,13 @@ describe('ShowSongService', () => {
let songDataServiceSpy: jasmine.SpyObj<SongDataService>; let songDataServiceSpy: jasmine.SpyObj<SongDataService>;
let userServiceSpy: jasmine.SpyObj<UserService>; let userServiceSpy: jasmine.SpyObj<UserService>;
let showServiceSpy: jasmine.SpyObj<ShowService>; let showServiceSpy: jasmine.SpyObj<ShowService>;
let user$: BehaviorSubject<any>; let user$: BehaviorSubject<User | null>;
const song = {id: 'song-1', key: 'G', title: 'Amazing Grace'} as any; const song = {id: 'song-1', key: 'G', title: 'Amazing Grace'} as unknown as Song;
const showSong = {id: 'show-song-1', songId: 'song-1'} as any; const showSong = {id: 'show-song-1', songId: 'song-1'} as unknown as ShowSong;
const show = {id: 'show-1', order: ['show-song-1', 'show-song-2']} as any; const show = {id: 'show-1', order: ['show-song-1', 'show-song-2']} as unknown as Show;
beforeEach(() => { beforeEach(async () => {
user$ = new BehaviorSubject<any>({id: 'user-1', name: 'Benjamin', role: 'editor', chordMode: 'letters', songUsage: {}}); user$ = new BehaviorSubject<User | null>({id: 'user-1', name: 'Benjamin', role: 'editor', chordMode: 'onlyFirst', songUsage: {}});
showSongDataServiceSpy = jasmine.createSpyObj<ShowSongDataService>('ShowSongDataService', ['add', 'read$', 'list$', 'delete', 'update$']); showSongDataServiceSpy = jasmine.createSpyObj<ShowSongDataService>('ShowSongDataService', ['add', 'read$', 'list$', 'delete', 'update$']);
songDataServiceSpy = jasmine.createSpyObj<SongDataService>('SongDataService', ['read$']); songDataServiceSpy = jasmine.createSpyObj<SongDataService>('SongDataService', ['read$']);
userServiceSpy = jasmine.createSpyObj<UserService>('UserService', ['incSongCount', 'decSongCount'], { userServiceSpy = jasmine.createSpyObj<UserService>('UserService', ['incSongCount', 'decSongCount'], {
@@ -37,7 +41,7 @@ describe('ShowSongService', () => {
showServiceSpy.read$.and.returnValue(of(show)); showServiceSpy.read$.and.returnValue(of(show));
showServiceSpy.update$.and.resolveTo(); showServiceSpy.update$.and.resolveTo();
void TestBed.configureTestingModule({ await TestBed.configureTestingModule({
providers: [ providers: [
{provide: ShowSongDataService, useValue: showSongDataServiceSpy}, {provide: ShowSongDataService, useValue: showSongDataServiceSpy},
{provide: SongDataService, useValue: songDataServiceSpy}, {provide: SongDataService, useValue: songDataServiceSpy},
@@ -62,7 +66,7 @@ describe('ShowSongService', () => {
songId: 'song-1', songId: 'song-1',
key: 'G', key: 'G',
keyOriginal: 'G', keyOriginal: 'G',
chordMode: 'letters', chordMode: 'onlyFirst',
addedLive: true, addedLive: true,
}); });
}); });
@@ -99,7 +103,7 @@ describe('ShowSongService', () => {
await service.delete$('show-1', 'show-song-1', 0); await service.delete$('show-1', 'show-song-1', 0);
expect(showSongDataServiceSpy.delete).toHaveBeenCalledWith('show-1', 'show-song-1'); expect(showSongDataServiceSpy.delete).toHaveBeenCalledWith('show-1', 'show-song-1');
expect(showServiceSpy.update$).toHaveBeenCalledWith('show-1', {order: ['show-song-2']}); expect(showServiceSpy.update$).toHaveBeenCalledWith('show-1', jasmine.objectContaining({order: ['show-song-2']}));
expect(userServiceSpy.decSongCount).toHaveBeenCalledWith('song-1'); expect(userServiceSpy.decSongCount).toHaveBeenCalledWith('song-1');
}); });

View File

@@ -5,6 +5,7 @@ import {ShowSong} from './show-song';
import {SongDataService} from '../../songs/services/song-data.service'; import {SongDataService} from '../../songs/services/song-data.service';
import {UserService} from '../../../services/user/user.service'; import {UserService} from '../../../services/user/user.service';
import {ShowService} from './show.service'; import {ShowService} from './show.service';
import {arrayRemove, arrayUnion} from 'firebase/firestore';
@Injectable({ @Injectable({
providedIn: 'root', providedIn: 'root',
@@ -27,8 +28,9 @@ export class ShowSongService {
chordMode: user.chordMode, chordMode: user.chordMode,
addedLive, addedLive,
}; };
await this.userService.incSongCount(songId); const showSongId = await this.showSongDataService.add(showId, data);
return await this.showSongDataService.add(showId, data); await Promise.all([this.userService.incSongCount(songId), this.showService.update$(showId, {songIds: arrayUnion(songId) as never})]);
return showSongId;
} }
public read$ = (showId: string, songId: string): Observable<ShowSong | null> => this.showSongDataService.read$(showId, songId); public read$ = (showId: string, songId: string): Observable<ShowSong | null> => this.showSongDataService.read$(showId, songId);
@@ -38,14 +40,19 @@ export class ShowSongService {
public list = (showId: string): Promise<ShowSong[]> => firstValueFrom(this.list$(showId)); public list = (showId: string): Promise<ShowSong[]> => firstValueFrom(this.list$(showId));
public async delete$(showId: string, showSongId: string, index: number): Promise<void> { public async delete$(showId: string, showSongId: string, index: number): Promise<void> {
const [showSong, show] = await Promise.all([this.read(showId, showSongId), firstValueFrom(this.showService.read$(showId))]); const [showSong, show, showSongs] = await Promise.all([this.read(showId, showSongId), firstValueFrom(this.showService.read$(showId)), this.list(showId)]);
if (!show) return; if (!show) return;
if (!showSong) return; if (!showSong) return;
const order = [...show.order]; const order = [...show.order];
order.splice(index, 1); order.splice(index, 1);
const hasSameSongStillInShow = showSongs.some(song => song.id !== showSongId && song.songId === showSong.songId);
await Promise.all([this.showSongDataService.delete(showId, showSongId), this.showService.update$(showId, {order}), this.userService.decSongCount(showSong.songId)]); await Promise.all([
this.showSongDataService.delete(showId, showSongId),
this.showService.update$(showId, hasSameSongStillInShow ? {order} : {order, songIds: arrayRemove(showSong.songId) as never}),
this.userService.decSongCount(showSong.songId),
]);
} }
public update$ = async (showId: string, songId: string, data: Partial<ShowSong>): Promise<void> => await this.showSongDataService.update$(showId, songId, data); public update$ = async (showId: string, songId: string, data: Partial<ShowSong>): Promise<void> => await this.showSongDataService.update$(showId, songId, data);

View File

@@ -1,5 +1,5 @@
import {TestBed} from '@angular/core/testing'; import {TestBed} from '@angular/core/testing';
import {BehaviorSubject, of} from 'rxjs'; import {BehaviorSubject, firstValueFrom, of} from 'rxjs';
import {ShowDataService} from './show-data.service'; import {ShowDataService} from './show-data.service';
import {ShowService} from './show.service'; import {ShowService} from './show.service';
import {UserService} from '../../../services/user/user.service'; import {UserService} from '../../../services/user/user.service';
@@ -8,23 +8,25 @@ describe('ShowService', () => {
let service: ShowService; let service: ShowService;
let showDataServiceSpy: jasmine.SpyObj<ShowDataService>; let showDataServiceSpy: jasmine.SpyObj<ShowDataService>;
let user$: BehaviorSubject<unknown>; let user$: BehaviorSubject<unknown>;
let shows$: BehaviorSubject<unknown[]>;
const shows = [ const shows = [
{id: 'show-1', owner: 'user-1', published: false, archived: false}, {id: 'show-1', owner: 'user-1', published: false, archived: false},
{id: 'show-2', owner: 'other-user', published: true, archived: false}, {id: 'show-2', owner: 'other-user', published: true, archived: false},
{id: 'show-3', owner: 'user-1', published: true, archived: true}, {id: 'show-3', owner: 'user-1', published: true, archived: true},
] as never; ] as never;
beforeEach(() => { beforeEach(async () => {
user$ = new BehaviorSubject<unknown>({id: 'user-1'}); user$ = new BehaviorSubject<unknown>({id: 'user-1'});
shows$ = new BehaviorSubject<unknown[]>(shows as unknown[]);
showDataServiceSpy = jasmine.createSpyObj<ShowDataService>('ShowDataService', ['read$', 'listPublicSince$', 'update', 'add'], { showDataServiceSpy = jasmine.createSpyObj<ShowDataService>('ShowDataService', ['read$', 'listPublicSince$', 'update', 'add'], {
list$: of(shows), list$: shows$.asObservable() as unknown as ShowDataService['list$'],
}); });
showDataServiceSpy.read$.and.returnValue(of(shows[0])); showDataServiceSpy.read$.and.returnValue(of(shows[0]));
showDataServiceSpy.listPublicSince$.and.returnValue(of([shows[1]])); showDataServiceSpy.listPublicSince$.and.returnValue(of([shows[1]]));
showDataServiceSpy.update.and.resolveTo(); showDataServiceSpy.update.and.resolveTo();
showDataServiceSpy.add.and.resolveTo('new-show-id'); showDataServiceSpy.add.and.resolveTo('new-show-id');
void TestBed.configureTestingModule({ await TestBed.configureTestingModule({
providers: [ providers: [
{provide: ShowDataService, useValue: showDataServiceSpy}, {provide: ShowDataService, useValue: showDataServiceSpy},
{provide: UserService, useValue: {user$: user$.asObservable()}}, {provide: UserService, useValue: {user$: user$.asObservable()}},
@@ -38,34 +40,36 @@ describe('ShowService', () => {
expect(service).toBeTruthy(); expect(service).toBeTruthy();
}); });
it('should list published shows and own drafts, but exclude archived ones', done => { it('should list published shows and own drafts, but exclude archived ones', async () => {
service.list$().subscribe(result => { const result = await firstValueFrom(service.list$());
expect(result.map(show => show.id)).toEqual(['show-1', 'show-2']); expect(result.map(show => show.id)).toEqual(['show-1', 'show-2']);
done();
});
}); });
it('should filter out private drafts when publishedOnly is true', done => { it('should filter out private drafts when publishedOnly is true', async () => {
service.list$(true).subscribe(result => { const result = await firstValueFrom(service.list$(true));
expect(result.map(show => show.id)).toEqual(['show-2']); expect(result.map(show => show.id)).toEqual(['show-2']);
done();
});
}); });
it('should delegate public listing to the data service', done => { it('should include own archived shows when requested', async () => {
service.listPublicSince$(6).subscribe(result => { const result = await firstValueFrom(service.list$(false, true));
expect(result).toEqual([shows[1]]); expect(result.map(show => show.id)).toEqual(['show-1', 'show-2', 'show-3']);
expect(showDataServiceSpy.listPublicSince$).toHaveBeenCalledWith(6);
done();
});
}); });
it('should delegate reads to the data service', done => { it('should not include archived shows from other users when requested', async () => {
service.read$('show-1').subscribe(result => { shows$.next([...(shows as unknown as unknown[]), {id: 'show-4', owner: 'other-user', published: true, archived: true}]);
expect(result).toEqual(shows[0]);
expect(showDataServiceSpy.read$).toHaveBeenCalledWith('show-1'); const result = await firstValueFrom(service.list$(false, true));
done(); expect(result.map(show => show.id)).toEqual(['show-1', 'show-2', 'show-3']);
}); });
it('should delegate public listing to the data service', async () => {
await expectAsync(firstValueFrom(service.listPublicSince$(6))).toBeResolvedTo([shows[1]]);
expect(showDataServiceSpy.listPublicSince$).toHaveBeenCalledWith(6);
});
it('should delegate reads to the data service', async () => {
await expectAsync(firstValueFrom(service.read$('show-1'))).toBeResolvedTo(shows[0]);
expect(showDataServiceSpy.read$).toHaveBeenCalledWith('show-1');
}); });
it('should delegate updates to the data service', async () => { it('should delegate updates to the data service', async () => {
@@ -97,6 +101,7 @@ describe('ShowService', () => {
showType: type, showType: type,
owner: 'user-1', owner: 'user-1',
order: [], order: [],
songIds: [],
public: true, public: true,
}); });
}); });
@@ -111,6 +116,7 @@ describe('ShowService', () => {
showType: type, showType: type,
owner: 'user-1', owner: 'user-1',
order: [], order: [],
songIds: [],
public: false, public: false,
}); });
}); });

View File

@@ -20,13 +20,15 @@ export class ShowService {
public read$ = (showId: string): Observable<Show | null> => this.showDataService.read$(showId); public read$ = (showId: string): Observable<Show | null> => this.showDataService.read$(showId);
public listPublicSince$ = (lastMonths: number): Observable<Show[]> => this.showDataService.listPublicSince$(lastMonths); public listPublicSince$ = (lastMonths: number): Observable<Show[]> => this.showDataService.listPublicSince$(lastMonths);
public list$(publishedOnly = false): Observable<Show[]> { public list$(publishedOnly = false, includeOwnArchived = false): Observable<Show[]> {
return this.userService.user$.pipe( return this.userService.user$.pipe(
switchMap( switchMap(
() => this.showDataService.list$, () => this.showDataService.list$,
(user: User | null, shows: Show[]) => ({user, shows}) (user: User | null, shows: Show[]) => ({user, shows})
), ),
map(s => s.shows.filter(show => !show.archived).filter(show => show.published || (show.owner === s.user?.id && !publishedOnly))) map(s =>
s.shows.filter(show => !show.archived || (includeOwnArchived && show.owner === s.user?.id)).filter(show => show.published || (show.owner === s.user?.id && !publishedOnly))
)
); );
} }
@@ -39,6 +41,7 @@ export class ShowService {
...data, ...data,
owner: user.id, owner: user.id,
order: [], order: [],
songIds: [],
public: ShowService.SHOW_TYPE_PUBLIC.indexOf(data.showType) !== -1, public: ShowService.SHOW_TYPE_PUBLIC.indexOf(data.showType) !== -1,
}; };
return await this.showDataService.add(calculatedData); return await this.showDataService.add(calculatedData);

View File

@@ -1,14 +1,16 @@
import {Timestamp} from '@angular/fire/firestore'; import {Timestamp} from '@angular/fire/firestore';
export type PresentationBackground = 'none' | 'blue' | 'green' | 'leder' | 'praise' | 'bible'; export type PresentationBackground = 'none' | 'blue' | 'green' | 'leder' | 'praise' | 'bible';
export type ReportedType = null | 'pending' | 'reported' | 'not-required';
export interface Show { export interface Show {
id: string; id: string;
showType: string; showType: string;
date: Timestamp; date: Timestamp;
owner: string; owner: string;
songIds?: string[];
public: boolean; public: boolean;
reported: boolean; reportedType: ReportedType;
published: boolean; published: boolean;
archived: boolean; archived: boolean;
order: string[]; order: string[];

View File

@@ -1,136 +1,127 @@
@if (show$ | async; as show) { <app-page-frame title="Veranstaltungen" [withMenu]="false">
<div> @if (show$ | async; as show) {
<app-card <div content>
[fullscreen]="useSwiper" <app-card
closeLink="../" [fullscreen]="useSwiper"
heading="{{ show.showType | showType }}, {{ closeLink="../"
heading="{{ show.showType | showType }}, {{
show.date.toDate() | date: 'dd.MM.yyyy' show.date.toDate() | date: 'dd.MM.yyyy'
}} - {{ getStatus(show) }}" }} - {{ getStatus(show) }}"
> >
@if (!useSwiper) { @if (!useSwiper) {
<p>{{ show.public ? 'öffentliche' : 'geschlossene' }} Veranstaltung von <p class="show-meta">
<app-user-name [userId]="show.owner"></app-user-name> {{ show.public ? 'öffentliche' : 'geschlossene' }} Veranstaltung von
</p> <app-user-name [userId]="show.owner"></app-user-name>
}
<div class="head">
<div>
@if (!useSwiper) {
<mat-checkbox [(ngModel)]="showText">Text anzeigen</mat-checkbox>
}
</div>
<div [class.floating]="useSwiper">
<app-menu-button (click)="onZoomOut()" @fade [icon]="faZoomOut" class="btn-delete btn-icon"
matTooltip="Verkleinern"></app-menu-button>
<app-menu-button (click)="onZoomIn()" @fade [icon]="faZoomIn" class="btn-delete btn-icon"
matTooltip="Vergrößern"></app-menu-button>
<app-menu-button (click)="useSwiper=!useSwiper;fullscreen(useSwiper)" @fade
[icon]="useSwiper ? faRestore : faMaximize" class="btn-delete btn-icon"
matTooltip="Vollbild"></app-menu-button>
</div>
</div>
@if (showSongs && !useSwiper) {
<div (cdkDropListDropped)="drop($event, show)"
[cdkDropListDisabled]="show.published || showText"
[style.cursor]="!(show.published || showText) ? 'drag' : 'inherit'"
[style.font-size]="textSize + 'em'"
cdkDropList
class="song-list">
@for (song of orderedShowSongs(show); track trackBy(i, song); let i = $index) {
<div cdkDrag class="song-row">
<app-song
[fullscreen]="useSwiper"
[index]="i"
[showId]="showId"
[showSong]="song"
[showText]="showText"
[show]="show"
></app-song>
</div>
}
</div>
}
@if (useSwiper) {
<swiper-container scrollbar="true">
@for (song of orderedShowSongs(show); track trackBy(i, song); let i = $index) {
<swiper-slide
[style.font-size]="textSize + 'em'"
class="song-swipe">
<app-song
[fullscreen]="true"
[index]="i"
[showId]="showId"
[showSong]="song"
[showText]="true"
[show]="show"
></app-song>
<div class="time">{{ currentTime | date: 'HH:mm' }}</div>
@if (getNextSong(orderedShowSongs(show), i); as next) {
<div class="next-song">{{ next }}
<fa-icon [icon]="faNextSong"></fa-icon>
</div>
}
</swiper-slide>
}
</swiper-container>
}
@if (songs$ | async; as songs) {
@if (songs && !show.published && !useSwiper) {
<app-add-song
[showSongs]="showSongs"
[show]="show"
[songs]="songs"
></app-add-song>
}
}
@if (!useSwiper) {
<app-button-row>
<ng-container *appRole="['leader']">
<ng-container *appOwner="show.owner"> <ng-container *appOwner="show.owner">
@if (!show.archived) { <app-badge [type]="getPublishedBadgeType(show)">{{ show.published | publishedType }}</app-badge>
<app-button (click)="onArchive(true)" [icon]="faBox"> @if (show.reportedType) {
Archivieren <app-badge [type]="getReportedTypeBadgeType(show)">{{ show.reportedType | reportedType }}</app-badge>
</app-button>
}
@if (show.archived) {
<app-button (click)="onArchive(false)" [icon]="faBoxOpen">
Wiederherstellen
</app-button>
}
@if (!show.published) {
<app-button (click)="onPublish(true)" [icon]="faPublish">
Veröffentlichen
</app-button>
}
@if (show.published) {
<app-button (click)="onPublish(false)" [icon]="faUnpublish">
Veröffentlichung zurückziehen
</app-button>
}
@if (show.published) {
<app-button (click)="onShare(show)" [icon]="faShare">
Teilen
</app-button>
}
@if (!show.published) {
<app-button (click)="onChange(show.id)" [icon]="faSliders">
Ändern
</app-button>
} }
</ng-container> </ng-container>
</ng-container> </p>
<app-button [icon]="faDownload" [matMenuTriggerFor]="menu"> }
Herunterladen <div class="head">
</app-button> <div>
<mat-menu #menu="matMenu"> @if (!useSwiper) {
<app-button (click)="onDownload()" [icon]="faUser"> <mat-checkbox [(ngModel)]="showText">Text anzeigen</mat-checkbox>
Ablauf für Lobpreisgruppe }
</app-button> </div>
<app-button (click)="onDownloadHandout()" [icon]="faUsers"> <div [class.floating]="useSwiper">
Handout mit Copyright Infos <app-menu-button (click)="onZoomOut()" @fade [icon]="faZoomOut" class="btn-delete btn-icon"
</app-button> matTooltip="Verkleinern"></app-menu-button>
</mat-menu> <app-menu-button (click)="onZoomIn()" @fade [icon]="faZoomIn" class="btn-delete btn-icon"
</app-button-row> matTooltip="Vergrößern"></app-menu-button>
} <app-menu-button
</app-card> (click)="useSwiper=!useSwiper;fullscreen(useSwiper)"
</div> @fade
} [icon]="useSwiper ? faRestore : faMaximize"
class="btn-delete btn-icon"
matTooltip="Vollbild"
></app-menu-button>
</div>
</div>
@if (showSongs && !useSwiper) {
<div
(cdkDropListDropped)="drop($event, show)"
[cdkDropListDisabled]="show.published || showText"
[style.--song-key-column-width]="getSongKeyColumnWidth(show)"
[style.font-size]="textSize + 'em'"
cdkDropList
class="song-list"
>
@for (song of orderedShowSongs(show); track trackBy(i, song); let i = $index) {
<div cdkDrag class="song-row">
<app-song
[dragHandle]="!(show.published || showText)"
[fullscreen]="useSwiper"
[index]="i"
[showId]="showId"
[showSong]="song"
[showText]="showText"
[show]="show"
></app-song>
</div>
}
</div>
}
@if (useSwiper) {
<swiper-container scrollbar="true">
@for (song of orderedShowSongs(show); track trackBy(i, song); let i = $index) {
<swiper-slide [style.font-size]="textSize + 'em'" class="song-swipe">
<app-song [fullscreen]="true" [index]="i" [showId]="showId" [showSong]="song" [showText]="true"
[show]="show"></app-song>
<div class="time">{{ currentTime | date: 'HH:mm' }}</div>
@if (getNextSong(orderedShowSongs(show), i); as next) {
<div class="next-song">
{{ next }}
<fa-icon [icon]="faNextSong"></fa-icon>
</div>
}
</swiper-slide>
}
</swiper-container>
}
@if (songs$ | async; as songs) {
@if (songs && !show.published && !useSwiper) {
<app-add-song [showSongs]="showSongs" [show]="show" [songs]="songs"></app-add-song>
}
}
@if (!useSwiper) {
<app-button-row>
<ng-container *appRole="['leader']">
<ng-container *appOwner="show.owner">
@if (!show.archived) {
<app-button (click)="onArchive(true)" [icon]="faBox"> Archivieren</app-button>
}
@if (show.archived) {
<app-button (click)="onArchive(false)" [icon]="faBoxOpen"> Wiederherstellen</app-button>
}
@if (!show.published) {
<app-button (click)="onPublish(show, true)" [icon]="faPublish"> Veröffentlichen</app-button>
}
@if (show.published) {
<app-button (click)="onPublish(show, false)" [icon]="faUnpublish"> Veröffentlichung zurückziehen
</app-button>
}
@if (show.published) {
<app-button (click)="onShare(show)" [icon]="faShare"> Teilen</app-button>
}
@if (show.published && show.reportedType === 'pending') {
<app-button (click)="onReport(show)" [icon]="faReport"> CCLI</app-button>
}
@if (!show.published) {
<app-button (click)="onChange(show.id)" [icon]="faSliders"> Ändern</app-button>
}
</ng-container>
</ng-container>
<app-button [icon]="faDownload" [matMenuTriggerFor]="menu"> Herunterladen</app-button>
<mat-menu #menu="matMenu">
<app-button (click)="onDownload()" [icon]="faUser"> Ablauf für Lobpreisgruppe</app-button>
<app-button (click)="onDownloadHandout()" [icon]="faUsers"> Handout mit Copyright Infos</app-button>
</mat-menu>
</app-button-row>
}
</app-card>
</div>
}
</app-page-frame>

View File

@@ -1,6 +1,6 @@
:host { :host {
--button-padding-mobile: 10px; --button-padding-mobile: 4px;
--button-font-size-mobile: 25px; --button-font-size-mobile: 20px;
} }
.song-row:not(:last-child) { .song-row:not(:last-child) {
@@ -13,6 +13,13 @@
min-height: calc(100vh - 60px); min-height: calc(100vh - 60px);
} }
.show-meta {
display: flex;
align-items: center;
gap: 8px;
flex-wrap: wrap;
}
.head { .head {
display: flex; display: flex;
@@ -52,7 +59,7 @@
} }
.next-song { .next-song {
color: var(--text-muted); color: var(--text-soft);
position: fixed; position: fixed;
bottom: 0; bottom: 0;
right: 10px; right: 10px;
@@ -63,7 +70,7 @@
} }
.time { .time {
color: var(--text-muted); color: var(--text-soft);
position: fixed; position: fixed;
bottom: 0; bottom: 0;
left: 10px; left: 10px;

View File

@@ -1,24 +1,114 @@
import {ComponentFixture, TestBed, waitForAsync} from '@angular/core/testing'; import {ComponentFixture, TestBed} from '@angular/core/testing';
import {BehaviorSubject, of} from 'rxjs';
import {ShowComponent} from './show.component'; import {ShowComponent} from './show.component';
import {ActivatedRoute, Router} from '@angular/router';
import {ShowService} from '../services/show.service';
import {SongService} from '../../songs/services/song.service';
import {ShowSongService} from '../services/show-song.service';
import {DocxService} from '../services/docx.service';
import {UserService} from '../../../services/user/user.service';
import {MatDialog} from '@angular/material/dialog';
import {GuestShowService} from '../../guest/guest-show.service';
describe('ShowComponent', () => { describe('ShowComponent', () => {
let component: ShowComponent; let component: ShowComponent;
let fixture: ComponentFixture<ShowComponent>; let fixture: ComponentFixture<ShowComponent>;
let showServiceSpy: jasmine.SpyObj<ShowService>;
let showSongServiceSpy: jasmine.SpyObj<ShowSongService>;
let dialogSpy: jasmine.SpyObj<MatDialog>;
let user$: BehaviorSubject<unknown>;
let userId$: BehaviorSubject<string | null>;
beforeEach(waitForAsync(() => { beforeEach(async () => {
void TestBed.configureTestingModule({ showServiceSpy = jasmine.createSpyObj<ShowService>('ShowService', ['update$', 'read$']);
showSongServiceSpy = jasmine.createSpyObj<ShowSongService>('ShowSongService', ['list$', 'list']);
dialogSpy = jasmine.createSpyObj<MatDialog>('MatDialog', ['open']);
user$ = new BehaviorSubject<unknown>({id: 'user-1', role: ['leader']});
userId$ = new BehaviorSubject<string | null>('user-1');
showServiceSpy.read$.and.returnValue(of(null));
showServiceSpy.update$.and.resolveTo();
showSongServiceSpy.list$.and.returnValue(of([]));
showSongServiceSpy.list.and.resolveTo([]);
await TestBed.configureTestingModule({
imports: [ShowComponent], imports: [ShowComponent],
providers: [
{provide: ActivatedRoute, useValue: {params: of({showId: 'show-1'})}},
{provide: ShowService, useValue: showServiceSpy},
{provide: SongService, useValue: {list$: () => of([])}},
{provide: ShowSongService, useValue: showSongServiceSpy},
{provide: DocxService, useValue: {create: jasmine.createSpy('create').and.resolveTo()}},
{provide: Router, useValue: {navigateByUrl: jasmine.createSpy('navigateByUrl')}},
{
provide: UserService,
useValue: {
user$: user$.asObservable(),
userId$: userId$.asObservable(),
loggedIn$: () => of(true),
},
},
{provide: MatDialog, useValue: dialogSpy},
{provide: GuestShowService, useValue: {share: jasmine.createSpy('share').and.resolveTo('https://example.invalid')}},
],
}).compileComponents(); }).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(ShowComponent); fixture = TestBed.createComponent(ShowComponent);
component = fixture.componentInstance; component = fixture.componentInstance;
fixture.detectChanges();
}); });
it('should create', () => { it('should create', () => {
void expect(component).toBeTruthy(); void expect(component).toBeTruthy();
}); });
it('should reset reportedType when unpublishing', async () => {
await component.onPublish({id: 'show-1', public: true} as never, false);
expect(showServiceSpy.update$).toHaveBeenCalledWith('show-1', {published: false, reportedType: null});
});
it('should set not-required for private shows when publishing', async () => {
await component.onPublish({id: 'show-1', public: false} as never, true);
expect(showServiceSpy.update$).toHaveBeenCalledWith('show-1', {published: true, reportedType: 'not-required'});
});
it('should set pending for public shows with reportable CCLI songs', async () => {
showSongServiceSpy.list.and.resolveTo([{legalOwner: 'CCLI', legalOwnerId: '123'}] as never);
await component.onPublish({id: 'show-1', public: true} as never, true);
expect(showServiceSpy.update$).toHaveBeenCalledWith('show-1', {published: true, reportedType: 'pending'});
});
it('should set not-required for public shows without reportable CCLI songs', async () => {
showSongServiceSpy.list.and.resolveTo([{legalOwner: 'CCLI', legalOwnerId: ''}] as never);
await component.onPublish({id: 'show-1', public: true} as never, true);
expect(showServiceSpy.update$).toHaveBeenCalledWith('show-1', {published: true, reportedType: 'not-required'});
});
it('should open report dialog with deduplicated reportable songs and mark show as reported', () => {
component.showSongs = [
{id: 'show-song-1', songId: 'song-1', title: 'Alpha', legalOwner: 'CCLI', legalOwnerId: '123'},
{id: 'show-song-2', songId: 'song-1', title: 'Alpha', legalOwner: 'CCLI', legalOwnerId: '123'},
{id: 'show-song-3', songId: 'song-2', title: 'Beta', legalOwner: 'other', legalOwnerId: '456'},
{id: 'show-song-4', songId: 'song-3', title: 'Gamma', legalOwner: 'CCLI', legalOwnerId: '789'},
] as never;
dialogSpy.open.and.returnValue({afterClosed: () => of(true)} as never);
component.onReport({id: 'show-1', order: ['show-song-1', 'show-song-2', 'show-song-3', 'show-song-4']} as never);
expect(dialogSpy.open).toHaveBeenCalledWith(jasmine.any(Function), {
width: '640px',
data: {
songs: [
{title: 'Alpha', ccliNumber: '123'},
{title: 'Gamma', ccliNumber: '789'},
],
},
});
expect(showServiceSpy.update$).toHaveBeenCalledWith('show-1', {reportedType: 'reported'});
});
}); });

View File

@@ -1,5 +1,13 @@
import {ChangeDetectorRef, Component, CUSTOM_ELEMENTS_SCHEMA, HostListener, OnDestroy, OnInit, inject} from '@angular/core'; import {
import {filter, map, shareReplay, switchMap, tap} from 'rxjs/operators'; ChangeDetectorRef,
Component,
CUSTOM_ELEMENTS_SCHEMA,
HostListener,
inject,
OnDestroy,
OnInit,
} from '@angular/core';
import {filter, map, shareReplay, switchMap, take, tap} from 'rxjs/operators';
import {ActivatedRoute, Router} from '@angular/router'; import {ActivatedRoute, Router} from '@angular/router';
import {ShowService} from '../services/show.service'; import {ShowService} from '../services/show.service';
import {Observable, of, Subscription} from 'rxjs'; import {Observable, of, Subscription} from 'rxjs';
@@ -14,6 +22,7 @@ import {
faBox, faBox,
faBoxOpen, faBoxOpen,
faChevronRight, faChevronRight,
faCompactDisc,
faFileDownload, faFileDownload,
faLock, faLock,
faMagnifyingGlassMinus, faMagnifyingGlassMinus,
@@ -48,6 +57,13 @@ import {OwnerDirective} from '../../../services/user/owner.directive';
import {ButtonComponent} from '../../../widget-modules/components/button/button.component'; import {ButtonComponent} from '../../../widget-modules/components/button/button.component';
import {MatMenu, MatMenuTrigger} from '@angular/material/menu'; import {MatMenu, MatMenuTrigger} from '@angular/material/menu';
import {ShowTypePipe} from '../../../widget-modules/pipes/show-type-translater/show-type.pipe'; import {ShowTypePipe} from '../../../widget-modules/pipes/show-type-translater/show-type.pipe';
import {UserService} from '../../../services/user/user.service';
import {ReportedTypePipe} from '../../../widget-modules/pipes/reported-type-translator/reported-type.pipe';
import {BadgeComponent, BadgeType} from '../../../widget-modules/components/badge/badge.component';
import {ReportDialogComponent, ReportDialogSong} from '../dialog/report-dialog/report-dialog.component';
import {PublishedTypePipe} from '../../../widget-modules/pipes/published-type-translator/published-type.pipe';
import {ensureSwiperElement} from '../../../services/swiper-element';
import {PageFrameComponent} from '../../../widget-modules/components/sidebar/page-frame.component';
@Component({ @Component({
selector: 'app-show', selector: 'app-show',
@@ -77,27 +93,22 @@ import {ShowTypePipe} from '../../../widget-modules/pipes/show-type-translater/s
AsyncPipe, AsyncPipe,
DatePipe, DatePipe,
ShowTypePipe, ShowTypePipe,
ReportedTypePipe,
PublishedTypePipe,
BadgeComponent,
PageFrameComponent,
], ],
}) })
export class ShowComponent implements OnInit, OnDestroy { export class ShowComponent implements OnInit, OnDestroy {
private activatedRoute = inject(ActivatedRoute);
private showService = inject(ShowService);
private songService = inject(SongService);
private showSongService = inject(ShowSongService);
private docxService = inject(DocxService);
private router = inject(Router);
private cRef = inject(ChangeDetectorRef);
public dialog = inject(MatDialog); public dialog = inject(MatDialog);
private guestShowService = inject(GuestShowService);
public show$: Observable<Show | null> | null = null; public show$: Observable<Show | null> | null = null;
public songs$: Observable<Song[] | null> | null = null; public songs$: Observable<Song[] | null> | null = null;
public showSongs: ShowSong[] | null = null; public showSongs: ShowSong[] | null = null;
public showId: string | null = null; public showId: string | null = null;
public showText = false; public showText = false;
public faBox = faBox; public faBox = faBox;
public faBoxOpen = faBoxOpen; public faBoxOpen = faBoxOpen;
public faReport = faCompactDisc;
public faPublish = faUnlock; public faPublish = faUnlock;
public faUnpublish = faLock; public faUnpublish = faLock;
public faShare = faArrowUpRightFromSquare; public faShare = faArrowUpRightFromSquare;
@@ -112,12 +123,23 @@ export class ShowComponent implements OnInit, OnDestroy {
public faRestore = faMinimize; public faRestore = faMinimize;
public faMaximize = faMaximize; public faMaximize = faMaximize;
public faNextSong = faChevronRight; public faNextSong = faChevronRight;
public currentTime: Date; public currentTime!: Date;
private activatedRoute = inject(ActivatedRoute);
private showService = inject(ShowService);
private songService = inject(SongService);
private showSongService = inject(ShowSongService);
private docxService = inject(DocxService);
private router = inject(Router);
private cRef = inject(ChangeDetectorRef);
private userService = inject(UserService);
private guestShowService = inject(GuestShowService);
private subs: Subscription[] = []; private subs: Subscription[] = [];
private clockIntervalId: ReturnType<typeof setInterval> | null = null;
public ngOnInit(): void { public ngOnInit(): void {
void ensureSwiperElement();
this.currentTime = new Date(); this.currentTime = new Date();
setInterval(() => { this.clockIntervalId = setInterval(() => {
this.currentTime = new Date(); this.currentTime = new Date();
}, 10000); }, 10000);
this.show$ = this.activatedRoute.params.pipe( this.show$ = this.activatedRoute.params.pipe(
@@ -128,7 +150,7 @@ export class ShowComponent implements OnInit, OnDestroy {
shareReplay({ shareReplay({
bufferSize: 1, bufferSize: 1,
refCount: true, refCount: true,
}) }),
); );
this.subs.push( this.subs.push(
this.activatedRoute.params this.activatedRoute.params
@@ -136,12 +158,12 @@ export class ShowComponent implements OnInit, OnDestroy {
map(param => param as {showId: string}), map(param => param as {showId: string}),
map(param => param.showId), map(param => param.showId),
switchMap(showId => this.showSongService.list$(showId)), switchMap(showId => this.showSongService.list$(showId)),
filter(_ => !!_ && _.length > 0) filter(_ => !!_ && _.length > 0),
) )
.subscribe(_ => { .subscribe(_ => {
this.showSongs = _; this.showSongs = _;
this.cRef.markForCheck(); this.cRef.markForCheck();
}) }),
); );
this.songs$ = this.show$.pipe( this.songs$ = this.show$.pipe(
@@ -149,12 +171,15 @@ export class ShowComponent implements OnInit, OnDestroy {
shareReplay({ shareReplay({
bufferSize: 1, bufferSize: 1,
refCount: true, refCount: true,
}) }),
); );
} }
public ngOnDestroy(): void { public ngOnDestroy(): void {
this.subs.forEach(_ => _.unsubscribe()); this.subs.forEach(_ => _.unsubscribe());
if (this.clockIntervalId) {
clearInterval(this.clockIntervalId);
}
} }
public onZoomIn() { public onZoomIn() {
@@ -166,20 +191,39 @@ export class ShowComponent implements OnInit, OnDestroy {
} }
public onArchive(archived: boolean): void { public onArchive(archived: boolean): void {
if (!archived && this.showId != null) void this.showService.update$(this.showId, {archived}); if (!archived && this.showId != null) void this.setArchiveState(false);
else { else {
const dialogRef = this.dialog.open(ArchiveDialogComponent, { const dialogRef = this.dialog.open(ArchiveDialogComponent, {
width: '350px', width: '350px',
}); });
dialogRef.afterClosed().subscribe((archive: boolean) => { dialogRef
if (archive && this.showId != null) void this.showService.update$(this.showId, {archived}); .afterClosed()
}); .pipe(take(1))
.subscribe((archive: boolean) => {
if (archive && this.showId != null) void this.setArchiveState(true);
});
} }
} }
public async onPublish(published: boolean): Promise<void> { public async onPublish(show: Show, published: boolean): Promise<void> {
if (this.showId != null) await this.showService.update$(this.showId, {published}); if (!show.id) {
return;
}
if (!published) {
await this.showService.update$(show.id, {published: false, reportedType: null});
return;
}
if (!show.public) {
await this.showService.update$(show.id, {published: true, reportedType: 'not-required'});
return;
}
const showSongs = this.showSongs ?? (await this.showSongService.list(show.id));
const reportedType = showSongs.some(song => song.legalOwner === 'CCLI' && !!song.legalOwnerId) ? 'pending' : 'not-required';
await this.showService.update$(show.id, {published: true, reportedType});
} }
public onShare = async (show: Show): Promise<void> => { public onShare = async (show: Show): Promise<void> => {
@@ -187,16 +231,54 @@ export class ShowComponent implements OnInit, OnDestroy {
this.dialog.open(ShareDialogComponent, {data: {url, show}}); this.dialog.open(ShareDialogComponent, {data: {url, show}});
}; };
public onReport(show: Show): void {
const songs = this.getReportableSongs(show);
if (songs.length === 0) {
return;
}
const dialogRef = this.dialog.open(ReportDialogComponent, {
width: '640px',
data: {songs},
});
dialogRef
.afterClosed()
.pipe(take(1))
.subscribe((reported: boolean) => {
if (reported) {
void this.showService.update$(show.id, {reportedType: 'reported'});
}
});
}
public getStatus(show: Show): string { public getStatus(show: Show): string {
if (show.published) { if (show.published) {
return 'veröffentlicht'; return 'veröffentlicht';
} }
if (show.reported) { if (show.reportedType === 'reported') {
return 'gemeldet'; return 'gemeldet';
} }
return 'entwurf'; return 'entwurf';
} }
public getReportedTypeBadgeType(show: Show): BadgeType {
switch (show.reportedType) {
case 'pending':
return 'error';
case 'reported':
return 'ok';
case 'not-required':
return 'none';
default:
return 'none';
}
}
public getPublishedBadgeType(show: Show): BadgeType {
return show.published ? 'ok' : 'none';
}
public async onDownload(): Promise<void> { public async onDownload(): Promise<void> {
if (this.showId != null) await this.docxService.create(this.showId); if (this.showId != null) await this.docxService.create(this.showId);
} }
@@ -255,6 +337,52 @@ export class ShowComponent implements OnInit, OnDestroy {
const song = showSongs[i + 1]; const song = showSongs[i + 1];
return song?.title ?? ''; return song?.title ?? '';
} }
public getSongKeyColumnWidth(show: Show): string {
const labels = this.orderedShowSongs(show).map(song => {
if (song.keyOriginal && song.keyOriginal !== song.key) {
return `${song.keyOriginal} -> ${song.key}`;
}
return song.key ?? '';
});
const longestLabelLength = labels.reduce((max, label) => Math.max(max, label.length), 0);
const widthInCh = Math.max(3, longestLabelLength);
return `${widthInCh}ch`;
}
private getReportableSongs(show: Show): ReportDialogSong[] {
const uniqueSongs = new Map<string, ReportDialogSong>();
this.orderedShowSongs(show)
.filter(song => song.legalOwner === 'CCLI' && !!song.legalOwnerId)
.forEach(song => {
const key = song.songId || `${song.title}:${song.legalOwnerId}`;
if (!uniqueSongs.has(key)) {
uniqueSongs.set(key, {
title: song.title,
ccliNumber: song.legalOwnerId,
});
}
});
return Array.from(uniqueSongs.values());
}
private async setArchiveState(archived: boolean): Promise<void> {
if (!this.showId) {
return;
}
const updates: Array<Promise<void | null>> = [this.showService.update$(this.showId, {archived})];
(this.showSongs ?? []).forEach(showSong => {
updates.push(archived ? this.userService.decSongCount(showSong.songId) : this.userService.incSongCount(showSong.songId));
});
await Promise.all(updates);
}
} }
export interface Swiper { export interface Swiper {

View File

@@ -1,69 +1,81 @@
@if (iSong && iSong && show) { @if (iSong && iSong && show) {
<div> <div>
@if (show.published || fullscreen) { @if (show.published || fullscreen) {
<div class="title published"> <div class="title published">
<div class="key">{{ iSong.key }}</div> <div class="key">{{ iSong.key }}</div>
<div>{{ iSong.title }}</div> <div>{{ iSong.title }}</div>
</div>
} @if (!show.published && !fullscreen) {
<div class="song" [class.show-text-layout]="!!showText" [class.compact-layout]="!showText" [class.with-drag]="dragHandle && !edit">
@if (dragHandle && !edit) {
<button aria-label="Lied verschieben" cdkDragHandle class="drag-handle" type="button"></button>
}
<span class="title">{{ iSong.title }}</span>
@if (!edit) {
<div class="keys-container">
<div (click)="openKeySelect()" (keydown.enter)="openKeySelect()" (keydown.space)="openKeySelect()" class="keys" role="button" tabindex="0">
@if (iSong.keyOriginal !== iSong.key) {
<span>{{ iSong.keyOriginal }}&nbsp;&nbsp;</span>
}
<span>{{ iSong.key }}</span>
</div> </div>
} </div>
@if (!show.published && !fullscreen) { } @if (!edit) {
<div class="song"> <app-menu-button (click)="onEdit()" [icon]="faEdit" class="btn-edit btn-icon" matTooltip="Lied für diese Veranstaltung bearbeiten"></app-menu-button>
<span class="title">{{ iSong.title }}</span> } @if (!edit) {
@if (!edit) { <app-menu-button (click)="onDelete()" [icon]="faDelete" class="btn-delete btn-icon" matTooltip="Lied aus Veranstaltung entfernen"></app-menu-button>
<span class="keys">
@if (iSong.keyOriginal !== iSong.key) {
<span>{{ iSong.keyOriginal }}&nbsp;&nbsp;</span>
}<span
(click)="openKeySelect()">{{ iSong.key }}</span>
@if (keys) {
<mat-form-field (click)="option.open()" class="transpose">
<mat-select #option [formControl]="keyFormControl">
@for (key of keys; track key) {
<mat-option [value]="key">{{ key }}</mat-option>
}
</mat-select>
</mat-form-field>
}
</span>
}
@if (!edit) {
<app-menu-button (click)="onEdit()" [icon]="faEdit" class="btn-edit btn-icon"
matTooltip="Lied für diese Veranstaltung bearbeiten"></app-menu-button>
}
@if (!edit) {
<app-menu-button (click)="onDelete()" [icon]="faDelete" class="btn-delete btn-icon"
matTooltip="Lied aus Veranstaltung entfernen"></app-menu-button>
}
</div>
}
@if (edit) {
<mat-form-field appearance="outline">
<mat-label>Songtext</mat-label>
<textarea [cdkTextareaAutosize]="true"
[formControl]="editSongControl"
class="edit"
matInput
matTooltip="Tonart ändern"
></textarea>
</mat-form-field>
}
@if (edit) {
<div>Es wird nur der Liedtext für dieser Veranstaltung geändert.</div>
}
@if (edit) {
<app-button-row>
<app-button (click)="onSave()" [icon]="faSave">Speichern</app-button>
<app-button (click)="onDiscard()" [icon]="faEraser">Verwerfen</app-button>
</app-button-row>
}
@if (!edit && (showText )) {
<app-song-text
(chordModeChanged)="onChordModeChanged($event)"
[chordMode]="iSong.chordMode"
[showSwitch]="!show.published"
[text]="iSong.text"
[transpose]="{ baseKey: iSong.keyOriginal, targetKey: iSong.key }"
></app-song-text>
} }
</div> </div>
@if (!edit) {
<div aria-hidden="true" class="song select" [class.show-text-layout]="!!showText" [class.compact-layout]="!showText" [class.with-drag]="dragHandle">
@if (dragHandle) {
<span class="drag-handle-placeholder"></span>
} @if (!showText) {
<span class="keys">
<mat-form-field class="keys-select">
<mat-select #option [formControl]="keyFormControl" tabIndex="-1">
@for (key of keys; track key) {
<mat-option [value]="key">{{ key }}</mat-option>
}
</mat-select>
</mat-form-field>
</span>
<span class="title"></span>
} @else {
<span class="title"></span>
<span class="keys">
<mat-form-field class="keys-select">
<mat-select #option [formControl]="keyFormControl" tabIndex="-1">
@for (key of keys; track key) {
<mat-option [value]="key">{{ key }}</mat-option>
}
</mat-select>
</mat-form-field>
</span>
}
<span class="btn-edit"></span>
<span class="btn-delete"></span>
</div>
} } @if (edit) {
<mat-form-field appearance="outline">
<mat-label>Songtext</mat-label>
<textarea [cdkTextareaAutosize]="true" [formControl]="editSongControl" class="edit" matInput matTooltip="Tonart ändern"></textarea>
</mat-form-field>
} @if (edit) {
<div>Es wird nur der Liedtext für dieser Veranstaltung geändert.</div>
} @if (edit) {
<app-button-row>
<app-button (click)="onSave()" [icon]="faSave">Speichern</app-button>
<app-button (click)="onDiscard()" [icon]="faEraser">Verwerfen</app-button>
</app-button-row>
} @if (!edit && (showText)) {
<app-song-text
(chordModeChanged)="onChordModeChanged($event)"
[chordMode]="iSong.chordMode"
[showSwitch]="!show.published"
[text]="iSong.text"
[transpose]="{ baseKey: iSong.keyOriginal, targetKey: iSong.key }"
></app-song-text>
}
</div>
} }

View File

@@ -1,12 +1,10 @@
.song { .song {
min-height: 28px; &:not(.select) {
display: grid; min-height: 28px;
grid-template-columns: auto 70px 25px 25px;
@media screen and (max-width: 860px) {
grid-template-columns: auto 70px 45px 45px;
} }
grid-template-areas: "title keys edit delete";
display: grid;
& > * { & > * {
display: flex; display: flex;
@@ -14,12 +12,109 @@
} }
overflow: hidden; overflow: hidden;
&.compact-layout {
grid-template-columns: var(--song-key-column-width, 30px) auto 25px 25px;
grid-template-areas: "keys title edit delete";
@media screen and (max-width: 860px) {
grid-template-columns: var(--song-key-column-width, 30px) auto 30px 30px;
}
&.with-drag {
grid-template-columns: 24px var(--song-key-column-width, 30px) auto 25px 25px;
grid-template-areas: "drag keys title edit delete";
@media screen and (max-width: 860px) {
grid-template-columns: 24px var(--song-key-column-width, 30px) auto 30px 30px;
}
}
}
&.show-text-layout {
grid-template-columns: auto var(--song-key-column-width, 30px) 25px 25px;
grid-template-areas: "title keys edit delete";
@media screen and (max-width: 860px) {
grid-template-columns: auto var(--song-key-column-width, 30px) 30px 30px;
}
&.with-drag {
grid-template-columns: 24px auto var(--song-key-column-width, 30px) 25px 25px;
grid-template-areas: "drag title keys edit delete";
@media screen and (max-width: 860px) {
grid-template-columns: 24px auto var(--song-key-column-width, 30px) 30px 30px;
}
}
}
}
.drag-handle,
.drag-handle-placeholder {
grid-area: drag;
}
.drag-handle {
width: 16px;
height: 36px;
padding: 4px 0;
border: 0;
background: transparent;
cursor: grab;
justify-self: start;
position: relative;
&::before {
content: "";
width: 10px;
height: 18px;
display: block;
border-radius: 999px;
background-image: radial-gradient(circle, var(--text-soft) 1.2px, transparent 1.3px),
radial-gradient(circle, var(--text-soft) 1.2px, transparent 1.3px);
background-position: 0 0, 6px 0;
background-size: 6px 6px;
background-repeat: repeat-y;
opacity: 0.65;
transition: var(--transition);
}
&:hover::before {
opacity: 1;
background-image: radial-gradient(circle, var(--primary-color) 1.2px, transparent 1.3px),
radial-gradient(circle, var(--primary-color) 1.2px, transparent 1.3px);
}
&:active {
cursor: grabbing;
}
}
.drag-handle-placeholder {
width: 16px;
}
.keys-container {
display: flex;
flex-direction: column;
}
.keys-select {
height: 0;
overflow: hidden;
line-height: 0;
min-width: max(100px, var(--song-key-column-width, 30px));
} }
.keys { .keys {
display: flex;
align-items: center;
position: relative; position: relative;
margin-right: 10px; margin-right: 10px;
cursor: pointer; cursor: pointer;
flex-grow: 0;
height: 100%;
&:hover { &:hover {
color: var(--color-primary); color: var(--color-primary);
@@ -41,6 +136,7 @@
.title { .title {
grid-area: title; grid-area: title;
min-width: 0;
&.published { &.published {
margin: 10px 0; margin: 10px 0;
@@ -80,4 +176,5 @@ button {
textarea.edit { textarea.edit {
font-family: 'Ubuntu Mono', monospace; font-family: 'Ubuntu Mono', monospace;
line-height: 15px;
} }

View File

@@ -1,4 +1,4 @@
import {ComponentFixture, TestBed, waitForAsync} from '@angular/core/testing'; import {ComponentFixture, TestBed} from '@angular/core/testing';
import {SongComponent} from './song.component'; import {SongComponent} from './song.component';
@@ -6,11 +6,11 @@ describe('SongComponent', () => {
let component: SongComponent; let component: SongComponent;
let fixture: ComponentFixture<SongComponent>; let fixture: ComponentFixture<SongComponent>;
beforeEach(waitForAsync(() => { beforeEach(async () => {
void TestBed.configureTestingModule({ await TestBed.configureTestingModule({
imports: [SongComponent], imports: [SongComponent],
}).compileComponents(); }).compileComponents();
})); });
beforeEach(() => { beforeEach(() => {
fixture = TestBed.createComponent(SongComponent); fixture = TestBed.createComponent(SongComponent);

View File

@@ -1,8 +1,9 @@
import {Component, Input, OnInit, ViewChild, inject} from '@angular/core'; import {Component, DestroyRef, Input, OnInit, ViewChild, inject} from '@angular/core';
import {takeUntilDestroyed} from '@angular/core/rxjs-interop';
import {ShowSongService} from '../../services/show-song.service'; import {ShowSongService} from '../../services/show-song.service';
import {ShowSong} from '../../services/show-song'; import {ShowSong} from '../../services/show-song';
import {getScale} from '../../../songs/services/key.helper'; import {getScale} from '../../../songs/services/key.helper';
import {ReactiveFormsModule, UntypedFormControl} from '@angular/forms'; import {FormControl, ReactiveFormsModule} from '@angular/forms';
import {ChordMode, SongTextComponent} from '../../../../widget-modules/components/song-text/song-text.component'; import {ChordMode, SongTextComponent} from '../../../../widget-modules/components/song-text/song-text.component';
import {Show} from '../../services/show'; import {Show} from '../../services/show';
import {faEraser, faPenToSquare, faSave, faTrash} from '@fortawesome/free-solid-svg-icons'; import {faEraser, faPenToSquare, faSave, faTrash} from '@fortawesome/free-solid-svg-icons';
@@ -17,6 +18,7 @@ import {MatInput} from '@angular/material/input';
import {CdkTextareaAutosize} from '@angular/cdk/text-field'; import {CdkTextareaAutosize} from '@angular/cdk/text-field';
import {ButtonRowComponent} from '../../../../widget-modules/components/button-row/button-row.component'; import {ButtonRowComponent} from '../../../../widget-modules/components/button-row/button-row.component';
import {ButtonComponent} from '../../../../widget-modules/components/button/button.component'; import {ButtonComponent} from '../../../../widget-modules/components/button/button.component';
import {CdkDragHandle} from '@angular/cdk/drag-drop';
@Component({ @Component({
selector: 'app-song', selector: 'app-song',
@@ -36,14 +38,17 @@ import {ButtonComponent} from '../../../../widget-modules/components/button/butt
ButtonRowComponent, ButtonRowComponent,
ButtonComponent, ButtonComponent,
SongTextComponent, SongTextComponent,
CdkDragHandle,
], ],
}) })
export class SongComponent implements OnInit { export class SongComponent implements OnInit {
private showSongService = inject(ShowSongService); private showSongService = inject(ShowSongService);
private destroyRef = inject(DestroyRef);
@Input() public show: Show | null = null; @Input() public show: Show | null = null;
@Input() public showId: string | null = null; @Input() public showId: string | null = null;
@Input() public showText: boolean | null = null; @Input() public showText: boolean | null = null;
@Input() public dragHandle = false;
@Input() public index = -1; @Input() public index = -1;
@Input() public fullscreen = false; @Input() public fullscreen = false;
public keys: string[] = []; public keys: string[] = [];
@@ -51,11 +56,11 @@ export class SongComponent implements OnInit {
public faEdit = faPenToSquare; public faEdit = faPenToSquare;
public faSave = faSave; public faSave = faSave;
public faEraser = faEraser; public faEraser = faEraser;
public keyFormControl: UntypedFormControl = new UntypedFormControl(); public keyFormControl = new FormControl<string>('', {nonNullable: true});
public iSong: ShowSong | null = null; public iSong: ShowSong | null = null;
public edit = false; public edit = false;
public editSongControl = new UntypedFormControl(); public editSongControl = new FormControl<string | null>(null);
@ViewChild('option') private keyOptions: MatSelect; @ViewChild('option') private keyOptions!: MatSelect;
@Input() @Input()
public set showSong(song: ShowSong) { public set showSong(song: ShowSong) {
@@ -65,8 +70,8 @@ export class SongComponent implements OnInit {
public ngOnInit(): void { public ngOnInit(): void {
if (!this.iSong) return; if (!this.iSong) return;
this.keyFormControl = new UntypedFormControl(this.iSong.key); this.keyFormControl = new FormControl<string>(this.iSong.key, {nonNullable: true});
this.keyFormControl.valueChanges.subscribe((value: string) => { this.keyFormControl.valueChanges.pipe(takeUntilDestroyed(this.destroyRef)).subscribe(value => {
if (!this.showId || !this.iSong) return; if (!this.showId || !this.iSong) return;
void this.showSongService.update$(this.showId, this.iSong.id, {key: value}); void this.showSongService.update$(this.showId, this.iSong.id, {key: value});
}); });

View File

@@ -4,6 +4,7 @@ import {NewComponent} from './new/new.component';
import {ListComponent} from './list/list.component'; import {ListComponent} from './list/list.component';
import {ShowComponent} from './show/show.component'; import {ShowComponent} from './show/show.component';
import {EditComponent} from './edit/edit.component'; import {EditComponent} from './edit/edit.component';
import {RoleGuard} from '../../widget-modules/guards/role.guard';
const routes: Routes = [ const routes: Routes = [
{ {
@@ -14,6 +15,10 @@ const routes: Routes = [
{ {
path: 'new', path: 'new',
component: NewComponent, component: NewComponent,
canActivate: [RoleGuard],
data: {
requiredRoles: ['leader'],
},
}, },
{ {
path: ':showId/edit', path: ':showId/edit',

View File

@@ -1,7 +1,29 @@
export interface ChordAddDescriptor {
raw: string;
quality: 'major' | 'minor' | 'diminished' | 'augmented' | null;
extensions: string[];
additions: string[];
suspensions: string[];
alterations: string[];
modifiers: string[];
}
export interface ChordValidationIssue {
lineNumber: number;
lineText: string;
token: string;
suggestion: string | null;
reason: 'alias' | 'minor_format' | 'major_format' | 'invalid_suffix' | 'unknown_token' | 'tab_character';
message: string;
}
export interface Chord { export interface Chord {
chord: string; chord: string;
length: number; length: number;
position: number; position: number;
slashChord: string | null; slashChord: string | null;
add: string | null; add: string | null;
addDescriptor?: ChordAddDescriptor | null;
prefix?: string;
suffix?: string;
} }

View File

@@ -12,7 +12,7 @@ describe('FileDataService', () => {
let fileDeleteSpy: jasmine.Spy; let fileDeleteSpy: jasmine.Spy;
let dbServiceSpy: jasmine.SpyObj<DbService>; let dbServiceSpy: jasmine.SpyObj<DbService>;
beforeEach(() => { beforeEach(async () => {
filesCollectionValueChangesSpy = jasmine.createSpy('valueChanges').and.returnValue(of([{id: 'file-1', name: 'plan.pdf'}])); filesCollectionValueChangesSpy = jasmine.createSpy('valueChanges').and.returnValue(of([{id: 'file-1', name: 'plan.pdf'}]));
filesCollectionAddSpy = jasmine.createSpy('add').and.resolveTo({id: 'file-2'}); filesCollectionAddSpy = jasmine.createSpy('add').and.resolveTo({id: 'file-2'});
songDocCollectionSpy = jasmine.createSpy('collection').and.returnValue({ songDocCollectionSpy = jasmine.createSpy('collection').and.returnValue({
@@ -30,7 +30,7 @@ describe('FileDataService', () => {
dbServiceSpy = jasmine.createSpyObj<DbService>('DbService', ['doc']); dbServiceSpy = jasmine.createSpyObj<DbService>('DbService', ['doc']);
dbServiceSpy.doc.and.callFake(songDocSpy); dbServiceSpy.doc.and.callFake(songDocSpy);
void TestBed.configureTestingModule({ await TestBed.configureTestingModule({
providers: [{provide: DbService, useValue: dbServiceSpy}], providers: [{provide: DbService, useValue: dbServiceSpy}],
}); });

View File

@@ -1,23 +1,48 @@
import {TestBed} from '@angular/core/testing'; import {TestBed} from '@angular/core/testing';
import {Storage} from '@angular/fire/storage'; import {Storage} from '@angular/fire/storage';
import {FileService} from './file.service';
import {FileDataService} from './file-data.service'; import {FileDataService} from './file-data.service';
import {FileService} from './file.service';
describe('FileService', () => { describe('FileService', () => {
let service: FileService; let service: FileService;
let fileDataServiceSpy: jasmine.SpyObj<FileDataService>;
type FileServiceInternals = FileService & {
resolveDownloadUrl: (path: string) => Promise<string>;
deleteFromStorage: (path: string) => Promise<void>;
};
beforeEach(() => { beforeEach(async () => {
void TestBed.configureTestingModule({ fileDataServiceSpy = jasmine.createSpyObj<FileDataService>('FileDataService', ['delete']);
fileDataServiceSpy.delete.and.resolveTo();
await TestBed.configureTestingModule({
providers: [ providers: [
{provide: Storage, useValue: {}}, {provide: Storage, useValue: {app: 'test-storage'}},
{provide: FileDataService, useValue: {delete: () => Promise.resolve()}}, {provide: FileDataService, useValue: fileDataServiceSpy},
], ],
}); });
service = TestBed.inject(FileService); service = TestBed.inject(FileService);
}); });
it('should be created', () => { it('should be created', () => {
void expect(service).toBeTruthy(); expect(service).toBeTruthy();
});
it('should resolve download urls via AngularFire storage helpers', async () => {
const resolveSpy = spyOn(service as FileServiceInternals, 'resolveDownloadUrl').and.resolveTo('https://cdn.example/file.pdf');
await expectAsync(service.getDownloadUrl('songs/song-1/file.pdf').toPromise()).toBeResolvedTo('https://cdn.example/file.pdf');
expect(resolveSpy).toHaveBeenCalledWith('songs/song-1/file.pdf');
});
it('should delete the file from storage and metadata from firestore', async () => {
const deleteFromStorageSpy = spyOn(service as FileServiceInternals, 'deleteFromStorage').and.resolveTo();
await service.delete('songs/song-1/file.pdf', 'song-1', 'file-1');
expect(deleteFromStorageSpy).toHaveBeenCalledWith('songs/song-1/file.pdf');
expect(fileDataServiceSpy.delete).toHaveBeenCalledWith('song-1', 'file-1');
}); });
}); });

View File

@@ -1,22 +1,28 @@
import {EnvironmentInjector, Injectable, inject, runInInjectionContext} from '@angular/core'; import {EnvironmentInjector, inject, Injectable, runInInjectionContext} from '@angular/core';
import {deleteObject, getDownloadURL, ref, Storage} from '@angular/fire/storage'; import {deleteObject, getDownloadURL, ref, Storage} from '@angular/fire/storage';
import {from, Observable} from 'rxjs'; import {from, Observable} from 'rxjs';
import {FileDataService} from './file-data.service'; import {FileDataService} from './file-data.service';
@Injectable({ @Injectable()
providedIn: 'root',
})
export class FileService { export class FileService {
private storage = inject(Storage); private storage = inject(Storage);
private fileDataService = inject(FileDataService); private fileDataService = inject(FileDataService);
private environmentInjector = inject(EnvironmentInjector); private environmentInjector = inject(EnvironmentInjector);
public getDownloadUrl(path: string): Observable<string> { public getDownloadUrl(path: string): Observable<string> {
return from(runInInjectionContext(this.environmentInjector, () => getDownloadURL(ref(this.storage, path)))); return from(runInInjectionContext(this.environmentInjector, () => this.resolveDownloadUrl(path)));
} }
public delete(path: string, songId: string, fileId: string): void { public delete(path: string, songId: string, fileId: string): void {
void runInInjectionContext(this.environmentInjector, () => deleteObject(ref(this.storage, path))); void runInInjectionContext(this.environmentInjector, () => this.deleteFromStorage(path));
void this.fileDataService.delete(songId, fileId); void this.fileDataService.delete(songId, fileId);
} }
private resolveDownloadUrl(path: string): Promise<string> {
return getDownloadURL(ref(this.storage, path));
}
private deleteFromStorage(path: string): Promise<void> {
return deleteObject(ref(this.storage, path));
}
} }

View File

@@ -5,4 +5,5 @@ export interface Line {
type: LineType; type: LineType;
text: string; text: string;
chords: Chord[] | null; chords: Chord[] | null;
lineNumber?: number;
} }

View File

@@ -1,6 +1,6 @@
import {TestBed} from '@angular/core/testing'; import {TestBed} from '@angular/core/testing';
import {firstValueFrom, Subject} from 'rxjs'; import {firstValueFrom, Subject} from 'rxjs';
import {skip, take, toArray} from 'rxjs/operators'; import {take, toArray} from 'rxjs/operators';
import {DbService} from '../../../services/db.service'; import {DbService} from '../../../services/db.service';
import {SongDataService} from './song-data.service'; import {SongDataService} from './song-data.service';
@@ -14,7 +14,7 @@ describe('SongDataService', () => {
let colSpy: jasmine.Spy; let colSpy: jasmine.Spy;
let dbServiceSpy: jasmine.SpyObj<DbService>; let dbServiceSpy: jasmine.SpyObj<DbService>;
beforeEach(() => { beforeEach(async () => {
songs$ = new Subject<Array<{id: string; title: string}>>(); songs$ = new Subject<Array<{id: string; title: string}>>();
docUpdateSpy = jasmine.createSpy('update').and.resolveTo(); docUpdateSpy = jasmine.createSpy('update').and.resolveTo();
docDeleteSpy = jasmine.createSpy('delete').and.resolveTo(); docDeleteSpy = jasmine.createSpy('delete').and.resolveTo();
@@ -32,7 +32,7 @@ describe('SongDataService', () => {
dbServiceSpy.doc.and.callFake(docSpy); dbServiceSpy.doc.and.callFake(docSpy);
dbServiceSpy.col.and.callFake(colSpy); dbServiceSpy.col.and.callFake(colSpy);
void TestBed.configureTestingModule({ await TestBed.configureTestingModule({
providers: [{provide: DbService, useValue: dbServiceSpy}], providers: [{provide: DbService, useValue: dbServiceSpy}],
}); });

View File

@@ -11,13 +11,20 @@ export class SongDataService {
private dbService = inject(DbService); private dbService = inject(DbService);
private collection = 'songs'; private collection = 'songs';
public list$: Observable<Song[]> = this.dbService.col$<Song>(this.collection).pipe( private loadedList$: Observable<Song[]> = this.dbService.col$<Song>(this.collection).pipe(
shareReplay({
bufferSize: 1,
refCount: false, // keep the listener alive after first subscription to avoid reloading on navigation
})
);
public list$: Observable<Song[]> = this.loadedList$.pipe(
startWith([] as Song[]), // immediate empty emit keeps UI responsive while first snapshot arrives startWith([] as Song[]), // immediate empty emit keeps UI responsive while first snapshot arrives
shareReplay({ shareReplay({
bufferSize: 1, bufferSize: 1,
refCount: false, // keep the listener alive after first subscription to avoid reloading on navigation refCount: false, // keep the listener alive after first subscription to avoid reloading on navigation
}) })
); );
public listLoaded$ = (): Observable<Song[]> => this.loadedList$;
public read$ = (songId: string): Observable<Song | null> => this.dbService.doc$(this.collection + '/' + songId); public read$ = (songId: string): Observable<Song | null> => this.dbService.doc$(this.collection + '/' + songId);
public update$ = async (songId: string, data: Partial<Song>): Promise<void> => await this.dbService.doc(this.collection + '/' + songId).update(data); public update$ = async (songId: string, data: Partial<Song>): Promise<void> => await this.dbService.doc(this.collection + '/' + songId).update(data);

View File

@@ -0,0 +1,29 @@
import {TestBed} from '@angular/core/testing';
import {firstValueFrom, of} from 'rxjs';
import {SongService} from './song.service';
import {SongListResolver} from './song-list.resolver';
describe('SongListResolver', () => {
let resolver: SongListResolver;
let songServiceSpy: jasmine.SpyObj<SongService>;
beforeEach(async () => {
songServiceSpy = jasmine.createSpyObj<SongService>('SongService', ['listLoaded$']);
songServiceSpy.listLoaded$.and.returnValue(of([{id: 'song-1', title: 'Amazing Grace'}]) as never);
await TestBed.configureTestingModule({
providers: [{provide: SongService, useValue: songServiceSpy}],
});
resolver = TestBed.inject(SongListResolver);
});
it('should be created', () => {
expect(resolver).toBeTruthy();
});
it('should resolve the first emitted song list from the service', async () => {
await expectAsync(firstValueFrom(resolver.resolve())).toBeResolvedTo([{id: 'song-1', title: 'Amazing Grace'}] as never);
expect(songServiceSpy.listLoaded$).toHaveBeenCalled();
});
});

View File

@@ -12,6 +12,6 @@ export class SongListResolver {
private songService = inject(SongService); private songService = inject(SongService);
public resolve(): Observable<Song[]> { public resolve(): Observable<Song[]> {
return this.songService.list$().pipe(take(1)); return this.songService.listLoaded$().pipe(take(1));
} }
} }

View File

@@ -1,5 +1,5 @@
import {TestBed} from '@angular/core/testing'; import {TestBed} from '@angular/core/testing';
import {of} from 'rxjs'; import {firstValueFrom, of} from 'rxjs';
import {SongDataService} from './song-data.service'; import {SongDataService} from './song-data.service';
import {SongService} from './song.service'; import {SongService} from './song.service';
import {UserService} from '../../../services/user/user.service'; import {UserService} from '../../../services/user/user.service';
@@ -15,7 +15,7 @@ describe('SongService', () => {
edits: [], edits: [],
} as never; } as never;
beforeEach(() => { beforeEach(async () => {
songDataServiceSpy = jasmine.createSpyObj<SongDataService>('SongDataService', ['read$', 'update$', 'add', 'delete'], { songDataServiceSpy = jasmine.createSpyObj<SongDataService>('SongDataService', ['read$', 'update$', 'add', 'delete'], {
list$: of([song]), list$: of([song]),
}); });
@@ -27,7 +27,7 @@ describe('SongService', () => {
songDataServiceSpy.delete.and.resolveTo(); songDataServiceSpy.delete.and.resolveTo();
userServiceSpy.currentUser.and.resolveTo({name: 'Benjamin'} as never); userServiceSpy.currentUser.and.resolveTo({name: 'Benjamin'} as never);
void TestBed.configureTestingModule({ await TestBed.configureTestingModule({
providers: [ providers: [
{provide: SongDataService, useValue: songDataServiceSpy}, {provide: SongDataService, useValue: songDataServiceSpy},
{provide: UserService, useValue: userServiceSpy}, {provide: UserService, useValue: userServiceSpy},
@@ -41,11 +41,8 @@ describe('SongService', () => {
expect(service).toBeTruthy(); expect(service).toBeTruthy();
}); });
it('should list songs from the data service', done => { it('should list songs from the data service', async () => {
service.list$().subscribe(songs => { await expectAsync(firstValueFrom(service.list$())).toBeResolvedTo([song]);
expect(songs).toEqual([song]);
done();
});
}); });
it('should delegate reads to the data service', async () => { it('should delegate reads to the data service', async () => {

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