17 Commits

Author SHA1 Message Date
a14d860022 Update README.md 2025-06-03 14:35:59 +02:00
9f97e584bd Merge pull request #20 from Slasherss1/1.1.0
v1.1.0
2025-06-03 13:31:05 +02:00
00daf7c972 chore: Bumped version numbers 2025-06-03 13:26:28 +02:00
d4c7084820 feat: Added unchecked room highlighting. Resolves #11 2025-06-03 13:23:58 +02:00
0c60f39152 feat: Added menu items and account security to settings 2025-06-01 21:48:56 +02:00
ca6037d405 feat: added user search to various components 2025-06-01 17:44:48 +02:00
94702834b4 feat: Added user search component. Resolves #15 2025-06-01 13:54:47 +02:00
3b56d40d5a feat: Added admin start page 2025-06-01 10:25:05 +02:00
efd76e16a1 feat: Added notification dialog on frontend 2025-05-31 19:56:31 +02:00
375bb1ceb4 feat: Added notifications outbox to admin panel 2025-05-31 16:57:58 +02:00
86347e254b feat: Added redirect after login for users. Closes #17 2025-05-24 11:26:42 +02:00
cf2fa0b607 fix: Redesigned user cards 2025-05-21 19:56:25 +02:00
45fb44712e fix: Made menu empty if no items.
Not too elegant of a solution, but works.
Going to do the same in print display of backend. Probably not gonna be elegant aswell.
2025-05-20 22:02:51 +02:00
92768ceda6 fix: The date picker now outputs start of day 2025-05-20 21:22:49 +02:00
26dac21e7e fix: Added missing news message. Resolves #18. 2025-05-20 21:10:21 +02:00
7d98cc2c49 fix: Added serviceWorker env and fixed #19 2025-05-20 20:58:52 +02:00
90d5b5da1c feat: Made login errors download from server 2025-05-16 00:38:59 +02:00
83 changed files with 1351 additions and 304 deletions

View File

@@ -1,8 +1,4 @@
# Ipwa
This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 15.0.4.
This project depends on the [Backend server](https://github.com/Slasherss1/ipwa-backend2)
## Things to change
Change following files:
- (Optional) `src/assets/icons/*` - You can change the icons to your own
This project depends on the [Backend server](https://github.com/Slasherss1/ipwa-backend)

View File

@@ -70,6 +70,30 @@
"with": "src/environments/environment.development.ts"
}
]
},
"swDevelopment": {
"buildOptimizer": false,
"optimization": false,
"vendorChunk": true,
"extractLicenses": false,
"sourceMap": true,
"namedChunks": true,
"outputHashing": "all",
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.swdev.ts"
}
],
"assets": [
{
"glob": "ngsw-worker.js",
"input": "node_modules/@angular/servce-worker",
"output": "."
},
"src/ngsw.json",
"src/manifest.webmanifest"
]
}
},
"defaultConfiguration": "production"

View File

@@ -1,16 +1,16 @@
{
"$schema": "./node_modules/@angular/service-worker/config/schema.json",
"index": "./index.html",
"index": "/ipwa/index.html",
"assetGroups": [
{
"name": "app",
"installMode": "prefetch",
"resources": {
"files": [
"/favicon.ico",
"/manifest.webmanifest",
"/*.css",
"/*.js"
"/ipwa/favicon.ico",
"/ipwa/manifest.webmanifest",
"/ipwa/*.css",
"/ipwa/*.js"
]
}
},
@@ -20,8 +20,8 @@
"updateMode": "prefetch",
"resources": {
"files": [
"./assets/**",
"/**/*.(svg|cur|jpg|jpeg|png|apng|webp|avif|gif|otf|ttf|woff|woff2)"
"/ipwa/assets/**",
"/ipwa/**/*.(svg|cur|jpg|jpeg|png|apng|webp|avif|gif|otf|ttf|woff|woff2)"
]
}
}

2
package-lock.json generated
View File

@@ -1,6 +1,6 @@
{
"name": "ipwa",
"version": "1.0.1",
"version": "1.1.0",
"lockfileVersion": 3,
"requires": true,
"packages": {

View File

@@ -1,6 +1,6 @@
{
"name": "ipwa",
"version": "1.0.1",
"version": "1.1.0",
"license": "GPL-3.0-or-later",
"scripts": {
"ng": "ng",

View File

@@ -3,7 +3,7 @@
<mat-label>Wyszukaj</mat-label>
<input matInput (keyup)="filter($event)">
</mat-form-field>
<button mat-icon-button (click)="new()"><mat-icon>add</mat-icon></button>
<button mat-icon-button (click)="openUserCard()"><mat-icon>add</mat-icon></button>
</div>
<mat-spinner *ngIf="loading"></mat-spinner>
<table mat-table [dataSource]="users">
@@ -24,17 +24,9 @@
<td mat-cell *matCellDef="let element">{{element.uname}}</td>
</div>
<div matColumnDef="actions">
<th mat-header-cell *matHeaderCellDef>Akcje</th>
<th mat-header-cell *matHeaderCellDef>Karta użytkownika</th>
<td mat-cell *matCellDef="let element">
<button mat-mini-fab (click)="resetPass(element._id)"><mat-icon>lock_reset</mat-icon></button>
<button mat-mini-fab (click)="edit(element)"><mat-icon>edit</mat-icon></button>
<button mat-mini-fab (click)="toggleLock(element)">
<div [ngSwitch]="element.locked">
<mat-icon *ngSwitchCase="true">lock</mat-icon>
<mat-icon *ngSwitchDefault>lock_open</mat-icon>
</div>
</button>
<button mat-mini-fab (click)="delete(element._id)"><mat-icon>delete_forever</mat-icon></button>
<button mat-mini-fab (click)="openUserCard(element._id)"><mat-icon>manage_accounts</mat-icon></button>
</td>
</div>
<tr mat-header-row *matHeaderRowDef="collumns"></tr>

View File

@@ -4,10 +4,7 @@ import { MatDialog } from '@angular/material/dialog';
import { MatTableDataSource } from '@angular/material/table';
import { MatPaginator } from '@angular/material/paginator';
import { MatSnackBar } from '@angular/material/snack-bar';
import { UserDeleteComponent } from './user-delete/user-delete.component';
import { UserEditComponent } from './user-edit/user-edit.component';
import { catchError, throwError } from 'rxjs';
import { UserResetComponent } from './user-reset/user-reset.component';
import { LocalStorageService } from 'src/app/services/local-storage.service';
import { Group } from 'src/app/types/group';
import User from 'src/app/types/user';
@@ -57,75 +54,9 @@ export class AccountMgmtComponent implements OnInit, AfterViewInit {
this.users.filter = value.toLowerCase().trim()
}
edit(item: any) {
this.dialog.open(UserEditComponent, {data: {user: item, groups: this.groups}}).afterClosed().subscribe(reply => {
if (reply) {
this.ac.accs.putAcc(item._id, reply).pipe(catchError((err)=>{
this.sb.open("Wystąpił błąd. Skontaktuj się z obsługą programu.")
return throwError(()=> new Error(err.message))
})).subscribe((data)=> {
if (data.status == 200) {
this.sb.open("Użytkownik został zmodyfikowany.", undefined, {duration: 2500})
this.ngOnInit()
} else {
this.sb.open("Wystąpił błąd. Skontaktuj się z obsługą programu.")
}
})
}
})
}
new() {
this.dialog.open(UserEditComponent, {data: {groups: this.groups}}).afterClosed().subscribe(reply => {
if (reply) {
this.ac.accs.postAcc(reply).pipe(catchError((err)=>{
this.sb.open("Wystąpił błąd. Skontaktuj się z obsługą programu.")
return throwError(()=> new Error(err.message))
})).subscribe((data)=> {
if (data.status == 201) {
this.sb.open("Użytkownik został utworzony.", undefined, {duration: 2500})
this.ngOnInit()
} else {
this.sb.open("Wystąpił błąd. Skontaktuj się z obsługą programu.")
}
})
}
})
}
delete(id: string) {
this.dialog.open(UserDeleteComponent).afterClosed().subscribe(reply => {
if (reply) {
this.ac.accs.deleteAcc(id).subscribe((res) => {
if (res.status == 200) {
this.sb.open("Użytkownik został usunięty.", undefined, {duration: 2500})
this.ngOnInit()
} else {
this.sb.open("Wystąpił błąd. Skontaktuj się z obsługą programu.")
console.error(res);
}
})
}
})
}
resetPass(id: string) {
this.dialog.open(UserResetComponent).afterClosed().subscribe((res) => {
if (res == true) {
this.ac.accs.resetPass(id).subscribe((patch)=>{
if (patch.status == 200) {
this.sb.open("Hasło zostało zresetowane", undefined, {duration: 2500})
}
})
}
})
}
toggleLock(item: any) {
this.ac.accs.putAcc(item._id, {locked: !item.locked}).subscribe((res) => {
if (res.status == 200) {
item.locked = !item.locked
}
openUserCard(id?: string) {
this.dialog.open<UserEditComponent, UserEditComponent.InputData, UserEditComponent.ReturnData>(UserEditComponent, {data: {id: id, type: id ? "edit" : "new", groups: this.groups}}).afterClosed().subscribe(r => {
if (r) this.ngOnInit()
})
}

View File

@@ -1,39 +1,67 @@
<form [formGroup]="form" (ngSubmit)="editUser()">
<mat-form-field appearance="outline">
<mat-label>Imię</mat-label>
<input type="text" matInput formControlName="fname">
</mat-form-field>
<mat-form-field appearance="outline">
<mat-label>Nazwisko</mat-label>
<input type="text" matInput formControlName="surname">
</mat-form-field>
<mat-form-field appearance="outline">
<mat-label>Pokój</mat-label>
<input type="text" matInput formControlName="room">
</mat-form-field>
<mat-form-field appearance="outline">
<mat-label>Nazwa użytkownika</mat-label>
<input type="text" matInput required formControlName="uname">
</mat-form-field>
<mat-form-field appearance="outline">
<mat-label>Grupy</mat-label>
<mat-select multiple formControlName="groups">
@for (item of groups; track $index) {
<mat-option [value]="item._id">{{item.name}}</mat-option>
<h1 mat-dialog-title>Karta użytkownika</h1>
<mat-dialog-content>
<form [formGroup]="form">
<div>
<mat-form-field appearance="outline" color="accent">
<mat-label>Imię</mat-label>
<input type="text" matInput formControlName="fname">
</mat-form-field>
<mat-form-field appearance="outline" color="accent">
<mat-label>Nazwisko</mat-label>
<input type="text" matInput formControlName="surname">
</mat-form-field>
<mat-form-field appearance="outline" color="accent">
<mat-label>Pokój</mat-label>
<input type="text" matInput formControlName="room">
</mat-form-field>
<mat-form-field appearance="outline" color="accent">
<mat-label>Grupy</mat-label>
<mat-select multiple formControlName="groups">
@for (item of groups; track $index) {
<mat-option [value]="item._id">{{item.name}}</mat-option>
}
</mat-select>
</mat-form-field>
<span *ngIf="data.type == 'edit'">Data rejestracji:<br>{{regDate?.format('DD.MM.YYYY')}}</span>
</div>
<div>
<mat-form-field appearance="outline" color="accent">
<mat-label>Nazwa użytkownika</mat-label>
<input type="text" matInput required formControlName="uname">
</mat-form-field>
@if (data.type == "edit") {
<button mat-stroked-button color="accent" (click)="resetPass()">Resetuj hasło</button>
@if (locked) {
<button mat-stroked-button color="warn" (click)="toggleLock(false)"><mat-icon>lock</mat-icon>Blokada ręczna</button>
} @else {
<button mat-stroked-button color="accent" (click)="toggleLock(true)">Zablokuj konto</button>
}
@if (lockout) {
<button mat-stroked-button color="warn" (click)="disableLockout()"><mat-icon>lock_clock</mat-icon>Auto-Blokada</button>
} @else {
<button mat-stroked-button disabled>Auto-Blokada nieczynna</button>
}
<mat-form-field *ngIf="ls.permChecker(32)" color="accent">
<mat-label>Uprawnienia</mat-label>
<mat-select multiple formControlName="flags">
<mat-option [value]="1" *ngIf="ls.capCheck(1)">Wiadomości</mat-option>
<mat-option [value]="2" *ngIf="ls.capCheck(2)">Jadłospis</mat-option>
<mat-option [value]="4" *ngIf="ls.capCheck(4)">Powiadomienia</mat-option>
<mat-option [value]="8" *ngIf="ls.capCheck(8)">Grupy</mat-option>
<mat-option [value]="16">Konta</mat-option>
<mat-option [value]="64" *ngIf="ls.capCheck(32)">Klucze</mat-option>
<mat-option [value]="128" *ngIf="ls.capCheck(16)">Czystość</mat-option>
</mat-select>
</mat-form-field>
}
</mat-select>
</mat-form-field>
<mat-form-field *ngIf="this.ls.permChecker(32)">
<mat-label>Uprawnienia</mat-label>
<mat-select multiple formControlName="flags">
<mat-option [value]="1" *ngIf="ls.capCheck(1)">Wiadomości</mat-option>
<mat-option [value]="2" *ngIf="ls.capCheck(2)">Jadłospis</mat-option>
<mat-option [value]="4" *ngIf="ls.capCheck(4)">Powiadomienia</mat-option>
<mat-option [value]="8" *ngIf="ls.capCheck(8)">Grupy</mat-option>
<mat-option [value]="16">Konta</mat-option>
<mat-option [value]="64" *ngIf="ls.capCheck(32)">Klucze</mat-option>
<mat-option [value]="128" *ngIf="ls.capCheck(16)">Czystość</mat-option>
</mat-select>
</mat-form-field>
<button mat-stroked-button>Wyślij</button>
</form>
</div>
</form>
</mat-dialog-content>
<mat-dialog-actions>
@if (data.type == "edit") {
<button mat-stroked-button color="warn" style="margin-right: auto;">Usuń konto</button>
}
<button mat-stroked-button mat-dialog-close>Zamknij</button>
<button mat-flat-button color="accent" (click)="submit()">Zapisz</button>
<mat-spinner diameter="32" color="accent" *ngIf="loading"></mat-spinner>
</mat-dialog-actions>

View File

@@ -4,7 +4,29 @@
}
form {
margin-top: 1ch !important;
display: flex;
flex-direction: column;
grid-auto-flow: column;
flex-direction: row;
flex-wrap: wrap;
align-items: center;
justify-content: center;
column-gap: 3ch;
div {
display: grid;
grid-template-columns: 1fr;
grid-template-rows: repeat(5, 1fr);
align-items: center;
button {
align-self: stretch;
justify-self: stretch;
height: auto;
margin-bottom: 1lh;
}
}
}
mat-dialog-actions {
display: flex;
justify-content: flex-end;
}

View File

@@ -1,52 +1,126 @@
import { Component, Inject } from '@angular/core';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { MAT_DIALOG_DATA, MatDialog, MatDialogRef } from '@angular/material/dialog';
import { FormControl, FormGroup } from '@angular/forms';
import { LocalStorageService } from 'src/app/services/local-storage.service';
import { Group } from 'src/app/types/group';
import { AdminCommService } from '../../admin-comm.service';
import { UserDeleteComponent } from '../user-delete/user-delete.component';
import { MatSnackBar } from '@angular/material/snack-bar';
import { UserResetComponent } from '../user-reset/user-reset.component';
import { catchError, throwError } from 'rxjs';
import { Moment } from 'moment';
import * as moment from 'moment';
export namespace UserEditComponent {
export type InputData = {type: "new" | "edit", id?: string, groups: Group[]}
export type ReturnData = true | undefined
}
@Component({
selector: 'app-user-edit',
templateUrl: './user-edit.component.html',
styleUrls: ['./user-edit.component.scss']
})
export class UserEditComponent {
form: FormGroup
export class UserEditComponent {
lockout = false;
locked = false;
loading = false;
form: FormGroup = new FormGroup({
fname: new FormControl<string>(""),
surname: new FormControl<string>(""),
room: new FormControl<string>(""),
uname: new FormControl<string>(""),
groups: new FormControl<Array<string>>([]),
flags: new FormControl<Array<number>>([]),
})
groups: Group[]
constructor (public dialogRef: MatDialogRef<UserEditComponent>, @Inject(MAT_DIALOG_DATA) public data: any, readonly ls: LocalStorageService) {
if (data.user == null) {
data.user = {
fname: "",
surname: "",
room: "",
uname: "",
groups: [],
admin: 0
id?: string
regDate?: Moment;
constructor (
public dialogRef: MatDialogRef<UserEditComponent>,
@Inject(MAT_DIALOG_DATA) public data: UserEditComponent.InputData,
readonly ls: LocalStorageService,
readonly acu: AdminCommService,
private dialog: MatDialog,
private sb: MatSnackBar
) {
this.groups = data.groups
if (data.type == "edit") {
this.id = data.id
this.acu.accs.getUser(data.id!).subscribe((r) => {
this.regDate = moment(r.regDate)
var flags: Array<number> = []
if (r.admin) {
if ((r.admin & 1) == 1) flags.push(1)
if ((r.admin & 2) == 2) flags.push(2)
if ((r.admin & 4) == 4) flags.push(4)
if ((r.admin & 8) == 8) flags.push(8)
if ((r.admin & 16) == 16) flags.push(16)
if ((r.admin & 32) == 32) flags.push(32)
if ((r.admin & 64) == 64) flags.push(64)
if ((r.admin & 128) == 128) flags.push(128)
}
this.locked = r.locked ? true : false
this.lockout = r.lockout
this.form.get("fname")?.setValue(r.fname)
this.form.get("surname")?.setValue(r.surname)
this.form.get("room")?.setValue(r.room)
this.form.get("uname")?.setValue(r.uname)
this.form.get("groups")?.setValue(r.groups)
this.form.get("flags")?.setValue(flags)
})
}
}
protected submit() {
this.loading = true
if (this.data.type == "edit") {
this.acu.accs.putAcc(this.id!, this.getForm()).pipe(catchError((err)=>{
this.sb.open("Wystąpił błąd. Skontaktuj się z obsługą programu.")
return throwError(()=> new Error(err.message))
})).subscribe((data)=> {
if (data.status == 200) {
this.sb.open("Użytkownik został zmodyfikowany.", undefined, {duration: 2500})
this.dialogRef.close(true)
} else {
this.sb.open("Wystąpił błąd. Skontaktuj się z obsługą programu.")
this.loading = false
}
})
} else {
this.acu.accs.postAcc(this.getForm()).pipe(catchError((err)=>{
this.sb.open("Wystąpił błąd. Skontaktuj się z obsługą programu.")
return throwError(()=> new Error(err.message))
})).subscribe((data)=> {
if (data.status == 201) {
this.sb.open("Użytkownik został utworzony.", undefined, {duration: 2500})
this.dialogRef.close(true)
} else {
this.sb.open("Wystąpił błąd. Skontaktuj się z obsługą programu.")
this.loading = false
}
})
}
}
protected disableLockout() {
this.loading = true
this.acu.accs.clearLockout(this.id!).pipe(catchError((err)=>{
this.sb.open("Wystąpił błąd. Skontaktuj się z obsługą programu.")
return throwError(()=> new Error(err.message))
})).subscribe((s) => {
if (s.status == 200) {
this.loading = false
this.lockout = false
} else {
this.sb.open("Wystąpił błąd. Skontaktuj się z obsługą programu.")
this.loading = false
}
}
this.groups = data.groups ? data.groups : []
var flags: Array<number> = []
if (data.user.admin) {
if ((data.user.admin & 1) == 1) flags.push(1)
if ((data.user.admin & 2) == 2) flags.push(2)
if ((data.user.admin & 4) == 4) flags.push(4)
if ((data.user.admin & 8) == 8) flags.push(8)
if ((data.user.admin & 16) == 16) flags.push(16)
if ((data.user.admin & 32) == 32) flags.push(32)
if ((data.user.admin & 64) == 64) flags.push(64)
if ((data.user.admin & 128) == 128) flags.push(128)
}
this.form = new FormGroup({
fname: new FormControl(data.user.fname),
surname: new FormControl(data.user.surname),
room: new FormControl(data.user.room),
uname: new FormControl<string>(data.user.uname),
groups: new FormControl<Array<string>>(data.user.groups),
flags: new FormControl<Array<number>>(flags),
})
}
protected editUser() {
this.dialogRef.close({
protected getForm() {
return {
fname: this.form.get('fname')?.value,
surname: this.form.get('surname')?.value,
room: this.form.get('room')?.value,
@@ -60,6 +134,44 @@ export class UserEditComponent {
return undefined
}
})()
}
}
protected delete() {
this.dialog.open(UserDeleteComponent).afterClosed().subscribe(reply => {
if (reply) {
this.acu.accs.deleteAcc(this.id!).subscribe((res) => {
if (res.status == 200) {
this.sb.open("Użytkownik został usunięty.", undefined, {duration: 2500})
this.dialogRef.close()
} else {
this.sb.open("Wystąpił błąd. Skontaktuj się z obsługą programu.")
console.error(res);
}
})
}
})
}
protected resetPass() {
this.loading = true
this.dialog.open(UserResetComponent).afterClosed().subscribe((res) => {
if (res == true) {
this.acu.accs.resetPass(this.id!).subscribe((patch)=>{
if (patch.status == 200) {
this.sb.open("Hasło zostało zresetowane", undefined, {duration: 2500})
this.loading = false
}
})
}
})
}
protected toggleLock(state: boolean) {
this.acu.accs.putAcc(this.id!, {locked: state}).subscribe((res) => {
if (res.status == 200) {
this.locked = state
}
})
}
}

View File

@@ -131,7 +131,7 @@ export class AdminCommService {
return this.http.post<Status>(environment.apiEndpoint+`/admin/accs`, item, {withCredentials: true})
},
putAcc: (id: string, update: object) => {
putAcc: (id: string, update: Partial<User>) => {
return this.http.put<Status>(environment.apiEndpoint+`/admin/accs/${id}`, update, {withCredentials: true})
},
@@ -141,6 +141,14 @@ export class AdminCommService {
deleteAcc: (id: string) => {
return this.http.delete<Status>(environment.apiEndpoint+`/admin/accs/${id}`, {withCredentials: true})
},
getUser: (id: string) => {
return this.http.get<Omit<User, "pass"> & {lockout: boolean}>(environment.apiEndpoint+`/admin/accs/${id}`, {withCredentials: true})
},
clearLockout: (id: string) => {
return this.http.delete<Status>(environment.apiEndpoint+`/admin/accs/${id}/lockout`, {withCredentials: true})
}
}
//#endregion
@@ -174,6 +182,17 @@ export class AdminCommService {
},
getGroups: () => {
return this.http.get<Group[]>(environment.apiEndpoint+"/admin/notif/groups", {withCredentials: true})
},
outbox: {
getSent: () => {
return this.http.get<{_id: string, sentDate: moment.Moment, title: string}[]>(environment.apiEndpoint+"/admin/notif/outbox", {withCredentials: true})
},
getBody: (id: string) => {
return this.http.get(environment.apiEndpoint+`/admin/notif/outbox/${id}/message`, {withCredentials: true, responseType: "text"})
},
getRcpts: (id: string) => {
return this.http.get<{_id: string, uname: string, room?: string, fname?: string, surname?: string}[]>(environment.apiEndpoint+`/admin/notif/outbox/${id}/rcpts`, {withCredentials: true})
}
}
}
//#endregion
@@ -233,7 +252,7 @@ export class AdminCommService {
return this.http.post<Status>(environment.apiEndpoint+`/admin/clean/attendence/${room}`, attendence, {withCredentials: true})
},
getSummary: () => {
return this.http.get<{room: string, hours: string[], notes: string}[]>(environment.apiEndpoint+`/admin/clean/attendenceSummary`, {withCredentials: true})
return this.http.get<{room: string, hours: string[], notes: string, auto: boolean}[]>(environment.apiEndpoint+`/admin/clean/attendenceSummary`, {withCredentials: true})
},
deleteRoom: (room: string) => {
return this.http.delete<Status>(environment.apiEndpoint+`/admin/clean/attendence/${room}`, {withCredentials: true})

View File

@@ -1,17 +1,4 @@
<mat-toolbar color="accent">
<button mat-icon-button (click)="drawer.toggle()"><mat-icon>menu</mat-icon></button>
<span>{{title.getTitle()}}</span>
<span style="flex: 1 1 auto"></span>
<button mat-icon-button *ngIf="toolbar.menu" [matMenuTriggerFor]="menu"><mat-icon>more_vert</mat-icon></button>
</mat-toolbar>
<mat-menu #menu="matMenu">
@for (item of toolbar.menu; track $index) {
<button mat-menu-item *ngIf="item.check" (click)="toolbar.comp[item.fn]()">
<mat-icon *ngIf="item.icon">{{item.icon}}</mat-icon>
<span>{{item.title}}</span>
</button>
}
</mat-menu>
<app-toolbar [drawer]="drawer"/>
<mat-sidenav-container>
<mat-sidenav #drawer mode="over" autoFocus="false">
<mat-nav-list>

View File

@@ -1,9 +1,7 @@
import { Component } from '@angular/core';
import { Title } from '@angular/platform-browser';
import { Router } from '@angular/router';
import { LocalStorageService } from '../services/local-storage.service';
import { Link } from '../types/link';
import { ToolbarService } from './toolbar.service';
@Component({
selector: 'app-admin-view',
@@ -26,7 +24,7 @@ export class AdminViewComponent {
public get LINKS(): Link[] {
return this._LINKS.filter(v => v.enabled);
}
constructor(readonly title: Title, readonly router: Router, readonly ls: LocalStorageService, protected toolbar: ToolbarService) { }
constructor(readonly router: Router, readonly ls: LocalStorageService) { }
goNormal() {
this.router.navigateByUrl('app')
}

View File

@@ -18,7 +18,7 @@
</div>
<div matColumnDef="actions">
<th mat-header-cell *matHeaderCellDef>Usuń</th>
<td mat-cell *matCellDef="let item"><button mat-mini-fab color="warn" (click)="delete(item.room)"><mat-icon>delete</mat-icon></button></td>
<td mat-cell *matCellDef="let item"><button mat-mini-fab color="warn" (click)="delete(item.room)" *ngIf="!item.auto"><mat-icon>delete</mat-icon></button></td>
</div>
<tr mat-header-row *matHeaderRowDef="collumns"></tr>
<tr mat-row *matRowDef="let rowData; columns: collumns"></tr>

View File

@@ -1,5 +1,5 @@
import { Component, OnInit } from '@angular/core';
import { ToolbarService } from '../../toolbar.service';
import { ToolbarService } from '../../toolbar/toolbar.service';
import { Router, ActivatedRoute } from '@angular/router';
import { MatTableDataSource } from '@angular/material/table';
import { AdminCommService } from '../../admin-comm.service';
@@ -11,7 +11,7 @@ import { AdminCommService } from '../../admin-comm.service';
})
export class AttendenceSummaryComponent implements OnInit {
data: MatTableDataSource<{room: string, hours: string[], notes: string}> = new MatTableDataSource<{room: string, hours: string[], notes: string}>();
data: MatTableDataSource<{room: string, hours: string[], notes: string, auto: boolean}> = new MatTableDataSource<{room: string, hours: string[], notes: string, auto: boolean}>();
collumns = ['room', 'hours', 'actions']
constructor (private toolbar: ToolbarService, private router: Router, private route: ActivatedRoute, private ac: AdminCommService) {

View File

@@ -4,7 +4,7 @@ import * as moment from 'moment';
import { FormArray, FormBuilder } from '@angular/forms';
import { weekendFilter } from 'src/app/fd.da';
import { MatSnackBar } from '@angular/material/snack-bar';
import { ToolbarService } from '../toolbar.service';
import { ToolbarService } from '../toolbar/toolbar.service';
import { ActivatedRoute, Router } from '@angular/router';
import { MatDialog } from '@angular/material/dialog';
import { AttendenceComponent } from './attendence/attendence.component';
@@ -49,8 +49,8 @@ export class GradesComponent implements OnInit, OnDestroy {
if (!this.filter(this.date)) this.date.isoWeekday(8);
this.toolbar.comp = this
this.toolbar.menu = [
{ title: "Pokoje do sprawdzenia", check: true, fn: "attendenceSummary", icon: "overview"},
{ title: "Podsumowanie", check: true, fn: "summary", icon: "analytics" },
{ title: "Obecność", check: true, fn: "attendenceSummary", icon: "overview"}
]
this.form.valueChanges.subscribe((v) => {
this.calculate()

View File

@@ -1,5 +1,5 @@
import { Component, OnDestroy, OnInit, ViewChild } from '@angular/core';
import { ToolbarService } from '../../toolbar.service';
import { ToolbarService } from '../../toolbar/toolbar.service';
import { ActivatedRoute, Router } from '@angular/router';
import { AdminCommService } from '../../admin-comm.service';
import * as moment from 'moment';

View File

@@ -8,7 +8,7 @@
</mat-chip-listbox>
<button mat-icon-button (click)="new()"><mat-icon>add</mat-icon></button>
</div>
<mat-spinner *ngIf="loading"></mat-spinner>
<mat-spinner *ngIf="loading" color="accent"></mat-spinner>
<table mat-table [dataSource]="keys">
<div matColumnDef="room">
<th mat-header-cell *matHeaderCellDef>Sala</th>

View File

@@ -1,6 +1,6 @@
<mat-dialog-content>
<form (ngSubmit)="send()" [formGroup]="form">
<mat-form-field>
<mat-form-field color="accent">
<mat-label>Sala</mat-label>
<mat-select formControlName="room" required>
@for (item of rooms; track $index) {
@@ -9,17 +9,9 @@
</mat-select>
<mat-error *ngIf="form.controls['room'].hasError('required')">Wymagane</mat-error>
</mat-form-field>
<mat-form-field>
<mat-form-field color="accent">
<mat-label>Wypożyczający</mat-label>
<!-- TODO: Add user selector -->
<input matInput placeholder="Nazwa użytkownika" formControlName="user" required>
<!-- <input #input matInput placeholder="Nazwa użytkownika" formControlName="user" required [matAutocomplete]="auto" (input)="filter()">
<mat-autocomplete requireSelection #auto="matAutocomplete">
@for (item of unames; track item) {
<mat-option [value]="item">{{item}}</mat-option>
}
</mat-autocomplete> -->
<mat-error *ngIf="form.controls['user'].hasError('unf')">Zła nazwa użytkownika</mat-error>
<app-user-search formControlName="user" required/>
<mat-error *ngIf="form.controls['user'].hasError('required')">Wymagane</mat-error>
</mat-form-field>
<button mat-button>Wyślij</button>

View File

@@ -1,8 +1,8 @@
import { Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { Component, OnInit } from '@angular/core';
import { AdminCommService } from '../../admin-comm.service';
import { MatDialogRef } from '@angular/material/dialog';
import { FormControl, FormGroup } from '@angular/forms';
import { startWith } from 'rxjs';
import { UserSearchResult } from 'src/app/commonComponents/user-search/user-search.component';
@Component({
selector: 'app-new-key',
@@ -10,11 +10,10 @@ import { startWith } from 'rxjs';
styleUrl: './new-key.component.scss'
})
export class NewKeyComponent implements OnInit {
// @ViewChild('input') input!: ElementRef<HTMLInputElement>
rooms: string[] = []
form = new FormGroup({
room: new FormControl<string>(""),
user: new FormControl<string>("")
user: new FormControl<UserSearchResult | null>(null)
})
unames: any[] = []
constructor ( private ac: AdminCommService, public dialogRef: MatDialogRef<NewKeyComponent> ) {}
@@ -24,26 +23,11 @@ export class NewKeyComponent implements OnInit {
this.rooms = v
})
}
// filter() {
// const v = this.input.nativeElement.value
// console.log(v);
// if (v) {
// this.ac.userFilter(v.toLowerCase()).subscribe((v) => {
// this.unames = v
// })
// } else {
// this.unames = []
// }
// }
send() {
if (this.form.valid) {
this.dialogRef.close(this.form.value)
} else {
this.form.controls['user'].setErrors({unf: true})
}
}
}
}

View File

@@ -31,7 +31,7 @@ export class MenuAddComponent {
submit() {
switch (this.type) {
case "day":
this.dialogRef.close({type: "day", value: this.day.utc()})
this.dialogRef.close({type: "day", value: this.day.utc().startOf('day')})
break;
case "week":
this.dialogRef.close({type: "week", value: {start: this.range.value.start?.utc().hours(24), count: 5}})

View File

@@ -101,11 +101,11 @@ export class MenuNewComponent {
}
editSn(id: string) {
this.ac.menu.editSn(id, this.dataSource.data.find(v => v._id == id)?.sn).subscribe(s => this.refreshIfGood(s))
this.ac.menu.editSn(id, this.dataSource.data.find(v => v._id == id)!.sn).subscribe(s => this.refreshIfGood(s))
}
editOb(id: string) {
this.ac.menu.editOb(id, this.dataSource.data.find(v => v._id == id)?.ob).subscribe(s => this.refreshIfGood(s))
this.ac.menu.editOb(id, this.dataSource.data.find(v => v._id == id)!.ob).subscribe(s => this.refreshIfGood(s))
}
editKol(id: string) {

View File

@@ -22,4 +22,9 @@
<mat-card-footer>
<p>{{item.date | date:'d-LL-yyyy HH:mm'}}</p>
</mat-card-footer>
</mat-card>
<mat-card *ngIf="news.length == 0">
<p>
Brak wiadomości.
</p>
</mat-card>

View File

@@ -22,6 +22,10 @@ mat-card-content p {
white-space: pre-line;
}
mat-card p {
margin: 15px;
}
button {
margin-right: 4pt;
}

View File

@@ -1,11 +1,10 @@
<!-- TODO: Remake the notifications module -->
<form [formGroup]="form" (ngSubmit)="submit()">
<div formGroupName="recp">
<mat-radio-group formControlName="type">
<mat-radio-button value="uname">
<mat-radio-button value="uid">
<mat-form-field>
<mat-label>Nazwa użytkownika</mat-label>
<input matInput type="text" formControlName="uname">
<mat-label>Użytkownik</mat-label>
<app-user-search formControlName="uid" required/>
</mat-form-field>
</mat-radio-button>
<mat-radio-button value="room">

View File

@@ -1,20 +1,32 @@
import { Component, OnInit } from '@angular/core';
import { Component, OnDestroy, OnInit } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';
import { AdminCommService } from '../admin-comm.service';
import { Notification } from 'src/app/types/notification';
import { Group } from 'src/app/types/group';
import { LocalStorageService } from 'src/app/services/local-storage.service';
import { ToolbarService } from '../toolbar/toolbar.service';
import { ActivatedRoute, Router } from '@angular/router';
import { UserSearchResult } from 'src/app/commonComponents/user-search/user-search.component';
@Component({
selector: 'app-notifications',
templateUrl: './notifications.component.html',
styleUrls: ['./notifications.component.scss']
})
export class NotificationsComponent implements OnInit {
export class NotificationsComponent implements OnInit, OnDestroy {
groups!: Group[]
constructor (private readonly acs: AdminCommService, readonly ls: LocalStorageService) { }
constructor (private readonly acs: AdminCommService, readonly ls: LocalStorageService, private toolbar: ToolbarService, private router: Router, private route: ActivatedRoute ) {
this.toolbar.comp = this
this.toolbar.menu = [
{ title: "Wysłane", fn: "outbox", icon: "outbox" }
]
}
outbox() {
this.router.navigate(["outbox"], { relativeTo: this.route })
}
ngOnInit(): void {
this.acs.notif.getGroups().subscribe((v) => {
@@ -22,11 +34,20 @@ export class NotificationsComponent implements OnInit {
})
}
ngOnDestroy(): void {
this.toolbar.comp = undefined
this.toolbar.menu = undefined
}
public inbox() {
}
success?: { sent: number; possible: number; };
form = new FormGroup<NotificationForm>({
form = new FormGroup({
recp: new FormGroup({
uname: new FormControl<string>(''),
uid: new FormControl<UserSearchResult | null>(null),
room: new FormControl<string|null>(null),
group: new FormControl<string>(''),
type: new FormControl<"room" | "uname" | "group">('uname', {nonNullable: true})
@@ -36,19 +57,8 @@ export class NotificationsComponent implements OnInit {
})
submit() {
this.acs.notif.send(this.form.value as Notification).subscribe((data) => {
this.acs.notif.send({...this.form.value, recp: {...this.form.get("recp")?.value, uid: this.form.controls['recp'].controls['uid'].value?._id}} as Notification).subscribe((data) => {
this.success = data
})
}
}
interface NotificationForm {
body: FormControl<string>;
title: FormControl<string>;
recp: FormGroup<{
uname: FormControl<string | null>;
room: FormControl<string | null>;
group: FormControl<string | null>;
type: FormControl<"room" | "uname" | "group">;
}>
}

View File

@@ -0,0 +1,31 @@
<mat-card>
<mat-card-header>
<mat-card-title-group>
<mat-card-title>
{{item.title}}
</mat-card-title>
<mat-card-subtitle>{{item.sentDate.format('[Wysłano] dddd DD MMMM YYYYr. o HH:mm')}}</mat-card-subtitle>
</mat-card-title-group>
</mat-card-header>
<mat-card-content>
<p *ngIf="body">
{{body}}
</p>
<hr>
<ul>
@for (user of rcpts; track $index) {
<li>
<span *ngIf="user.room">{{user.room}}: </span>{{user.fname}} {{user.surname}} <span
style="color: gray">({{user.uname}})</span>
</li>
}
</ul>
</mat-card-content>
<mat-card-footer>
<mat-card-actions>
<button mat-stroked-button (click)="getMessage()" *ngIf="!body">Wczytaj treść</button>
<button mat-stroked-button (click)="getRcpts()" *ngIf="!rcpts">Wczytaj odbiorców</button>
<mat-spinner diameter="32" color="accent" *ngIf="loading"></mat-spinner>
</mat-card-actions>
</mat-card-footer>
</mat-card>

View File

@@ -0,0 +1,3 @@
mat-card-title {
font-size: 24pt;
}

View File

@@ -0,0 +1,23 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { MessageComponent } from './message.component';
describe('MessageComponent', () => {
let component: MessageComponent;
let fixture: ComponentFixture<MessageComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [MessageComponent]
})
.compileComponents();
fixture = TestBed.createComponent(MessageComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@@ -0,0 +1,31 @@
import { Component, Input } from '@angular/core';
import { AdminCommService } from 'src/app/admin-view/admin-comm.service';
@Component({
selector: 'app-message',
templateUrl: './message.component.html',
styleUrl: './message.component.scss'
})
export class MessageComponent {
@Input() item!: {_id: string, sentDate: moment.Moment, title: string}
body?: string
rcpts?: {_id: string, uname: string, room?: string, fname?: string, surname?: string}[]
loading: boolean = false
constructor (readonly acu: AdminCommService) {}
getMessage() {
this.loading = true
this.acu.notif.outbox.getBody(this.item._id).subscribe(v => {
this.body = v
this.loading = false
})
}
getRcpts() {
this.loading = true
this.acu.notif.outbox.getRcpts(this.item._id).subscribe(v => {
this.rcpts = v
this.loading = false
})
}
}

View File

@@ -0,0 +1,6 @@
<p>Wysłane wiadomości:</p>
<div class="cardContainer">
@for (item of messages; track $index) {
<app-message [item]="item"></app-message>
}
</div>

View File

@@ -0,0 +1,6 @@
.cardContainer {
display: flex;
flex-wrap: wrap;
gap: 1ch;
margin: 1ch;
}

View File

@@ -0,0 +1,23 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { OutboxComponent } from './outbox.component';
describe('OutboxComponent', () => {
let component: OutboxComponent;
let fixture: ComponentFixture<OutboxComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [OutboxComponent]
})
.compileComponents();
fixture = TestBed.createComponent(OutboxComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@@ -0,0 +1,42 @@
import { Component, OnInit } from '@angular/core';
import { AdminCommService } from '../../admin-comm.service';
import { Router, ActivatedRoute } from '@angular/router';
import { ToolbarService } from '../../toolbar/toolbar.service';
import * as moment from 'moment';
@Component({
selector: 'app-outbox',
templateUrl: './outbox.component.html',
styleUrl: './outbox.component.scss'
})
export class OutboxComponent implements OnInit {
messages!: {
_id: string;
sentDate: moment.Moment;
title: string;
}[]
constructor (private readonly acs: AdminCommService, private toolbar: ToolbarService, private router: Router, private route: ActivatedRoute ) {
this.toolbar.comp = this
this.toolbar.menu = [
{ title: "Powiadomienia", fn: "goBack", icon: "arrow_back" }
]
}
goBack() {
this.router.navigate(['../'], {relativeTo: this.route})
}
ngOnInit(): void {
this.acs.notif.outbox.getSent().subscribe((v) => {
this.messages = v.map(i => {
return {
...i,
sentDate: moment(i.sentDate)
}
})
})
}
}

View File

@@ -1,4 +1,5 @@
<mat-accordion>
<!-- #region Rooms-->
<mat-expansion-panel>
<!-- TODO: Make more ergonomic -->
<mat-expansion-panel-header>
@@ -8,6 +9,8 @@
<p>Kliknij listę aby edytować</p>
<app-list-editor [converter]="usettings.rooms" (edit)="saveRoom($event)"></app-list-editor>
</mat-expansion-panel>
<!-- #endregion -->
<!-- #region Room grade reasons-->
<mat-expansion-panel>
<mat-expansion-panel-header>
<mat-panel-title>Powody nieczystości</mat-panel-title>
@@ -16,6 +19,8 @@
<p>Kliknij listę aby edytować</p>
<app-list-editor [list]="usettings.cleanThings" (edit)="saveCleanThings($event)"></app-list-editor>
</mat-expansion-panel>
<!-- #endregion -->
<!-- #region Key rooms-->
<mat-expansion-panel>
<mat-expansion-panel-header>
<mat-panel-title>Sale z kluczami</mat-panel-title>
@@ -23,6 +28,68 @@
</mat-expansion-panel-header>
<app-list-editor [list]="usettings.keyrooms" (edit)="saveKeyrooms($event)"></app-list-editor>
</mat-expansion-panel>
<!-- #endregion -->
<!-- #region Default menu items-->
<mat-expansion-panel>
<mat-expansion-panel-header>
<mat-panel-title>Domyślne wpisy jadłospisu</mat-panel-title>
<mat-panel-description></mat-panel-description>
</mat-expansion-panel-header>
<table>
<caption>Domyślne wpisy w jadłospisie dla danych pozycji</caption>
<thead>
<tr>
<th>Śniadanie</th>
<th>Kolacja</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<app-list-editor [list]="usettings.menu.defaultItems.sn" (edit)="saveSn($event)"/>
</td>
<td>
<app-list-editor [list]="usettings.menu.defaultItems.kol" (edit)="saveKol($event)"/>
</td>
</tr>
</tbody>
</table>
</mat-expansion-panel>
<!-- #endregion -->
<!-- #region Security-->
<mat-expansion-panel>
<mat-expansion-panel-header>
<mat-panel-title>Bezpieczeństwo</mat-panel-title>
</mat-expansion-panel-header>
<mat-tab-group color="accent">
<mat-tab label="Konta">
<p>
Domyślne hasło użytkownika po wygenerowaniu konto to <code>pierwszelogowanie</code><br>
Reset hasła powoduje zmianę na <code>reset</code>
</p>
<form [formGroup]="accSec" (submit)="saveAccSecTimeouts()">
<p>Ograniczenia logowania</p>
<mat-form-field color="accent">
<mat-label>Dozwolone próby logowania</mat-label>
<input matInput type="number" formControlName="attempts">
</mat-form-field><br>
<mat-form-field color="accent">
<mat-label>Okres liczenia prób</mat-label>
<input matInput type="number" formControlName="time">
<mat-hint>Podaj w minutach</mat-hint>
</mat-form-field><br>
<mat-form-field color="accent">
<mat-label>Czas blokady konta</mat-label>
<input matInput type="number" formControlName="lockout">
<mat-hint>Podaj w minutach</mat-hint>
</mat-form-field><br>
<button mat-flat-button color="accent">Zapisz</button>
</form>
</mat-tab>
</mat-tab-group>
</mat-expansion-panel>
<!-- #endregion -->
<!-- #region Program control-->
<mat-expansion-panel>
<mat-expansion-panel-header>
<mat-panel-title>Sterowanie programem</mat-panel-title>
@@ -41,4 +108,5 @@
Wyloguj wszystkich użytkowników
</button> -->
</mat-expansion-panel>
<!-- #endregion -->
</mat-accordion>

View File

@@ -1,6 +1,7 @@
import { Component, OnInit } from '@angular/core';
import { AdminCommService } from '../admin-comm.service';
import { MatSnackBar } from '@angular/material/snack-bar';
import { FormBuilder } from '@angular/forms';
@Component({
selector: 'app-settings',
@@ -11,10 +12,18 @@ export class SettingsComponent implements OnInit {
usettings!: IUSettings
reloadTimeout: boolean = false;
constructor (private readonly acu: AdminCommService, private readonly sb: MatSnackBar) { }
constructor (private readonly acu: AdminCommService, private readonly sb: MatSnackBar, private readonly fb: FormBuilder) { }
accSec = this.fb.nonNullable.group({
attempts: this.fb.nonNullable.control(1),
time: this.fb.nonNullable.control(1),
lockout: this.fb.nonNullable.control(1),
})
ngOnInit(): void {
this.acu.settings.getAll().subscribe((r) => {
this.usettings = r
this.accSecTimeouts = r.security.loginTimeout
})
}
@@ -31,10 +40,39 @@ export class SettingsComponent implements OnInit {
this.send()
}
saveSn(event: string[]) {
this.usettings.menu.defaultItems.sn = event
this.send()
}
saveKol(event: string[]) {
this.usettings.menu.defaultItems.kol = event
this.send()
}
saveAccSecTimeouts() {
this.usettings.security.loginTimeout = this.accSecTimeouts
this.send()
}
set accSecTimeouts(value: IUSettings['security']['loginTimeout']) {
this.accSec.setValue({
attempts: value.attempts,
lockout: value.lockout / 60,
time: value.time / 60
})
}
get accSecTimeouts(): IUSettings['security']['loginTimeout'] {
return {
attempts: this.accSec.controls['attempts'].value,
lockout: this.accSec.controls['lockout'].value * 60,
time: this.accSec.controls['time'].value * 60
}
}
send() {
this.acu.settings.post(this.usettings).subscribe((s) => {
if (s.status == 200) {
this.sb.open("Zapisano!", undefined, {duration: 1000})
this.sb.open("Zapisano!", undefined, { duration: 1000 })
} else {
console.error(s);
}
@@ -51,7 +89,7 @@ export class SettingsComponent implements OnInit {
}, 5000);
this.acu.settings.reload().subscribe((s) => {
if (s.status == 200) {
this.sb.open("Przeładowano ustawienia!", undefined, {duration: 3000})
this.sb.open("Przeładowano ustawienia!", undefined, { duration: 3000 })
} else {
console.error(s);
}
@@ -63,4 +101,17 @@ export interface IUSettings {
keyrooms: string[];
rooms: string[];
cleanThings: string[];
menu: {
defaultItems: {
sn: string[];
kol: string[];
}
};
security: {
loginTimeout: {
attempts: number;
time: number;
lockout: number;
}
}
}

View File

@@ -0,0 +1 @@
<span class="main"><mat-icon class="icon">arrow_upward</mat-icon><span>Wybierz zakładkę w menu</span></span>

View File

@@ -0,0 +1,13 @@
.main {
margin-top: 8px;
margin-left: 16px;
display: flex;
align-items: center;
gap: 1ch;
}
.icon {
width: fit-content;
height: fit-content;
font-size: 32pt;
}

View File

@@ -0,0 +1,23 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { StartAdminComponent } from './start.component';
describe('StartComponent', () => {
let component: StartAdminComponent;
let fixture: ComponentFixture<StartAdminComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [StartAdminComponent]
})
.compileComponents();
fixture = TestBed.createComponent(StartAdminComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@@ -0,0 +1,10 @@
import { Component } from '@angular/core';
@Component({
selector: 'app-start',
templateUrl: './start.component.html',
styleUrl: './start.component.scss'
})
export class StartAdminComponent {
}

View File

@@ -0,0 +1,14 @@
<mat-toolbar color="accent">
<button mat-icon-button (click)="drawer.toggle()"><mat-icon>menu</mat-icon></button>
<span>{{title.getTitle()}}</span>
<span style="flex: 1 1 auto"></span>
<button mat-icon-button *ngIf="toolbar.menu" [matMenuTriggerFor]="menu" (click)="openMenu()"><mat-icon>more_vert</mat-icon></button>
</mat-toolbar>
<mat-menu #menu="matMenu">
@for (item of _menu; track $index) {
<button mat-menu-item *ngIf="item.check ?? true" (click)="toolbar.comp[item.fn]()">
<mat-icon *ngIf="item.icon">{{item.icon}}</mat-icon>
<span>{{item.title}}</span>
</button>
}
</mat-menu>

View File

@@ -0,0 +1,23 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { ToolbarComponent } from './toolbar.component';
describe('ToolbarComponent', () => {
let component: ToolbarComponent;
let fixture: ComponentFixture<ToolbarComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ToolbarComponent]
})
.compileComponents();
fixture = TestBed.createComponent(ToolbarComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@@ -0,0 +1,26 @@
import { Component, Input, ViewChild } from '@angular/core';
import { MatDrawer } from '@angular/material/sidenav';
import { Title } from '@angular/platform-browser';
import { ToolbarService } from './toolbar.service';
import { MatMenuTrigger } from '@angular/material/menu';
@Component({
selector: 'app-toolbar',
templateUrl: './toolbar.component.html',
styleUrl: './toolbar.component.scss'
})
export class ToolbarComponent {
@Input() drawer!: MatDrawer;
@ViewChild(MatMenuTrigger) trigger!: MatMenuTrigger;
protected _menu?: typeof this.toolbar.menu
constructor(readonly title: Title, protected toolbar: ToolbarService) {
}
openMenu () {
this._menu = this.toolbar.menu
this.trigger.openMenu()
}
}

View File

@@ -6,9 +6,6 @@ import { Injectable } from '@angular/core';
export class ToolbarService {
public comp?: any;
public menu?: {title: string, check: boolean, icon?: string, fn: string}[]
constructor() { }
public menu?: {title: string, check?: boolean, icon?: string, fn: string}[]
}

View File

@@ -4,6 +4,6 @@ import { LocalStorageService } from './services/local-storage.service';
export const adminGuard: CanActivateChildFn = (childRoute, state) => {
const router = inject(Router)
if (inject(LocalStorageService).admin == false) return router.parseUrl('/')
if (inject(LocalStorageService).admin == undefined) return router.parseUrl('/')
return true
};

View File

@@ -19,6 +19,8 @@ import { SummaryComponent } from './admin-view/grades/summary/summary.component'
import { SettingsComponent } from './admin-view/settings/settings.component';
import { AttendenceSummaryComponent } from './admin-view/grades/attendence-summary/attendence-summary.component';
import { NotificationsComponent } from './admin-view/notifications/notifications.component';
import { OutboxComponent } from './admin-view/notifications/outbox/outbox.component';
import { StartAdminComponent } from './admin-view/start/start.component';
const routes: Routes = [
{path: "", redirectTo: "login", pathMatch: "full"},
@@ -30,10 +32,14 @@ const routes: Routes = [
{path: "grades", component: PersonalComponent, title: "Konto"}
]},
{path: "admin", component: AdminViewComponent, title: "Panel administracyjny", canActivateChild: [authGuard, adminGuard], children: [
{path: "", pathMatch: "full", component: StartAdminComponent},
{path: "news", title: "Edytowanie wiadomości", component: NewsEditComponent},
{path: "menu", title: "Edytowanie jadłospisu", component: MenuNewComponent},
{path: "accounts", title: "Użytkownicy", component: AccountMgmtComponent},
{path: "notifications", title: "Powiadomienia", component: NotificationsComponent},
{path: "notifications", children: [
{path: "", pathMatch: "full", title: "Powiadomienia", component: NotificationsComponent},
{path: "outbox", title: "Wysłane", component: OutboxComponent}
]},
{path: "groups", title: "Grupy", component: GroupsComponent},
{path: "keys", title: "Klucze", component: AdminKeyComponent},
{path: "grades", children: [

View File

@@ -6,6 +6,8 @@ import { Link } from '../types/link';
import { LocalStorageService } from '../services/local-storage.service';
import { interval } from 'rxjs';
import { MatSnackBar } from '@angular/material/snack-bar';
import { MatDialog } from '@angular/material/dialog';
import { NotifDialogComponent } from './notif-dialog/notif-dialog.component';
@Component({
selector: 'app-app-view',
@@ -25,7 +27,14 @@ export class AppViewComponent implements OnInit {
});
}
constructor (private ac: AuthClient, readonly swPush: SwPush, private us: UpdatesService, private ls: LocalStorageService, private sb: MatSnackBar) {}
constructor (
private ac: AuthClient,
readonly swPush: SwPush,
private us: UpdatesService,
private ls: LocalStorageService,
private sb: MatSnackBar,
private dialog: MatDialog
) {}
subscribeToNotif() {
if (this.swPush.isEnabled && this.ls.capCheck(4)) {
@@ -45,6 +54,13 @@ export class AppViewComponent implements OnInit {
}
newsCheck() {
if (this.ls.capCheck(4)) {
this.us.getNotifCheck().subscribe((s) => {
s.forEach(v => {
this.dialog.open(NotifDialogComponent, {data: v})
})
})
}
if (this.ls.newsflag) return;
this.us.newsCheck().subscribe((s) => {
if (s.hash != this.ls.newsCheck.hash) {

View File

@@ -13,8 +13,8 @@
<mat-card-content>
<ul>
<li *ngFor="let i of ls.defaultItems.sn">{{i}}</li>
<li *ngFor="let i of getsn.fancy">{{i.charAt(0).toUpperCase()+i.substring(1)}}</li>
<li *ngIf="getsn.second">{{getsn.second.charAt(0).toUpperCase()+getsn.second.substring(1)}}</li>
<li *ngFor="let i of getsn.fancy">{{capitalize(i)}}</li>
<li *ngIf="getsn.second">{{capitalize(getsn.second)}}</li>
</ul>
</mat-card-content>
</mat-card>
@@ -51,7 +51,7 @@
<button mat-icon-button (click)="vote('kol', '-')"><mat-icon [color]="menu!.kolv == '-' ? 'warn' : null">thumb_down</mat-icon></button>
</mat-card-actions>
</mat-card>
<mat-card *ngIf="!(getkol || getob || getsn || loading)">
<mat-card *ngIf="!(getkol || getob || getsn || loading || gettitle)">
<mat-card-content id="no-data">
Brak danych, wybierz inny dzień.
</mat-card-content>

View File

@@ -32,17 +32,34 @@ export class MenuComponent {
}
menu?: Menu;
get getsn() {return (this.menu && this.menu.sn) ? this.menu.sn : null}
get getob() {return (this.menu && this.menu.ob) ? this.menu.ob : null}
get getsn() {return (this.menu && this.checkIfAnyProperty(this.menu.sn)) ? this.menu.sn : null}
get getob() {return (this.menu && this.checkIfAnyProperty(this.menu.ob)) ? this.menu.ob : null}
get getkol() {return (this.menu && this.menu.kol) ? this.menu.kol : null}
get gettitle() {return (this.menu && this.menu.dayTitle && this.menu.dayTitle != "") ? this.menu.dayTitle : null}
private checkIfAnyProperty(obj: { [x: string]: string | string[];}) {
for (let i in obj) {
if (Array.isArray(obj[i])) {
if (obj[i].length > 0) return true
} else {
if (!!obj[i]) return true
}
}
return false
}
capitalize(str: string) {
return str.charAt(0).toUpperCase()+str.substring(1)
}
updateMenu(silent?: boolean) {
this.loading = !silent
if (!silent) this.menu = undefined
this.uc.getMenu(this.day).subscribe(m => {
this.loading = false
this.menu = m
console.log(m);
})
}

View File

@@ -9,4 +9,9 @@
<mat-card-footer>
<p>{{item.date | date:'d-LL-yyyy HH:mm'}}</p>
</mat-card-footer>
</mat-card>
<mat-card *ngIf="news.length == 0">
<p>
Brak wiadomości.
</p>
</mat-card>

View File

@@ -29,3 +29,7 @@ mat-card-footer p {
mat-card-content p {
white-space: pre-line;
}
mat-card p {
margin: 15px;
}

View File

@@ -0,0 +1,10 @@
<h1 mat-dialog-title>{{data.message.title}}</h1>
<mat-dialog-content>
<p>
{{data.message.body}}
</p>
<div>{{data.sentDate.format("[Wysłano] dddd DD MMMM YYYYr. o HH:mm")}}</div>
</mat-dialog-content>
<mat-dialog-actions align="end">
<button mat-raised-button color="primary" (click)="ack()">Odczytano</button>
</mat-dialog-actions>

View File

@@ -0,0 +1,23 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { NotifDialogComponent } from './notif-dialog.component';
describe('NotifDialogComponent', () => {
let component: NotifDialogComponent;
let fixture: ComponentFixture<NotifDialogComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [NotifDialogComponent]
})
.compileComponents();
fixture = TestBed.createComponent(NotifDialogComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@@ -0,0 +1,27 @@
import { Component, Inject } from '@angular/core';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import * as moment from 'moment';
import { UpdatesService } from 'src/app/services/updates.service';
@Component({
selector: 'app-notif-dialog',
templateUrl: './notif-dialog.component.html',
styleUrl: './notif-dialog.component.scss'
})
export class NotifDialogComponent {
constructor (
@Inject(MAT_DIALOG_DATA) public data: {_id: string, message: {title: string, body: string}, sentDate: moment.Moment},
public dialogRef: MatDialogRef<NotifDialogComponent>,
private uc: UpdatesService
) {
data.sentDate = moment(data.sentDate)
}
ack () {
this.uc.postInfoAck(this.data._id).subscribe((v) => {
this.dialogRef.close()
})
}
}

View File

@@ -0,0 +1,14 @@
<h1 mat-dialog-title>Dodatkowe ustawienia</h1>
<mat-dialog-content>
<mat-action-list>
@for (link of LINKS; track link) {
<button mat-list-item (click)="open(link.component)">
<mat-icon matListItemIcon *ngIf="link.icon">{{link.icon}}</mat-icon>
<div matListItemTitle>{{link.title}}</div>
</button>
}
</mat-action-list>
</mat-dialog-content>
<mat-dialog-actions align="end">
<button mat-dialog-close mat-button>Zamknij</button>
</mat-dialog-actions>

View File

@@ -0,0 +1,23 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { ExtraComponent } from './extra.component';
describe('ExtraComponent', () => {
let component: ExtraComponent;
let fixture: ComponentFixture<ExtraComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ExtraComponent]
})
.compileComponents();
fixture = TestBed.createComponent(ExtraComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@@ -0,0 +1,29 @@
import { ComponentType } from '@angular/cdk/portal';
import { Component } from '@angular/core';
import { Link } from 'src/app/types/link';
import { RedirectComponent } from './redirect/redirect.component';
import { MatDialog } from '@angular/material/dialog';
@Component({
selector: 'app-extra',
templateUrl: './extra.component.html',
styleUrl: './extra.component.scss'
})
export class ExtraComponent {
constructor (private dialog: MatDialog) {}
private readonly _LINKS: (Omit<Link, "href"> & {component: ComponentType<any>})[] = [
{ title: "Domyślna strona po logowaniu", component: RedirectComponent, enabled: true, icon: "home" }
]
public get LINKS() {
return this._LINKS.filter((v) => {
return v.enabled
});
}
open(component: ComponentType<any>) {
this.dialog.open(component)
}
}

View File

@@ -0,0 +1,14 @@
<h1 mat-dialog-title>Domyślna strona po logowaniu</h1>
<mat-dialog-content>
<p>Wpisz link względem /ipwa/ w poniższym polu.</p>
<p>Przykład: /app/menu</p>
<p style="color: red">Jeśli nie wiesz co tu wpisać, najlepiej nie zmieniaj tego ustawienia</p>
<mat-form-field>
<input matInput type="text" [(ngModel)]="redirect">
<mat-label>Link</mat-label>
</mat-form-field>
</mat-dialog-content>
<mat-dialog-actions align="end">
<button mat-dialog-close mat-button>Anuluj</button>
<button (click)="save()" mat-flat-button>Zapisz</button>
</mat-dialog-actions>

View File

@@ -0,0 +1,23 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { RedirectComponent } from './redirect.component';
describe('RedirectComponent', () => {
let component: RedirectComponent;
let fixture: ComponentFixture<RedirectComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [RedirectComponent]
})
.compileComponents();
fixture = TestBed.createComponent(RedirectComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@@ -0,0 +1,20 @@
import { Component } from '@angular/core';
import { MatDialogRef } from '@angular/material/dialog';
import { AuthClient } from 'src/app/services/auth.client';
@Component({
selector: 'app-redirect',
templateUrl: './redirect.component.html',
styleUrl: './redirect.component.scss'
})
export class RedirectComponent {
protected redirect = ""
constructor (public dialogRef: MatDialogRef<RedirectComponent>, private ac: AuthClient) {
this.redirect = ac.redirect
}
protected save() {
this.ac.redirect = this.redirect
this.dialogRef.close()
}
}

View File

@@ -30,6 +30,10 @@
<div matListItemTitle>Panel administracyjny</div>
<div matListItemLine>Poprzednio Tryb edycji</div>
</button>
<button mat-list-item (click)="openExtra()">
<mat-icon matListItemIcon>settings_applications</mat-icon>
<div matListItemTitle>Dodatkowe ustawienia</div>
</button>
<button mat-list-item (click)="openAbout()">
<mat-icon matListItemIcon>info</mat-icon>
<div matListItemTitle>O programie</div>

View File

@@ -10,6 +10,7 @@ import { LocalStorageService } from 'src/app/services/local-storage.service';
import { KeyComponent } from './key/key.component';
import { CleanComponent } from './clean/clean.component';
import { AboutComponent } from './about/about.component';
import { ExtraComponent } from './extra/extra.component';
@Component({
selector: 'app-personal',
@@ -63,6 +64,10 @@ export class PersonalComponent {
this.ac.check()
}
protected openExtra() {
this.dialog.open(ExtraComponent)
}
protected openAbout() {
this.dialog.open(AboutComponent)
}

View File

@@ -78,6 +78,15 @@ import { AttendenceComponent } from './admin-view/grades/attendence/attendence.c
import { AttendenceSummaryComponent } from './admin-view/grades/attendence-summary/attendence-summary.component';
import { HourDisplayComponent } from './admin-view/grades/attendence-summary/hour-display/hour-display.component';
import { AboutComponent } from './app-view/personal/about/about.component';
import { environment } from 'src/environments/environment';
import { ExtraComponent } from './app-view/personal/extra/extra.component';
import { RedirectComponent } from './app-view/personal/extra/redirect/redirect.component';
import { OutboxComponent } from './admin-view/notifications/outbox/outbox.component';
import { ToolbarComponent } from './admin-view/toolbar/toolbar.component';
import { MessageComponent } from './admin-view/notifications/outbox/message/message.component';
import { NotifDialogComponent } from './app-view/notif-dialog/notif-dialog.component';
import { UserSearchComponent } from './commonComponents/user-search/user-search.component';
import { StartAdminComponent } from './admin-view/start/start.component';
@NgModule({
declarations: [
@@ -121,6 +130,14 @@ import { AboutComponent } from './app-view/personal/about/about.component';
AttendenceSummaryComponent,
HourDisplayComponent,
AboutComponent,
ExtraComponent,
RedirectComponent,
OutboxComponent,
ToolbarComponent,
MessageComponent,
NotifDialogComponent,
UserSearchComponent,
StartAdminComponent,
],
imports: [
BrowserModule,
@@ -160,7 +177,7 @@ import { AboutComponent } from './app-view/personal/about/about.component';
A11yModule,
MatAutocompleteModule,
ServiceWorkerModule.register('ngsw-worker.js', {
enabled: !isDevMode(),
enabled: environment.production,
// Register the ServiceWorker as soon as the application is stable
// or after 30 seconds (whichever comes first).
registrationStrategy: 'registerWhenStable:30000'

View File

@@ -0,0 +1,15 @@
<div role="group" class="app-user-search-container" (focusin)="onFocusIn($event)" (focusout)="onFocusOut($event)">
<input type="text" [matAutocomplete]="ac" [formControl]="control" #inputComponent class="input-element">
<mat-spinner color="accent" diameter="16" *ngIf="loading" matSuffix></mat-spinner>
<mat-autocomplete #ac="matAutocomplete" autoActiveFirstOption (optionSelected)="saveValue($event)" [displayWith]="displayFn">
@for (item of list; track $index) {
<mat-option [value]="item">
@if (item.fname) {
{{item.fname}} {{item.surname}} <span *ngIf="item.room" class="room">({{item.room}})</span>
} @else {
{{item.uname}}
}
</mat-option>
}
</mat-autocomplete>
</div>

View File

@@ -0,0 +1,18 @@
:host {
display: flex;
align-items: center;
gap: 1ch;
}
.room {
color: gray;
}
input {
border: none;
background: none;
padding: 0;
outline: 0;
font: inherit;
color: currentColor;
}

View File

@@ -0,0 +1,23 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { UserSearchComponent } from './user-search.component';
describe('UserSearchComponent', () => {
let component: UserSearchComponent;
let fixture: ComponentFixture<UserSearchComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [UserSearchComponent]
})
.compileComponents();
fixture = TestBed.createComponent(UserSearchComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@@ -0,0 +1,193 @@
import { BooleanInput, coerceBooleanProperty } from '@angular/cdk/coercion';
import { Component, DoCheck, ElementRef, HostBinding, Input, OnDestroy, Optional, Self } from '@angular/core';
import { ControlValueAccessor, FormControl, FormGroupDirective, NgControl, NgForm } from '@angular/forms';
import { MatAutocompleteSelectedEvent } from '@angular/material/autocomplete';
import { MatFormFieldControl } from '@angular/material/form-field';
import { Subject } from 'rxjs';
import { AdminCommService } from 'src/app/admin-view/admin-comm.service';
export interface UserSearchResult {
_id: string;
fname: string;
surname: string;
uname: string;
room: string;
}
@Component({
selector: 'app-user-search',
templateUrl: './user-search.component.html',
styleUrl: './user-search.component.scss',
providers: [
{
provide: MatFormFieldControl,
useExisting: UserSearchComponent
}
],
host: {
'(blur)': '_onTouched()'
}
})
export class UserSearchComponent implements ControlValueAccessor, MatFormFieldControl<UserSearchResult>, OnDestroy, DoCheck {
protected loading: boolean = false
control: FormControl = new FormControl();
protected list: UserSearchResult[] = []
private timeout?: NodeJS.Timeout
private _onChange!: (_: UserSearchResult) => void
private _onTouched!: any
static nextId = 0;
@Input()
public get value(): UserSearchResult | null {
return this.control.value;
}
public set value(value: UserSearchResult | null) {
this.control.setValue(value)
this.stateChanges.next()
}
touched = false
stateChanges = new Subject<void>();
@HostBinding() id: string = `app-user-search-${UserSearchComponent.nextId++}`;
private _placeholder: string = "";
@Input()
public get placeholder(): string {
return this._placeholder;
}
public set placeholder(value: string) {
this._placeholder = value;
this.stateChanges.next()
}
focused: boolean = false;
onFocusIn(event: FocusEvent) {
if (!this.focused) {
this.focused = true;
this.stateChanges.next();
}
}
onFocusOut(event: FocusEvent) {
if (!this._elementRef.nativeElement.contains(event.relatedTarget as Element)) {
this.touched = true
this.focused = false;
this._onTouched();
this.stateChanges.next();
}
}
get empty(): boolean {
return !this.control.value
}
@HostBinding('class.floating')
get shouldLabelFloat(): boolean {
return this.focused || !this.empty
}
private _required: boolean = false;
@Input()
public get required(): boolean {
return this._required;
}
public set required(value: BooleanInput) {
this._required = coerceBooleanProperty(value);
this.stateChanges.next()
}
private _disabled: boolean = false;
@Input()
public get disabled(): boolean {
return this._disabled;
}
public set disabled(value: BooleanInput) {
this._disabled = coerceBooleanProperty(value);
this._disabled ? this.control.disable() : this.control.enable()
this.stateChanges.next()
}
errorState: boolean = false
controlType?: string | undefined = "app-user-search";
autofilled?: boolean | undefined;
@Input('aria-describedby') userAriaDescribedBy?: string;
setDescribedByIds(ids: string[]): void {
const controlElement = this._elementRef.nativeElement.querySelector('.app-user-search-container')!;
controlElement.setAttribute('aria-describedby', ids.join(' '))
}
onContainerClick(event: MouseEvent): void {
if ((event.target as Element).tagName.toLowerCase() != 'input') {
this._elementRef.nativeElement.querySelector('input').focus()
}
}
constructor(
readonly acu: AdminCommService,
@Optional() @Self() public ngControl: NgControl,
@Optional() private _parentForm: NgForm,
@Optional() private _parentFormGroup: FormGroupDirective,
private _elementRef: ElementRef
) {
if (this.ngControl != null) {
(this.ngControl as NgControl).valueAccessor = this
}
this.control.valueChanges.subscribe(() => {
if (typeof this.control.value == "object") return;
this.loading = true
if (this.timeout) clearTimeout(this.timeout)
this.timeout = setTimeout(() => {
this.acu.userFilter(this.control.value).subscribe(v => {
this.list = v
this.loading = false
})
}, 500)
})
}
ngDoCheck(): void {
if (this.ngControl) {
this.updateErrorState()
}
}
private updateErrorState() {
const parent = this._parentFormGroup || this._parentForm
const oldState = this.errorState;
const newState = (this.ngControl?.invalid || this.control.invalid) && (this.touched || parent.submitted);
if (oldState !== newState) {
this.errorState = newState
this.stateChanges.next()
}
}
ngOnDestroy(): void {
this.stateChanges.complete()
}
writeValue(obj: UserSearchResult): void {
this.value = obj
}
registerOnChange(fn: (_: UserSearchResult) => void): void {
this._onChange = fn
}
registerOnTouched(fn: any): void {
this._onTouched = fn
}
setDisabledState?(isDisabled: boolean): void {
this.disabled = isDisabled
}
protected displayFn(u: UserSearchResult): string {
if (!u) return ''
return u.fname ? `${u.fname} ${u.surname}` : u.uname
}
protected saveValue(e: MatAutocompleteSelectedEvent) {
this.autofilled = true
this.value = e.option.value
this._onChange(this.value!)
}
}

View File

@@ -22,30 +22,18 @@ export class LoginComponent implements OnInit {
ngOnInit() {
if (this.ls.loggedIn) {
this.router.navigateByUrl('app')
}
}
errorParser(err: any) {
switch (err.status) {
case 401:
this.error = "Zła nazwa użytkownika lub hasło"
break;
default:
this.error = "Nieznany błąd"
break;
this.router.navigateByUrl(this.ac.redirect || 'app')
}
}
submit() {
const val = this.form.value
this.ac.login(val.uname, val.pass).pipe(catchError((err,caught)=>{
this.errorParser(err)
this.error = err.error.message
return throwError(() => new Error(err.message))
})).subscribe((data) => {
this.ls.loggedIn = true
this.router.navigateByUrl('app')
this.router.navigateByUrl(this.ac.redirect || 'app')
if (data.admin) {
this.ls.admin = data.admin
}

View File

@@ -8,7 +8,21 @@ import { catchError, concat, first, from, interval, tap, throwError } from 'rxjs
})
export class AppUpdateService implements OnInit {
constructor(readonly appRef: ApplicationRef, readonly update: SwUpdate, readonly sb: MatSnackBar) { }
constructor(readonly appRef: ApplicationRef, readonly update: SwUpdate, readonly sb: MatSnackBar) {
this.update.versionUpdates.subscribe((evt) => {
switch (evt.type) {
case 'VERSION_DETECTED':
console.log(`Downloading ${evt.version.hash}`);
break;
case 'VERSION_READY':
console.log(`Current: ${evt.currentVersion.hash}, new: ${evt.latestVersion.hash}`);
break;
case 'VERSION_INSTALLATION_FAILED':
console.error(`Failed to install ${evt.version.hash}: ${evt.error}`);
break;
}
})
}
ngOnInit(): void {
const appIsStable = this.appRef.isStable.pipe(first(isStable => isStable === true))

View File

@@ -1,7 +1,7 @@
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { catchError, EMPTY, throwError } from 'rxjs';
import { catchError, EMPTY, tap, throwError } from 'rxjs';
import { environment } from 'src/environments/environment';
import { LocalStorageService } from './local-storage.service';
import { Status } from '../types/status';
@@ -12,11 +12,22 @@ import { Status } from '../types/status';
export class AuthClient {
constructor(private http: HttpClient, private router: Router, private ls: LocalStorageService) { }
private _redirect: string = "";
public get redirect(): string {
return this._redirect;
}
public set redirect(value: string) {
this._redirect = value;
this.putRedirect(value).subscribe()
}
public login(uname: string, pass: string) {
return this.http.post<any>(environment.apiEndpoint + '/auth/login', {
return this.http.post<Status & {admin: number, redirect: string}>(environment.apiEndpoint + '/auth/login', {
username: uname,
password: pass
}, {withCredentials: true})
}, {withCredentials: true}).pipe(tap((v) => {
if (v.redirect) this._redirect = v.redirect
}))
}
public logout() {
@@ -24,15 +35,26 @@ export class AuthClient {
}
public check() {
this.http.get(environment.apiEndpoint + '/auth/check', {withCredentials: true}).pipe(catchError((err) => {
this.http.get<{
admin?: number,
room?: string,
features: number,
menu: {
defaultItems: {
sn: string[];
kol: string[];
}
},
vapid: string
}>(environment.apiEndpoint + '/auth/check', {withCredentials: true}).pipe(catchError((err) => {
if (err.status == 401 && this.ls.loggedIn) {
this.ls.logOut()
this.router.navigateByUrl("/login")
return EMPTY
}
return throwError(() => new Error(err.message))
})).subscribe((data: any)=>{
if (data.admin) { this.ls.admin = data.admin } else { this.ls.admin = false }
})).subscribe((data)=>{
this.ls.admin = data.admin
if (this.ls.capFlag != data.features) {
this.ls.capFlag = data.features
document.location.reload()
@@ -48,4 +70,8 @@ export class AuthClient {
public chpass(oldpass:string,newpass:string) {
return this.http.post(environment.apiEndpoint + '/auth/chpass', {"oldPass": oldpass, "newPass": newpass}, {withCredentials: true, responseType: "text"})
}
private putRedirect(redirect: string) {
return this.http.put<Status>(environment.apiEndpoint + '/auth/redirect', {redirect: redirect}, {withCredentials: true})
}
}

View File

@@ -13,8 +13,8 @@ export class LocalStorageService {
}
logOut() {
this.loggedIn = false
this.admin = false
this.loggedIn = undefined
this.admin = undefined
}
public hasRoom() {
@@ -26,11 +26,11 @@ export class LocalStorageService {
}
get room() {
return localStorage.getItem('room')!
return localStorage.getItem('room') ?? undefined
}
set room(value: string) {
if (value == "") {
set room(value: string | undefined) {
if (!value) {
localStorage.removeItem('room')
} else {
localStorage.setItem('room', value)
@@ -49,10 +49,10 @@ export class LocalStorageService {
if (localStorage.getItem("loggedIn")) {
return true
}
return false
return
}
set loggedIn(is: boolean) {
set loggedIn(is: true | undefined) {
if (is) {
localStorage.setItem("loggedIn", "true")
} else {
@@ -60,7 +60,7 @@ export class LocalStorageService {
}
}
set admin(newInt: number | false) {
set admin(newInt: number | undefined) {
if (newInt) {
localStorage.setItem("admin", newInt.toString())
} else {
@@ -70,7 +70,7 @@ export class LocalStorageService {
get admin() {
var lsa = localStorage.getItem("admin")
return lsa ? Number.parseInt(lsa) : false
return lsa ? Number.parseInt(lsa) : undefined
}
set amgreg(toggle: boolean) {

View File

@@ -7,6 +7,7 @@ import * as moment from 'moment';
import { map } from 'rxjs';
import { UKey } from '../types/key';
import { CleanNote } from '../types/clean-note';
import { Status } from '../types/status';
@Injectable({
providedIn: 'root'
@@ -55,4 +56,12 @@ export class UpdatesService {
getClean(date: moment.Moment) {
return this.http.get<{grade: number, notes: CleanNote[], tips: string}>(environment.apiEndpoint+`/app/clean/${date.toISOString()}`, {withCredentials: true})
}
getNotifCheck() {
return this.http.get<{_id: string, message: {title: string, body: string}, sentDate: moment.Moment}[]>(environment.apiEndpoint+`/app/notif/check`, {withCredentials: true})
}
postInfoAck(id: string) {
return this.http.post<Status>(environment.apiEndpoint+`/app/notif/${id}/ack`, undefined, {withCredentials: true})
}
}

View File

@@ -3,11 +3,11 @@ import { Moment } from "moment";
export interface Menu {
_id: string;
day: Moment;
sn?: {
sn: {
fancy: string[];
second: string;
};
ob?: {
ob: {
soup: string;
vege: string;
meal: string;

View File

@@ -2,7 +2,7 @@ export interface Notification {
body: string;
title: string;
recp: {
uname: string | null;
uid: string | null;
room: string | null;
type: "all" | "room" | "uname"
}

View File

@@ -1,3 +1,4 @@
export interface Status {
status: number
status: number,
message?: string
}

View File

@@ -1,3 +1,5 @@
import { Moment } from "moment";
export default interface User {
_id: string;
uname: string;
@@ -8,4 +10,6 @@ export default interface User {
fname?: string;
surname?: string;
groups: string[];
regDate: Moment;
defaultPage?: string;
}

View File

@@ -0,0 +1,5 @@
export const environment = {
apiEndpoint: `http://localhost:12230`,
version: "testing (swDev)",
production: true
};

View File

@@ -1,5 +1,5 @@
export const environment = {
apiEndpoint: `${window.location.origin}/api`,
version: "v1.0.1",
version: "v1.1.0",
production: true
};