53 Commits

Author SHA1 Message Date
9093ba48b7 fix: spinner color 2025-06-15 11:42:39 +02:00
4c7639ee4c fix: Remade menu editor loading logic 2025-06-15 11:41:02 +02:00
2a117262df fix: changed dateselector and filter logic 2025-06-14 20:03:13 +02:00
4007dff254 feat: Added grade color directive 2025-06-14 11:02:41 +02:00
3b3f4fd3b1 fix: News now display author 2025-06-13 16:07:23 +02:00
5cd31a4981 fix: Remade perms 2025-06-13 15:11:57 +02:00
14f355df53 fix: acc state 2025-06-13 12:24:05 +02:00
4aedf3a8c3 fix: from 1.1.1-1 2025-06-12 12:25:02 +02:00
b7f2f35acb Merge pull request #22 from Slasherss1/1.1.1-1
fix: User delete button was unbound
2025-06-12 12:14:21 +02:00
86fdb8366e fix: User delete button was unbound 2025-06-12 12:12:36 +02:00
918f3f34f7 fix: post now sends created user object in response 2025-06-12 12:05:04 +02:00
003ff86d18 fix: Remade accmgmt comm 2025-06-12 11:53:14 +02:00
620717a534 fix: Debounce operator instead of manual timeouts. 2025-06-12 00:03:02 +02:00
198a614453 fix: httpclient in all admin specs 2025-06-11 22:06:49 +02:00
65fce617b1 fix: removed deprecated links 2025-06-11 22:06:02 +02:00
c9f319ccfe fix: tests disabled for now 2025-06-11 14:16:07 +02:00
5a6f036cb7 fix: Split admin comm service into multiple services 2025-06-11 14:11:14 +02:00
7fedaf09dc fix: Fixed app update test 2025-06-11 12:41:26 +02:00
a25a90c0d7 feat: Added file formatting 2025-06-11 11:56:39 +02:00
772fc52cf6 fix: Made news hide icon red when hidden. 2025-06-11 11:50:10 +02:00
2601396961 fix: removed all mentions of momentjs 2025-06-11 11:12:05 +02:00
76de91349d feat: Completed migration from moment to luxon 2025-06-09 21:52:20 +02:00
8ad18e8670 fix: hour display luxon 2025-06-09 14:47:53 +02:00
bd7d669e4b feat: Added luxon package 2025-06-09 14:36:43 +02:00
df8bc97f5b chore: version numbers 2025-06-09 14:22:05 +02:00
06e2f7fc0a fix: material 20 2025-06-09 14:14:22 +02:00
0e2e61ac34 fix: ng update core 20 2025-06-09 14:12:21 +02:00
5781f4ba61 fix: styles 2025-06-09 14:06:25 +02:00
c74e80721a fix: ng update core 19 2025-06-09 13:37:06 +02:00
f9d133a7db fix: material 18 2025-06-09 13:32:42 +02:00
7e4f10c1af fix: ng update core 2025-06-09 13:14:29 +02:00
46f351ec5b Merge pull request #21 from Slasherss1/1.1.1
v1.1.1
2025-06-06 10:08:21 +02:00
06c88cd920 chore: version numbers 2025-06-06 10:07:18 +02:00
00e79e5f4d feat: Added a link to documentation in admin panel 2025-06-04 19:26:26 +02:00
c525dfe1c1 fix: Fixed test units 2025-06-04 16:24:18 +02:00
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
6ab3598d38 v1.0.1 (#16)
* fix: Moved user type to a separate file. fix #7, fix #8

* fix: added more filters

* fix: Added attendence clear button and notes. fix #9, fix #10

* fix: bumped version number

* fix: Changed wording. Resolves #12

* fix: Resolve #13

* fix: Safari no longer displays system ui over lower guide.

* fix: Resolved #14
2025-05-13 19:28:21 +02:00
244 changed files with 11248 additions and 11635 deletions

8
.prettierignore Normal file
View File

@@ -0,0 +1,8 @@
angular.json
compose.yml
*.md
tsconfig*.json
*.html
.vscode
package*.json
ngsw-config.json

6
.prettierrc Normal file
View File

@@ -0,0 +1,6 @@
{
"arrowParens": "avoid",
"semi": false,
"trailingComma": "es5",
"bracketSpacing": true
}

View File

@@ -8,7 +8,7 @@ FROM httpd:alpine AS runtime
RUN apk add --no-cache certbot certbot-apache RUN apk add --no-cache certbot certbot-apache
COPY httpd.conf /usr/local/apache2/conf/httpd.conf COPY httpd.conf /usr/local/apache2/conf/httpd.conf
COPY cli.ini /etc/letsencrypt/cli.ini COPY cli.ini /etc/letsencrypt/cli.ini
COPY --from=build /build/dist /usr/local/apache2/htdocs/ COPY --from=build /build/dist/ipwa/browser /usr/local/apache2/htdocs/ipwa
COPY <<EOF /usr/local/apache2/htdocs/ipwa/.htaccess COPY <<EOF /usr/local/apache2/htdocs/ipwa/.htaccess
RewriteEngine on RewriteEngine on
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR] RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]

View File

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

View File

@@ -16,13 +16,15 @@
"prefix": "app", "prefix": "app",
"architect": { "architect": {
"build": { "build": {
"builder": "@angular-devkit/build-angular:browser", "builder": "@angular/build:application",
"options": { "options": {
"outputPath": "dist/ipwa", "outputPath": {
"base": "dist/ipwa"
},
"index": "src/index.html", "index": "src/index.html",
"main": "src/main.ts",
"polyfills": [ "polyfills": [
"zone.js" "zone.js",
"@angular/localize/init"
], ],
"tsConfig": "tsconfig.app.json", "tsConfig": "tsconfig.app.json",
"inlineStyleLanguage": "scss", "inlineStyleLanguage": "scss",
@@ -35,11 +37,11 @@
"src/styles.scss" "src/styles.scss"
], ],
"scripts": [], "scripts": [],
"serviceWorker": true, "serviceWorker": "ngsw-config.json",
"ngswConfigPath": "ngsw-config.json",
"allowedCommonJsDependencies": [ "allowedCommonJsDependencies": [
"moment" "moment"
] ],
"browser": "src/main.ts"
}, },
"configurations": { "configurations": {
"production": { "production": {
@@ -58,9 +60,7 @@
"outputHashing": "all" "outputHashing": "all"
}, },
"development": { "development": {
"buildOptimizer": false,
"optimization": false, "optimization": false,
"vendorChunk": true,
"extractLicenses": false, "extractLicenses": false,
"sourceMap": true, "sourceMap": true,
"namedChunks": true, "namedChunks": true,
@@ -70,12 +70,34 @@
"with": "src/environments/environment.development.ts" "with": "src/environments/environment.development.ts"
} }
] ]
},
"swDevelopment": {
"optimization": false,
"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" "defaultConfiguration": "production"
}, },
"serve": { "serve": {
"builder": "@angular-devkit/build-angular:dev-server", "builder": "@angular/build:dev-server",
"configurations": { "configurations": {
"production": { "production": {
"buildTarget": "ipwa:build:production" "buildTarget": "ipwa:build:production"
@@ -86,22 +108,23 @@
}, },
"options": { "options": {
"servePath": "/ipwa/", "servePath": "/ipwa/",
"open": true "open": false
}, },
"defaultConfiguration": "development" "defaultConfiguration": "development"
}, },
"extract-i18n": { "extract-i18n": {
"builder": "@angular-devkit/build-angular:extract-i18n", "builder": "@angular/build:extract-i18n",
"options": { "options": {
"buildTarget": "ipwa:build" "buildTarget": "ipwa:build"
} }
}, },
"test": { "test": {
"builder": "@angular-devkit/build-angular:karma", "builder": "@angular/build:karma",
"options": { "options": {
"polyfills": [ "polyfills": [
"zone.js", "zone.js",
"zone.js/testing" "zone.js/testing",
"@angular/localize/init"
], ],
"tsConfig": "tsconfig.spec.json", "tsConfig": "tsconfig.spec.json",
"inlineStyleLanguage": "scss", "inlineStyleLanguage": "scss",
@@ -116,7 +139,36 @@
"scripts": [] "scripts": []
} }
} }
},
"i18n": {
"sourceLocale": "pl"
} }
} }
},
"schematics": {
"@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,16 +1,16 @@
{ {
"$schema": "./node_modules/@angular/service-worker/config/schema.json", "$schema": "./node_modules/@angular/service-worker/config/schema.json",
"index": "./index.html", "index": "/ipwa/index.html",
"assetGroups": [ "assetGroups": [
{ {
"name": "app", "name": "app",
"installMode": "prefetch", "installMode": "prefetch",
"resources": { "resources": {
"files": [ "files": [
"/favicon.ico", "/ipwa/favicon.ico",
"/manifest.webmanifest", "/ipwa/manifest.webmanifest",
"/*.css", "/ipwa/*.css",
"/*.js" "/ipwa/*.js"
] ]
} }
}, },
@@ -20,8 +20,8 @@
"updateMode": "prefetch", "updateMode": "prefetch",
"resources": { "resources": {
"files": [ "files": [
"./assets/**", "/ipwa/assets/**",
"/**/*.(svg|cur|jpg|jpeg|png|apng|webp|avif|gif|otf|ttf|woff|woff2)" "/ipwa/**/*.(svg|cur|jpg|jpeg|png|apng|webp|avif|gif|otf|ttf|woff|woff2)"
] ]
} }
} }

12703
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,6 @@
{ {
"name": "ipwa", "name": "ipwa",
"version": "1.0.0", "version": "1.2.0",
"license": "GPL-3.0-or-later", "license": "GPL-3.0-or-later",
"scripts": { "scripts": {
"ng": "ng", "ng": "ng",
@@ -12,35 +12,38 @@
}, },
"private": true, "private": true,
"dependencies": { "dependencies": {
"@angular/animations": "^17.3.2", "@angular/animations": "^20.0.2",
"@angular/cdk": "^17.3.2", "@angular/cdk": "^20.0.2",
"@angular/cli": "^17.3.2", "@angular/cli": "^20.0.1",
"@angular/common": "^17.3.2", "@angular/common": "^20.0.2",
"@angular/compiler": "^17.3.2", "@angular/compiler": "^20.0.2",
"@angular/core": "^17.3.2", "@angular/core": "^20.0.2",
"@angular/forms": "^17.3.2", "@angular/forms": "^20.0.2",
"@angular/material": "^17.3.2", "@angular/material": "^20.0.2",
"@angular/material-moment-adapter": "^17.3.2", "@angular/material-luxon-adapter": "^20.0.2",
"@angular/platform-browser": "^17.3.2", "@angular/platform-browser": "^20.0.2",
"@angular/platform-browser-dynamic": "^17.3.2", "@angular/platform-browser-dynamic": "^20.0.2",
"@angular/router": "^17.3.2", "@angular/router": "^20.0.2",
"@angular/service-worker": "^17.3.2", "@angular/service-worker": "^20.0.2",
"luxon": "^3.6.1",
"marked": "^12.0.1", "marked": "^12.0.1",
"moment": "^2.29.4",
"rxjs": "~7.5.0", "rxjs": "~7.5.0",
"tslib": "^2.3.0", "tslib": "^2.3.0",
"zone.js": "~0.14.4" "zone.js": "~0.15.1"
}, },
"devDependencies": { "devDependencies": {
"@angular-devkit/build-angular": "^17.3.2", "@angular/build": "^20.0.1",
"@angular/compiler-cli": "^17.3.2", "@angular/compiler-cli": "^20.0.2",
"@angular/localize": "^20.0.2",
"@types/jasmine": "~4.3.0", "@types/jasmine": "~4.3.0",
"@types/luxon": "^3.6.2",
"jasmine-core": "~4.5.0", "jasmine-core": "~4.5.0",
"karma": "~6.4.0", "karma": "~6.4.0",
"karma-chrome-launcher": "~3.1.0", "karma-chrome-launcher": "~3.1.0",
"karma-coverage": "~2.2.0", "karma-coverage": "~2.2.0",
"karma-jasmine": "~5.1.0", "karma-jasmine": "~5.1.0",
"karma-jasmine-html-reporter": "~2.0.0", "karma-jasmine-html-reporter": "~2.0.0",
"typescript": "~5.4.3" "prettier": "3.5.3",
"typescript": "~5.8.3"
} }
} }

View File

@@ -1,43 +1,39 @@
<div id="upper-bar"> <div id="upper-bar">
<mat-form-field> <mat-form-field subscriptSizing="dynamic">
<mat-label>Wyszukaj</mat-label> <mat-label>Wyszukaj</mat-label>
<input matInput (keyup)="filter($event)"> <input matInput (keyup)="filter($event)">
</mat-form-field> </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> </div>
<mat-spinner *ngIf="loading"></mat-spinner> <div class="mainc">
<table mat-table [dataSource]="users"> @if (ac.state() != STATE.LOADED) {
<app-load-shade [state]="ac.state()" [error]="ac.error()" (refresh)="ac.refresh()"/>
}
<table mat-table [dataSource]="users">
<div matColumnDef="name"> <div matColumnDef="name">
<th mat-header-cell *matHeaderCellDef>Imię</th> <th mat-header-cell *matHeaderCellDef>Imię</th>
<td mat-cell *matCellDef="let element">{{element.fname}}</td> <td mat-cell *matCellDef="let element">{{element.fname}}</td>
</div> </div>
<div matColumnDef="surname"> <div matColumnDef="surname">
<th mat-header-cell *matHeaderCellDef>Nazwisko</th> <th mat-header-cell *matHeaderCellDef>Nazwisko</th>
<td mat-cell *matCellDef="let element">{{element.surname}}</td> <td mat-cell *matCellDef="let element">{{element.surname}}</td>
</div> </div>
<div matColumnDef="room"> <div matColumnDef="room">
<th mat-header-cell *matHeaderCellDef>Pokój</th> <th mat-header-cell *matHeaderCellDef>Pokój</th>
<td mat-cell *matCellDef="let element">{{element.room}}</td> <td mat-cell *matCellDef="let element">{{element.room}}</td>
</div> </div>
<div matColumnDef="uname"> <div matColumnDef="uname">
<th mat-header-cell *matHeaderCellDef>Nazwa użytkownika</th> <th mat-header-cell *matHeaderCellDef>Nazwa użytkownika</th>
<td mat-cell *matCellDef="let element">{{element.uname}}</td> <td mat-cell *matCellDef="let element">{{element.uname}}</td>
</div> </div>
<div matColumnDef="actions"> <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"> <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)="openUserCard(element._id)"><mat-icon>manage_accounts</mat-icon></button>
<button mat-mini-fab (click)="edit(element)"><mat-icon>edit</mat-icon></button> </td>
<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>
</td>
</div> </div>
<tr mat-header-row *matHeaderRowDef="collumns"></tr> <tr mat-header-row *matHeaderRowDef="collumns"></tr>
<tr mat-row *matRowDef="let row; columns: collumns"></tr> <tr mat-row *matRowDef="let row; columns: collumns"></tr>
</table> </table>
<mat-paginator pageSize="9" [pageSizeOptions]="[9, 15, 20, 50, 160]"></mat-paginator> <mat-paginator pageSize="9" [pageSizeOptions]="[9, 15, 20, 50, 160]"></mat-paginator>
</div>

View File

@@ -1,23 +1,30 @@
:host { :host {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
height: 100%; height: 100%;
}
.mainc {
position: relative;
height: 100%;
display: flex;
flex-direction: column;
} }
mat-paginator { mat-paginator {
margin-top: auto; margin-top: auto;
} }
mat-form-field { mat-form-field {
flex-grow: 1; flex-grow: 1;
} }
#upper-bar { #upper-bar {
display: flex; display: flex;
} }
button[mat-icon-button] { button[mat-icon-button] {
margin-left: 4pt; margin-left: 4pt;
margin-right: 4pt; margin-right: 4pt;
margin-top: 4pt; margin-top: 4pt;
} }

View File

@@ -1,38 +1,54 @@
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing'
import { AccountMgmtComponent } from './account-mgmt.component'; import { AccountMgmtComponent } from './account-mgmt.component'
import { AdminCommService } from '../admin-comm.service'; import { MatDialogModule } from '@angular/material/dialog'
import { MatDialogModule } from '@angular/material/dialog'; import { MatSnackBarModule } from '@angular/material/snack-bar'
import { MatSnackBarModule } from '@angular/material/snack-bar'; import { MatFormFieldModule } from '@angular/material/form-field'
import { MatFormFieldModule } from '@angular/material/form-field'; import { MatIconModule } from '@angular/material/icon'
import { MatIconModule } from '@angular/material/icon'; import { MatPaginatorModule } from '@angular/material/paginator'
import { MatPaginatorModule } from '@angular/material/paginator'; import { MatTableModule } from '@angular/material/table'
import { of } from 'rxjs'; import { MatInputModule } from '@angular/material/input'
import { MatTableModule } from '@angular/material/table'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'
import { MatInputModule } from '@angular/material/input'; import { MatProgressSpinnerModule } from '@angular/material/progress-spinner'
import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { AccountMgmtService } from './account-mgmt.service'
import { LoadShadeComponent } from 'src/app/commonComponents/load-shade/load-shade.component'
import { of } from 'rxjs'
import { signal } from '@angular/core'
import { STATE } from 'src/app/types/state'
describe('AccountMgmtComponent', () => { describe('AccountMgmtComponent', () => {
let component: AccountMgmtComponent; let component: AccountMgmtComponent
let fixture: ComponentFixture<AccountMgmtComponent>; let fixture: ComponentFixture<AccountMgmtComponent>
let acMock
beforeEach(async () => { beforeEach(async () => {
const acMock = jasmine.createSpyObj("AdminCommService", { acMock = {
getAccs: of() accs: of([]),
}) state: signal(STATE.NOT_LOADED),
refresh: jasmine.createSpy('getAccs'),
error: signal(undefined)
}
await TestBed.configureTestingModule({ await TestBed.configureTestingModule({
declarations: [AccountMgmtComponent], declarations: [AccountMgmtComponent, LoadShadeComponent],
providers: [ providers: [{ provide: AccountMgmtService, useValue: acMock }],
{provide: AdminCommService, useValue: acMock} imports: [
MatDialogModule,
MatSnackBarModule,
MatFormFieldModule,
MatIconModule,
MatPaginatorModule,
MatTableModule,
MatInputModule,
BrowserAnimationsModule,
MatProgressSpinnerModule,
], ],
imports: [MatDialogModule, MatSnackBarModule, MatFormFieldModule, MatIconModule, MatPaginatorModule, MatTableModule, MatInputModule, BrowserAnimationsModule] }).compileComponents()
}).compileComponents(); fixture = TestBed.createComponent(AccountMgmtComponent)
fixture = TestBed.createComponent(AccountMgmtComponent); component = fixture.componentInstance
component = fixture.componentInstance; fixture.detectChanges()
fixture.detectChanges(); })
});
it('should create', () => { it('should create', () => {
expect(component).toBeTruthy(); expect(component).toBeTruthy()
}); })
}); })

View File

@@ -1,55 +1,58 @@
import { AfterViewInit, Component, OnInit, ViewChild } from '@angular/core'; import { AfterViewInit, Component, ViewChild } from '@angular/core'
import { AdminCommService } from '../admin-comm.service'; import { MatDialog } from '@angular/material/dialog'
import { MatDialog } from '@angular/material/dialog'; import { MatTableDataSource } from '@angular/material/table'
import { MatTableDataSource } from '@angular/material/table'; import { MatPaginator } from '@angular/material/paginator'
import { MatPaginator } from '@angular/material/paginator'; import { UserEditComponent } from './user-edit/user-edit.component'
import { MatSnackBar } from '@angular/material/snack-bar'; import { LocalStorageService } from 'src/app/services/local-storage.service'
import { UserDeleteComponent } from './user-delete/user-delete.component'; import { Group } from 'src/app/types/group'
import { UserEditComponent } from './user-edit/user-edit.component'; import { User } from 'src/app/admin-view/account-mgmt/account.model'
import { catchError, throwError } from 'rxjs'; import { AccountMgmtService } from './account-mgmt.service'
import { UserResetComponent } from './user-reset/user-reset.component'; import { STATE } from 'src/app/types/state'
import { LocalStorageService } from 'src/app/services/local-storage.service';
import { Group } from 'src/app/types/group';
@Component({ @Component({
selector: 'app-account-mgmt', selector: 'app-account-mgmt',
templateUrl: './account-mgmt.component.html', templateUrl: './account-mgmt.component.html',
styleUrls: ['./account-mgmt.component.scss'] styleUrls: ['./account-mgmt.component.scss'],
standalone: false,
}) })
export class AccountMgmtComponent implements AfterViewInit {
export class AccountMgmtComponent implements OnInit, AfterViewInit {
protected groups: Group[] = [] protected groups: Group[] = []
users: MatTableDataSource<any> users: MatTableDataSource<User>
loading = false
@ViewChild(MatPaginator) paginator!: MatPaginator @ViewChild(MatPaginator) paginator!: MatPaginator
constructor(readonly ac:AdminCommService, private dialog: MatDialog, private sb: MatSnackBar, protected readonly ls: LocalStorageService) { constructor(
this.users = new MatTableDataSource<any>(); protected ac: AccountMgmtService,
this.users.filterPredicate = (data: Record<string, any>, filter: string): boolean => { private dialog: MatDialog,
const dataStr = Object.keys(data).reduce((curr: string, key: string) => { protected readonly ls: LocalStorageService
if (key == "_id") { ) {
return '' this.users = new MatTableDataSource<User>()
} this.users.filterPredicate = (
return curr + data[key] + '⫂' data: Record<string, any>,
}, '').toLowerCase() filter: string
): boolean => {
const dataStr = Object.keys(data)
.reduce((curr: string, key: string) => {
if (['_id', 'admin', 'groups', '__v', 'locked'].find(v => v == key)) {
return curr + ''
}
return curr + data[key] + '⫂'
}, '')
.toLowerCase()
const filternew = filter.trim().toLowerCase() const filternew = filter.trim().toLowerCase()
return dataStr.indexOf(filternew) != -1 return dataStr.indexOf(filternew) != -1
} }
} this.ac.refresh()
this.ac.accs.subscribe(d => {
ngAfterViewInit() { this.users.data = d
this.users.paginator = this.paginator })
} }
ngOnInit() { protected get STATE(): typeof STATE {
this.loading = true return STATE
this.ac.accs.getAccs().subscribe((data)=>{ }
this.loading = false
this.users.data = data.users ngAfterViewInit() {
this.groups = data.groups this.users.paginator = this.paginator
})
} }
filter(event: Event) { filter(event: Event) {
@@ -57,76 +60,19 @@ export class AccountMgmtComponent implements OnInit, AfterViewInit {
this.users.filter = value.toLowerCase().trim() this.users.filter = value.toLowerCase().trim()
} }
edit(item: any) { openUserCard(id?: string) {
this.dialog.open(UserEditComponent, {data: {user: item, groups: this.groups}}).afterClosed().subscribe(reply => { this.dialog
if (reply) { .open<
this.ac.accs.putAcc(item._id, reply).pipe(catchError((err)=>{ UserEditComponent,
this.sb.open("Wystąpił błąd. Skontaktuj się z obsługą programu.") UserEditComponent.InputData,
return throwError(()=> new Error(err.message)) UserEditComponent.ReturnData
})).subscribe((data)=> { >(UserEditComponent, {
if (data.status == 200) { data: { id: id, type: id ? 'edit' : 'new', groups: this.groups },
this.sb.open("Użytkownik został zmodyfikowany.", undefined, {duration: 2500}) })
this.ngOnInit() .afterClosed()
} else { .subscribe(r => {
this.sb.open("Wystąpił błąd. Skontaktuj się z obsługą programu.") if (r) this.ac.refresh()
} })
})
}
})
}
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
}
})
} }
collumns = ['name', 'surname', 'uname', 'actions'] collumns = ['name', 'surname', 'uname', 'actions']

View File

@@ -0,0 +1,96 @@
import { TestBed } from '@angular/core/testing';
import { AccountMgmtService } from './account-mgmt.service';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { environment } from 'src/environments/environment';
import { firstValueFrom, skip } from 'rxjs';
describe('AccountMgmtService', () => {
let service: AccountMgmtService;
let httpTesting: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
provideHttpClient(),
provideHttpClientTesting()
]
});
httpTesting = TestBed.inject(HttpTestingController);
service = TestBed.inject(AccountMgmtService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
it('should get user accounts', () => {
service.refresh()
const req = httpTesting.expectOne(environment.apiEndpoint + "/admin/accs", "Request to load all users")
expect(req.request.method).toBe("GET")
req.flush([])
httpTesting.verify()
})
describe('create user', () => {
xit('should create a user account and refresh list', () => {
const test_user = {
uname: "test",
groups: []
}
service.postAcc(test_user).subscribe(v => {
expect(v).toEqual(jasmine.objectContaining(test_user))
})
const req = httpTesting.expectOne(environment.apiEndpoint + "/admin/accs", "Request new user")
expect(req.request.method).toBe("POST")
req.flush({
...test_user,
_id: "test_id"
})
const req2 = httpTesting.expectOne(environment.apiEndpoint + "/admin/accs", "Request to load all users")
expect(req2.request.method).toBe("GET")
// service.accs.pipe(skip(1)).subscribe(v => {
// expect(v).toContain(createdUser)
// })
req2.flush([
{
...test_user,
_id: "test_id"
}
])
httpTesting.verify()
})
})
describe("delete user", () => {
it('should refresh accounts and not to contain deleted user', async () => {
service.deleteAcc("test").subscribe()
const req = httpTesting.expectOne(environment.apiEndpoint + "/admin/accs/test", "Request delete user")
expect(req.request.method).toBe("DELETE")
req.flush({ status: 200 })
const req2 = httpTesting.expectOne(environment.apiEndpoint + "/admin/accs", "Request to load all users")
expect(req2.request.method).toBe("GET")
service.accs.pipe(skip(1)).subscribe(v => {
expect(v).not.toContain(jasmine.objectContaining({ _id: "test" }))
})
req2.flush([])
httpTesting.verify()
})
})
});

View File

@@ -0,0 +1,110 @@
import { HttpClient } from '@angular/common/http';
import { Injectable, signal } from '@angular/core';
import { BehaviorSubject, catchError, map, of, tap } from 'rxjs';
import { STATE } from 'src/app/types/state';
import { Status } from 'src/app/types/status';
import { User, UserAPI } from 'src/app/admin-view/account-mgmt/account.model';
import { environment } from 'src/environments/environment';
import { DateTime } from 'luxon';
@Injectable({
providedIn: 'root'
})
export class AccountMgmtService {
constructor(private http: HttpClient) { }
private _accs = new BehaviorSubject<User[]>([])
public readonly accs = this._accs.asObservable()
private _state = signal(STATE.NOT_LOADED);
public readonly state = this._state.asReadonly();
private _error = signal<string | undefined>(undefined);
public readonly error = this._error.asReadonly();
private _selAcc = new BehaviorSubject<User | null>(null)
public readonly selAcc = this._selAcc.asObservable()
public refresh() {
this.getAccs()
}
private getAccs() {
this._state.set(STATE.PENDING)
this.http.get
<UserAPI[]>
(environment.apiEndpoint + `/admin/accs`, { withCredentials: true })
.pipe(
catchError((err: Error) => {
this._state.set(STATE.ERROR)
this._error.set(err.message)
return of()
}),
map<UserAPI[], User[]>(v => {
return v.map(i => ({
...i,
regDate: DateTime.fromISO(i.regDate)
}))
})
).subscribe(v => {
this._error.set(undefined)
this._accs.next(v ?? [])
this._state.set(STATE.LOADED)
})
}
selectAccount(acc: User) {
this._selAcc.next(acc)
}
//#region legacy
postAcc(item: Omit<User, "_id" | "regDate">) {
return this.http.post<User>(
environment.apiEndpoint + `/admin/accs`,
item,
{ withCredentials: true }
).pipe(tap(v => {
if (v instanceof Array) this.refresh()
}))
}
putAcc(id: string, update: Partial<User>) {
return this.http.put<Status>(
environment.apiEndpoint + `/admin/accs/${id}`,
update,
{ withCredentials: true }
)
}
resetPass(id: string) {
return this.http.patch<Status>(
environment.apiEndpoint + `/admin/accs/${id}/reset`,
undefined,
{ withCredentials: true }
)
}
deleteAcc(id: string) {
return this.http.delete<Status>(
environment.apiEndpoint + `/admin/accs/${id}`,
{ withCredentials: true }
)
.pipe(tap(v => {
if (v.status == 200) this.refresh()
}))
}
getUser(id: string) {
return this.http.get<
Omit<User, 'regDate'> & { lockout: boolean; regDate: string }
>(environment.apiEndpoint + `/admin/accs/${id}`, {
withCredentials: true,
})
}
clearLockout(id: string) {
return this.http.delete<Status>(
environment.apiEndpoint + `/admin/accs/${id}/lockout`,
{ withCredentials: true }
)
}
//#endregion
}

View File

@@ -0,0 +1,16 @@
import { DateTime } from 'luxon'
export interface User {
_id: string
uname: string
room?: string
admin?: string[]
locked?: boolean
fname?: string
surname?: string
groups: string[]
regDate: DateTime
defaultPage?: string
}
export type UserAPI = Omit<User, "regDate"> & {regDate: "string"}

View File

@@ -1,23 +1,23 @@
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing'
import { UserDeleteComponent } from './user-delete.component'; import { UserDeleteComponent } from './user-delete.component'
import { MatDialogModule } from '@angular/material/dialog'; import { MatDialogModule } from '@angular/material/dialog'
describe('UserDeleteComponent', () => { describe('UserDeleteComponent', () => {
let component: UserDeleteComponent; let component: UserDeleteComponent
let fixture: ComponentFixture<UserDeleteComponent>; let fixture: ComponentFixture<UserDeleteComponent>
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
declarations: [UserDeleteComponent], declarations: [UserDeleteComponent],
imports: [MatDialogModule] imports: [MatDialogModule],
}); })
fixture = TestBed.createComponent(UserDeleteComponent); fixture = TestBed.createComponent(UserDeleteComponent)
component = fixture.componentInstance; component = fixture.componentInstance
fixture.detectChanges(); fixture.detectChanges()
}); })
it('should create', () => { it('should create', () => {
expect(component).toBeTruthy(); expect(component).toBeTruthy()
}); })
}); })

View File

@@ -1,10 +1,9 @@
import { Component } from '@angular/core'; import { Component } from '@angular/core'
@Component({ @Component({
selector: 'app-user-delete', selector: 'app-user-delete',
templateUrl: './user-delete.component.html', templateUrl: './user-delete.component.html',
styleUrls: ['./user-delete.component.scss'] styleUrls: ['./user-delete.component.scss'],
standalone: false,
}) })
export class UserDeleteComponent { export class UserDeleteComponent {}
}

View File

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

View File

@@ -1,10 +1,32 @@
:host { :host {
padding: 8pt; padding: 8pt;
display: block; display: block;
} }
form { form {
display: flex; margin-top: 1ch !important;
flex-direction: column; display: flex;
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; 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,31 +1,46 @@
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing'
import { UserEditComponent } from './user-edit.component'; import { UserEditComponent } from './user-edit.component'
import { MAT_DIALOG_DATA, MatDialogModule, MatDialogRef } from '@angular/material/dialog'; import {
import { MatFormFieldModule } from '@angular/material/form-field'; MAT_DIALOG_DATA,
import { ReactiveFormsModule } from '@angular/forms'; MatDialogModule,
import { MatInputModule } from '@angular/material/input'; MatDialogRef,
import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; } from '@angular/material/dialog'
import { MatFormFieldModule } from '@angular/material/form-field'
import { ReactiveFormsModule } from '@angular/forms'
import { MatInputModule } from '@angular/material/input'
import { NoopAnimationsModule } from '@angular/platform-browser/animations'
import { MatSelectModule } from '@angular/material/select'
describe('UserEditComponent', () => { xdescribe('UserEditComponent', () => {
let component: UserEditComponent; let component: UserEditComponent
let fixture: ComponentFixture<UserEditComponent>; let fixture: ComponentFixture<UserEditComponent>
let acMock
beforeEach(async () => { beforeEach(async () => {
acMock = {}
await TestBed.configureTestingModule({ await TestBed.configureTestingModule({
declarations: [UserEditComponent], declarations: [UserEditComponent],
imports: [MatDialogModule, MatFormFieldModule, ReactiveFormsModule, MatInputModule, BrowserAnimationsModule], imports: [
MatDialogModule,
MatFormFieldModule,
ReactiveFormsModule,
MatInputModule,
NoopAnimationsModule,
MatSelectModule,
],
providers: [ providers: [
{provide: MatDialogRef, useValue: {}}, { provide: MatDialogRef, useValue: {} },
{provide: MAT_DIALOG_DATA, useValue: {}} { provide: MAT_DIALOG_DATA, useValue: { groups: [] } },
] // { provide: AdminCommService, useValue: acMock },
}).compileComponents(); ],
fixture = TestBed.createComponent(UserEditComponent); }).compileComponents()
component = fixture.componentInstance; fixture = TestBed.createComponent(UserEditComponent)
fixture.detectChanges(); component = fixture.componentInstance
}); fixture.detectChanges()
})
it('should create', () => { it('should create', () => {
expect(component).toBeTruthy(); expect(component).toBeTruthy()
}); })
}); })

View File

@@ -1,65 +1,199 @@
import { Component, Inject } from '@angular/core'; import { Component, Inject } from '@angular/core'
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog'; import {
import { FormControl, FormGroup } from '@angular/forms'; MAT_DIALOG_DATA,
import { LocalStorageService } from 'src/app/services/local-storage.service'; MatDialog,
import { Group } from 'src/app/types/group'; 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 { 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 { DateTime } from 'luxon'
import { AccountMgmtService } from '../account-mgmt.service'
import { AdminSyncService } from '../../admin-sync.service'
export namespace UserEditComponent {
export type InputData = { type: 'new' | 'edit'; id?: string; groups: Group[] }
export type ReturnData = true | undefined
}
@Component({ @Component({
selector: 'app-user-edit', selector: 'app-user-edit',
templateUrl: './user-edit.component.html', templateUrl: './user-edit.component.html',
styleUrls: ['./user-edit.component.scss'] styleUrls: ['./user-edit.component.scss'],
standalone: false,
}) })
export class UserEditComponent { export class UserEditComponent {
form: FormGroup lockout = false
groups: Group[] locked = false
constructor (public dialogRef: MatDialogRef<UserEditComponent>, @Inject(MAT_DIALOG_DATA) public data: any, readonly ls: LocalStorageService) { loading = false
if (data.user == null) { form: FormGroup = new FormGroup({
data.user = { fname: new FormControl<string>(''),
fname: "", surname: new FormControl<string>(''),
surname: "", room: new FormControl<string>(''),
room: "", uname: new FormControl<string>(''),
uname: "", groups: new FormControl<Array<string>>([]),
groups: [], flags: new FormControl<Array<string>>([]),
admin: 0 })
} id?: string
regDate?: DateTime
constructor(
public dialogRef: MatDialogRef<UserEditComponent>,
@Inject(MAT_DIALOG_DATA) public data: UserEditComponent.InputData,
readonly ls: LocalStorageService,
readonly acu: AccountMgmtService,
private dialog: MatDialog,
private sb: MatSnackBar,
protected adsyn: AdminSyncService
) {
if (data.type == 'edit') {
this.id = data.id
this.acu.getUser(data.id!).subscribe(r => {
this.regDate = DateTime.fromISO(r.regDate)
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(r.admin)
})
} }
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() { protected submit() {
this.dialogRef.close({ this.loading = true
if (this.data.type == 'edit') {
this.acu
.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
.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) {
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
.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
}
})
}
protected getForm() {
return {
fname: this.form.get('fname')?.value, fname: this.form.get('fname')?.value,
surname: this.form.get('surname')?.value, surname: this.form.get('surname')?.value,
room: this.form.get('room')?.value, room: this.form.get('room')?.value,
uname: this.form.get('uname')?.value, uname: this.form.get('uname')?.value,
groups: this.form.get('groups')?.value, groups: this.form.get('groups')?.value,
flags: (() => { admin: (() => {
var value = this.form.get('flags')?.value.reduce((a: number,b: number)=>a+b,0) var value = this.form.get('flags')?.value
if (this.ls.capCheck(32)) { if (this.ls.capCheck(32)) {
return value return value
} else { } else {
return undefined return undefined
} }
})() })(),
}
}
protected delete() {
this.dialog
.open(UserDeleteComponent)
.afterClosed()
.subscribe(reply => {
if (reply) {
this.acu.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.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.putAcc(this.id!, { locked: state }).subscribe(res => {
if (res.status == 200) {
this.locked = state
}
}) })
} }
} }

View File

@@ -1,21 +1,23 @@
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing'
import { UserResetComponent } from './user-reset.component'; import { UserResetComponent } from './user-reset.component'
import { MatDialogModule } from '@angular/material/dialog'
describe('UserResetComponent', () => { describe('UserResetComponent', () => {
let component: UserResetComponent; let component: UserResetComponent
let fixture: ComponentFixture<UserResetComponent>; let fixture: ComponentFixture<UserResetComponent>
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
declarations: [UserResetComponent] declarations: [UserResetComponent],
}); imports: [MatDialogModule],
fixture = TestBed.createComponent(UserResetComponent); })
component = fixture.componentInstance; fixture = TestBed.createComponent(UserResetComponent)
fixture.detectChanges(); component = fixture.componentInstance
}); fixture.detectChanges()
})
it('should create', () => { it('should create', () => {
expect(component).toBeTruthy(); expect(component).toBeTruthy()
}); })
}); })

View File

@@ -1,10 +1,9 @@
import { Component } from '@angular/core'; import { Component } from '@angular/core'
@Component({ @Component({
selector: 'app-user-reset', selector: 'app-user-reset',
templateUrl: './user-reset.component.html', templateUrl: './user-reset.component.html',
styleUrls: ['./user-reset.component.scss'] styleUrls: ['./user-reset.component.scss'],
standalone: false,
}) })
export class UserResetComponent { export class UserResetComponent {}
}

View File

@@ -1,24 +0,0 @@
import { TestBed } from '@angular/core/testing';
import { AdminCommService } from './admin-comm.service';
import { HttpClient } from '@angular/common/http';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
describe('AdminCommService', () => {
let service: AdminCommService;
let httpClient: HttpClient
let httpTestingController: HttpTestingController
beforeEach(() => {
TestBed.configureTestingModule({
imports: [ HttpClientTestingModule ]
});
service = TestBed.inject(AdminCommService);
httpClient = TestBed.inject(HttpClient);
httpTestingController = TestBed.inject(HttpTestingController);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
});

View File

@@ -1,269 +0,0 @@
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Moment } from 'moment';
import { environment } from 'src/environments/environment';
import { Menu } from '../types/menu';
import { Status } from '../types/status';
import { Group } from '../types/group';
import { map, of } from 'rxjs';
import { Notification } from '../types/notification';
import { News } from '../types/news';
import { AKey } from '../types/key';
import * as moment from 'moment';
import { IUSettings } from './settings/settings.component';
@Injectable({
providedIn: 'root'
})
export class AdminCommService {
constructor(private http: HttpClient) { }
//#region Menu
menu = {
getMenu: (start?: Moment | null, end?: Moment | null) => {
if (start && end) {
const body = {start: start.toString(), end: end.toString()}
return this.http.get<Menu[]>(environment.apiEndpoint+"/admin/menu", {withCredentials: true, params: body})
}
return
},
getOpts: () => {
return this.http.get<any>(environment.apiEndpoint+`/admin/menu/opts`, {withCredentials: true})
},
postMenu: (file: File) => {
if (file) {
const formData = new FormData();
formData.append("menu", file)
return this.http.post<Status>(environment.apiEndpoint+"/admin/menu/upload", formData, {withCredentials: true})
}
return
},
editSn: (id: string, content: Menu['sn']) => {
return this.putMenu(id, {sn: content})
},
editOb: (id: string, content: Menu['ob']) => {
return this.putMenu(id, {ob: content})
},
editKol: (id: string, content: Menu['kol']) => {
return this.putMenu(id, {kol: content})
},
editTitle: (id: string, content: Menu['dayTitle']) => {
return this.putMenu(id, {dayTitle: content})
},
print: (start?: Moment | null, end?: Moment | null) => {
if (start && end) {
const body = {start: start.toString(), end: end.toString()}
return this.http.get(environment.apiEndpoint+"/admin/menu/print", {withCredentials: true, params: body, responseType: "text"})
}
return
},
stat: (day: Moment, m: "ob" | "kol") => {
return this.http.get<{y: number, n: number}>(environment.apiEndpoint+`/admin/menu/${day.toISOString()}/votes/${m}`, {withCredentials: true})
},
new: {
single: (day: Moment) => {
return this.http.post<Status>(environment.apiEndpoint+`/admin/menu/${day.toISOString()}`, null, {withCredentials: true})
},
range: (start: Moment, count: number) => {
return this.http.post<Status>(environment.apiEndpoint+`/admin/menu/${start.toISOString()}/${count}/`, null, {withCredentials: true})
}
},
rm: (id: string) => {
return this.http.delete<Status>(environment.apiEndpoint+`/admin/menu/${id}`, {withCredentials: true})
}
}
private putMenu(id: string, update: Partial<Menu>) {
return this.http.put<Status>(environment.apiEndpoint+`/admin/menu/${id}`, update, {withCredentials: true})
}
//#endregion
//#region News
news = {
getNews: () => {
return this.http.get<News[]>(environment.apiEndpoint+`/admin/news`, {withCredentials: true})
},
postNews: (title: string, content: string) => {
return this.http.post<any>(environment.apiEndpoint+`/admin/news`, {title: title, content: content}, {withCredentials: true})
},
deleteNews: (id: string) => {
return this.http.delete<any>(environment.apiEndpoint+`/admin/news/${id}`, {withCredentials: true})
},
toggleNews: (id: string, inverter: boolean) => {
return this.putNews(id,{visible: !inverter})
},
togglePin: (id: string, inverter: boolean) => {
return this.putNews(id,{pinned: !inverter})
},
updateNews: (id: string, title: string, content: string) => {
return this.putNews(id,{title: title, content: content, date: Date.now})
}
}
private putNews(id: string, update: object) {
return this.http.put<any>(environment.apiEndpoint+`/admin/news/${id}`, update, {withCredentials: true})
}
//#endregion
//#region amgmt
accs = {
getAccs: () => {
return this.http.get<{
users: {
_id: string;
uname: string;
pass: string;
room?: string;
admin?: number;
locked?: boolean;
fname?: string;
surname?: string;
groups: string[];
}[],
groups: Group[]
}>(environment.apiEndpoint+`/admin/accs`, {withCredentials: true})
},
postAcc: (item: any) => {
return this.http.post<Status>(environment.apiEndpoint+`/admin/accs`, item, {withCredentials: true})
},
putAcc: (id: string, update: object) => {
return this.http.put<Status>(environment.apiEndpoint+`/admin/accs/${id}`, update, {withCredentials: true})
},
resetPass: (id: string) => {
return this.http.patch<Status>(environment.apiEndpoint+`/admin/accs/${id}/reset`, {}, {withCredentials: true})
},
deleteAcc: (id: string) => {
return this.http.delete<Status>(environment.apiEndpoint+`/admin/accs/${id}`, {withCredentials: true})
}
}
//#endregion
//#region Groups
groups = {
getGroups: () => {
return this.http.get<Group[]>(environment.apiEndpoint+`/admin/groups`, {withCredentials: true})
},
newGroup: (name: string) => {
return this.http.post<Status>(environment.apiEndpoint+`/admin/groups`, {name: name}, {withCredentials: true})
},
editName: (id: string, name: string) => {
return this.putGroups(id, {name: name.trim()})
},
remove: (id: string) => {
return this.http.delete<Status>(environment.apiEndpoint+`/admin/groups/${id}`, {withCredentials: true})
}
}
private putGroups(id: string, update: Partial<Group>) {
return this.http.put<Status>(environment.apiEndpoint+`/admin/groups/${id}`, update, {withCredentials: true})
}
//#endregion
//#region Notif
notif = {
send: (n: Notification) => {
return this.http.post<{sent: number, possible: number}>(environment.apiEndpoint+"/admin/notif/send", n, {withCredentials: true})
},
getGroups: () => {
return this.http.get<Group[]>(environment.apiEndpoint+"/admin/notif/groups", {withCredentials: true})
}
}
//#endregion
//#region Keys
keys = {
getKeys: () => {
return this.http.get<AKey[]>(environment.apiEndpoint+`/admin/keys`, {withCredentials: true}).pipe(map((v) => {
return v.map((r) => {
r.borrow = moment(r.borrow)
if (r.tb) r.tb = moment(r.tb)
return r
})
}))
},
avalKeys: () => {
return this.http.get<string[]>(environment.apiEndpoint+`/admin/keys/available`, {withCredentials: true})
},
postKey: (room: string, uname: string) => {
return this.http.post<Status>(environment.apiEndpoint+`/admin/keys/`, {room: room, whom: uname}, {withCredentials: true})
},
returnKey: (id: string) => {
return this.putKeys(id, {tb: moment.utc()})
}
}
private putKeys(id: string, update: Partial<AKey>) {
return this.http.put<Status>(environment.apiEndpoint+`/admin/keys/${id}`, update, {withCredentials: true})
}
//#endregion
//#region Clean
clean = {
getConfig: () => {
return this.http.get<{rooms: string[], things: string[]}>(environment.apiEndpoint+`/admin/clean/config`, {withCredentials: true})
},
getClean: (date: moment.Moment, room: string) => {
return this.http.get<{_id: string, date: string, grade: number, gradeDate: string, notes: {label: string, weight: number}[], room: string, tips: string} | null>(environment.apiEndpoint+`/admin/clean/${date.toISOString()}/${room}`, {withCredentials: true})
},
postClean: (obj: Object) => {
return this.http.post<Status>(environment.apiEndpoint+`/admin/clean/`, obj, {withCredentials: true})
},
delete: (id: string) => {
return this.http.delete<Status>(environment.apiEndpoint+`/admin/clean/${id}`, {withCredentials: true})
},
summary: {
getSummary: (start: moment.Moment, end: moment.Moment) => {
return this.http.get<{room: string, avg: number}[]>(environment.apiEndpoint+`/admin/clean/summary/${start.toISOString()}/${end.toISOString()}`, {withCredentials: true})
}
},
attendence: {
getUsers: (room: string) => {
return this.http.get<{users: {fname: string, surname: string, _id: string}[], attendence?: {id: string, hour?: string}[]}>(environment.apiEndpoint+`/admin/clean/attendence/${room}`, {withCredentials: true})
},
postAttendence: (room: string, attendence: {id: string, hour?: string}[]) => {
return this.http.post<Status>(environment.apiEndpoint+`/admin/clean/attendence/${room}`, attendence, {withCredentials: true})
},
getSummary: () => {
return this.http.get<{room: string, hours: string[]}[]>(environment.apiEndpoint+`/admin/clean/attendenceSummary`, {withCredentials: true})
}
}
}
//#endregion
//#region Settings
settings = {
getAll: () => {
return this.http.get<IUSettings>(environment.apiEndpoint+`/admin/settings/`, {withCredentials: true})
},
post: (settings: IUSettings) => {
return this.http.post<Status>(environment.apiEndpoint+`/admin/settings/`, settings, {withCredentials: true})
},
reload: () => {
return this.http.get<Status>(environment.apiEndpoint+`/admin/settings/reload/`, {withCredentials: true})
}
}
//#endregion
//#region misc
userFilter = (query: string) => {
return this.http.get<any[]>(environment.apiEndpoint+`/admin/usearch`, {params: {q: query}, withCredentials: true})
}
//#endregion
}

View File

@@ -0,0 +1,23 @@
import { TestBed } from '@angular/core/testing';
import { AdminSyncService } from './admin-sync.service';
import { provideHttpClient } from '@angular/common/http';
import { provideHttpClientTesting } from '@angular/common/http/testing';
describe('AdminSyncService', () => {
let service: AdminSyncService;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
provideHttpClient(),
provideHttpClientTesting()
]
});
service = TestBed.inject(AdminSyncService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
});

View File

@@ -0,0 +1,27 @@
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Group } from '../types/group';
import { environment } from 'src/environments/environment';
@Injectable({
providedIn: 'root'
})
export class AdminSyncService {
constructor(private http: HttpClient) { }
private _data: any
private sync() {
this.http.get(environment.apiEndpoint + `/admin/sync`, { withCredentials: true }).subscribe(v => {
this._data = v
})
}
public get groups(): Group[] {
var groups = this._data?.groups
if (!groups) this.sync()
return groups
}
}

View File

@@ -1,17 +1,4 @@
<mat-toolbar color="accent"> <app-toolbar [drawer]="drawer"/>
<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>
<mat-sidenav-container> <mat-sidenav-container>
<mat-sidenav #drawer mode="over" autoFocus="false"> <mat-sidenav #drawer mode="over" autoFocus="false">
<mat-nav-list> <mat-nav-list>
@@ -21,6 +8,10 @@
<a matListItemTitle>{{link.title}}</a> <a matListItemTitle>{{link.title}}</a>
</mat-list-item> </mat-list-item>
} }
<a mat-list-item href="https://foliand.men/wiki/!ipwa/" target="_blank">
<mat-icon matListItemIcon>developer_guide</mat-icon>
<a matListItemTitle>Dokumentacja</a>
</a>
<mat-list-item (click)="goNormal()"> <mat-list-item (click)="goNormal()">
<mat-icon matListItemIcon>close</mat-icon> <mat-icon matListItemIcon>close</mat-icon>
<h4 matListItemTitle>Zakończ edycję</h4> <h4 matListItemTitle>Zakończ edycję</h4>

View File

@@ -1,14 +1,15 @@
:host { :host {
width: 100%; width: 100%;
height: 100%; height: 100%;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
} }
mat-sidenav, mat-toolbar { mat-sidenav,
padding: 8pt mat-toolbar {
padding: 8pt;
} }
mat-sidenav-container { mat-sidenav-container {
flex-grow: 1; flex-grow: 1;
} }

View File

@@ -1,28 +1,45 @@
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing'
import { AdminViewComponent } from './admin-view.component'; import { AdminViewComponent } from './admin-view.component'
import { MatToolbarModule } from '@angular/material/toolbar'; import { MatToolbarModule } from '@angular/material/toolbar'
import { MatIconModule } from '@angular/material/icon'; import { MatIconModule } from '@angular/material/icon'
import { MatSidenavModule } from '@angular/material/sidenav'; import { MatDrawer, MatSidenavModule } from '@angular/material/sidenav'
import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'
import { MatListModule } from '@angular/material/list'; import { MatListModule } from '@angular/material/list'
import { RouterModule } from '@angular/router'; import { RouterModule } from '@angular/router'
import { Component, Input } from '@angular/core'
@Component({
selector: 'app-toolbar',
template: '',
standalone: false,
})
class ToolbarMock {
@Input() drawer!: MatDrawer
}
describe('AdminViewComponent', () => { describe('AdminViewComponent', () => {
let component: AdminViewComponent; let component: AdminViewComponent
let fixture: ComponentFixture<AdminViewComponent>; let fixture: ComponentFixture<AdminViewComponent>
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
declarations: [AdminViewComponent], declarations: [AdminViewComponent, ToolbarMock],
imports: [MatToolbarModule, MatIconModule, MatSidenavModule, BrowserAnimationsModule, MatListModule, RouterModule.forRoot([])] imports: [
}); MatToolbarModule,
fixture = TestBed.createComponent(AdminViewComponent); MatIconModule,
component = fixture.componentInstance; MatSidenavModule,
fixture.detectChanges(); BrowserAnimationsModule,
}); MatListModule,
RouterModule.forRoot([]),
],
})
fixture = TestBed.createComponent(AdminViewComponent)
component = fixture.componentInstance
fixture.detectChanges()
})
it('should create', () => { it('should create', () => {
expect(component).toBeTruthy(); expect(component).toBeTruthy()
}); })
}); })

View File

@@ -1,32 +1,78 @@
import { Component } from '@angular/core'; import { Component } from '@angular/core'
import { Title } from '@angular/platform-browser'; import { Router } from '@angular/router'
import { Router } from '@angular/router'; import { LocalStorageService } from '../services/local-storage.service'
import { LocalStorageService } from '../services/local-storage.service'; import { Link } from '../types/link'
import { Link } from '../types/link';
import { ToolbarService } from './toolbar.service';
@Component({ @Component({
selector: 'app-admin-view', selector: 'app-admin-view',
templateUrl: './admin-view.component.html', templateUrl: './admin-view.component.html',
styleUrls: ['./admin-view.component.scss'] styleUrls: ['./admin-view.component.scss'],
standalone: false,
}) })
export class AdminViewComponent { export class AdminViewComponent {
private readonly _LINKS: Link[] = [ private readonly _LINKS: Link[] = [
{ title: "Wiadomości", icon: "newspaper", href: "news", enabled: this.ls.permChecker(1) && this.ls.capCheck(1) }, {
{ title: "Jadłospis", icon: "restaurant_menu", href: "menu", enabled: this.ls.permChecker(2) && this.ls.capCheck(2) }, title: 'Wiadomości',
{ title: "Wysyłanie powiadomień", icon: "notifications", href: "notifications", enabled: this.ls.permChecker(4) && this.ls.capCheck(4) }, icon: 'newspaper',
{ title: "Grupy", icon: "groups", href: "groups", enabled: this.ls.permChecker(8) && this.ls.capCheck(8) }, href: 'news',
{ title: "Zarządzanie kontami", icon: "manage_accounts", href: "accounts", enabled: this.ls.permChecker(16) }, enabled: this.ls.permChecker("news") && this.ls.capCheck(1),
{ title: "Klucze", icon: "key", href: "keys", enabled: this.ls.permChecker(64) && this.ls.capCheck(32) }, },
{ title: "Czystość", icon: "cleaning_services", href: "grades", enabled: this.ls.permChecker(128) && this.ls.capCheck(16) }, {
{ title: "Frekwencja", icon: "checklist", href: "attendence", enabled: false }, title: 'Jadłospis',
{ title: "Ustawienia", icon: "settings_applications", href: "settings", enabled: this.ls.permChecker(32) }, icon: 'restaurant_menu',
{ title: "Instrukcje", icon: "description", href: "guide", enabled: true } href: 'menu',
]; enabled: this.ls.permChecker("menu") && this.ls.capCheck(2),
},
{
title: 'Wysyłanie powiadomień',
icon: 'notifications',
href: 'notifications',
enabled: this.ls.permChecker("notif") && this.ls.capCheck(4),
},
{
title: 'Grupy',
icon: 'groups',
href: 'groups',
enabled: this.ls.permChecker("groups") && this.ls.capCheck(8),
},
{
title: 'Zarządzanie kontami',
icon: 'manage_accounts',
href: 'accounts',
enabled: this.ls.permChecker("accs"),
},
{
title: 'Klucze',
icon: 'key',
href: 'keys',
enabled: this.ls.permChecker("keys") && this.ls.capCheck(32),
},
{
title: 'Czystość',
icon: 'cleaning_services',
href: 'grades',
enabled: this.ls.permChecker("grades") && this.ls.capCheck(16),
},
{
title: 'Frekwencja',
icon: 'checklist',
href: 'attendence',
enabled: false,
},
{
title: 'Ustawienia',
icon: 'settings_applications',
href: 'settings',
enabled: this.ls.permChecker("super"),
},
]
public get LINKS(): Link[] { public get LINKS(): Link[] {
return this._LINKS.filter(v => v.enabled); 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() { goNormal() {
this.router.navigateByUrl('app') this.router.navigateByUrl('app')
} }

View File

@@ -1,21 +1,29 @@
<div id="guide"> <div id="guide">
<p><b>Uwaga:</b> Obecność resetuje się o codziennie o 00:00</p> <p><b>Uwaga:</b> Obecność resetuje się o codziennie o 00:00</p>
<div id="legend"> <div id="legend">
<b>Legenda: </b> <b>Legenda: </b>
<span class="circle">Wychowanek obecny</span> <span class="circle">Wychowanek obecny</span>
<span class="circle">Wyjście w ciągu 30 min.</span> <span class="circle">Wyjście w ciągu 30 min.</span>
<span class="circle">Wychowanek nieobecny</span> <span class="circle">Wychowanek nieobecny</span>
</div> </div>
</div> </div>
<table mat-table [dataSource]="data" matSort> <table mat-table [dataSource]="data" matSort>
<div matColumnDef="room"> <div matColumnDef="room">
<th mat-header-cell *matHeaderCellDef mat-sort-header>Pokój</th> <th mat-header-cell *matHeaderCellDef mat-sort-header>Pokój</th>
<td mat-cell *matCellDef="let item">{{item.room}}</td> <td mat-cell *matCellDef="let item">{{item.room}}</td>
</div>
<div matColumnDef="hours">
<th mat-header-cell *matHeaderCellDef mat-sort-header>Godziny</th>
<td mat-cell *matCellDef="let item">@for (i of item.hours.sort().reverse(); track i; let isLast = $last) {
<span><app-hour-display [value]="i"></app-hour-display>{{ isLast ? '' : ', '}}</span>
}<span>{{item.notes}}</span></td>
</div> </div>
<div matColumnDef="hours"> <div matColumnDef="actions">
<th mat-header-cell *matHeaderCellDef mat-sort-header>Godziny</th> <th mat-header-cell *matHeaderCellDef>Usuń</th>
<td mat-cell *matCellDef="let item"><span *ngFor="let i of item.hours.sort().reverse(); let isLast=last"><app-hour-display [value]="i"></app-hour-display>{{ isLast ? '' : ', '}}</span></td> <td mat-cell *matCellDef="let item">@if (!item.auto) {
<button mat-mini-fab color="warn" (click)="delete(item.room)"><mat-icon>delete</mat-icon></button>
}</td>
</div> </div>
<tr mat-header-row *matHeaderRowDef="collumns"></tr> <tr mat-header-row *matHeaderRowDef="collumns"></tr>
<tr mat-row *matRowDef="let rowData; columns: collumns"></tr> <tr mat-row *matRowDef="let rowData; columns: collumns"></tr>
</table> </table>

View File

@@ -1,34 +1,34 @@
@use 'sass:list'; @use "sass:list";
#guide { #guide {
margin: 1em margin: 1em;
} }
#legend { #legend {
display: flex; display: flex;
justify-self: center; justify-self: center;
* { gap: 3ch;
margin: 2px; * {
} margin: 2px;
gap: 3ch; }
} }
.circle { .circle {
&::before { &::before {
border-radius: 7.5%; border-radius: 7.5%;
width: 2.5ch; width: 2.5ch;
height: 2.5ch; height: 2.5ch;
display: inline-block; display: inline-block;
content: ""; content: "";
vertical-align: middle; vertical-align: middle;
margin-right: 3px; margin-right: 3px;
} }
$list: (red, yellow, green); $list: (red, yellow, green);
@for $n from 1 through 3 { @for $n from 1 through 3 {
&:nth-of-type(#{$n})::before { &:nth-of-type(#{$n})::before {
background-color: nth($list, $n); background-color: list.nth($list, $n);
}
} }
} }
}

View File

@@ -1,23 +1,35 @@
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing'
import { AttendenceSummaryComponent } from './attendence-summary.component'; import { AttendenceSummaryComponent } from './attendence-summary.component'
import { RouterModule } from '@angular/router'
import { of } from 'rxjs'
import { MatTableModule } from '@angular/material/table'
describe('AttendenceSummaryComponent', () => { xdescribe('AttendenceSummaryComponent', () => {
let component: AttendenceSummaryComponent; let component: AttendenceSummaryComponent
let fixture: ComponentFixture<AttendenceSummaryComponent>; let fixture: ComponentFixture<AttendenceSummaryComponent>
let acMock
beforeEach(async () => { beforeEach(async () => {
acMock = {
clean: {
attendence: {
getSummary: jasmine.createSpy('getSummary').and.returnValue(of()),
},
},
}
await TestBed.configureTestingModule({ await TestBed.configureTestingModule({
declarations: [AttendenceSummaryComponent] declarations: [AttendenceSummaryComponent],
}) imports: [RouterModule.forRoot([]), MatTableModule],
.compileComponents(); // providers: [{ provide: AdminCommService, useValue: acMock }],
}).compileComponents()
fixture = TestBed.createComponent(AttendenceSummaryComponent);
component = fixture.componentInstance; fixture = TestBed.createComponent(AttendenceSummaryComponent)
fixture.detectChanges(); component = fixture.componentInstance
}); fixture.detectChanges()
})
it('should create', () => { it('should create', () => {
expect(component).toBeTruthy(); expect(component).toBeTruthy()
}); })
}); })

View File

@@ -1,33 +1,54 @@
import { Component, OnInit } from '@angular/core'; import { Component, OnInit } from '@angular/core'
import { ToolbarService } from '../../toolbar.service'; import { ToolbarService } from '../../toolbar/toolbar.service'
import { Router, ActivatedRoute } from '@angular/router'; import { Router, ActivatedRoute } from '@angular/router'
import { MatTableDataSource } from '@angular/material/table'; import { MatTableDataSource } from '@angular/material/table'
import { AdminCommService } from '../../admin-comm.service'; import { GradesService } from '../grades.service'
@Component({ @Component({
selector: 'app-attendence-summary', selector: 'app-attendence-summary',
templateUrl: './attendence-summary.component.html', templateUrl: './attendence-summary.component.html',
styleUrl: './attendence-summary.component.scss' styleUrl: './attendence-summary.component.scss',
standalone: false,
}) })
export class AttendenceSummaryComponent implements OnInit { export class AttendenceSummaryComponent implements OnInit {
data: MatTableDataSource<{
room: string
hours: string[]
notes: string
auto: boolean
}> = new MatTableDataSource<{
room: string
hours: string[]
notes: string
auto: boolean
}>()
collumns = ['room', 'hours', 'actions']
data: MatTableDataSource<{room: string, hours: string[]}> = new MatTableDataSource<{room: string, hours: string[]}>(); constructor(
collumns = ['room', 'hours'] private toolbar: ToolbarService,
private router: Router,
constructor (private toolbar: ToolbarService, private router: Router, private route: ActivatedRoute, private ac: AdminCommService) { private route: ActivatedRoute,
private ac: GradesService
) {
this.toolbar.comp = this this.toolbar.comp = this
this.toolbar.menu = [ this.toolbar.menu = [
{check: true, title: "Ocenianie", fn: "goBack", icon: "arrow_back"} { check: true, title: 'Ocenianie', fn: 'goBack', icon: 'arrow_back' },
] ]
} }
delete(room: string) {
this.ac.attendence.deleteRoom(room).subscribe(() => {
this.ngOnInit()
})
}
ngOnInit(): void { ngOnInit(): void {
this.ac.clean.attendence.getSummary().subscribe(v => { this.ac.attendence.getSummary().subscribe(v => {
this.data.data = v this.data.data = v
}) })
} }
goBack() { goBack() {
this.router.navigate(['../'], {relativeTo: this.route}) this.router.navigate(['../'], { relativeTo: this.route })
} }
} }

View File

@@ -1,8 +1,8 @@
:host { :host {
display: inline; display: inline;
} }
span { span {
padding: 2px; padding: 2px;
border-radius: 7.5%; border-radius: 7.5%;
} }

View File

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

View File

@@ -1,26 +1,27 @@
import { Component, Input } from '@angular/core'; import { Component, Input } from '@angular/core'
import * as moment from 'moment'; import { DateTime } from 'luxon'
@Component({ @Component({
selector: 'app-hour-display', selector: 'app-hour-display',
templateUrl: './hour-display.component.html', templateUrl: './hour-display.component.html',
styleUrl: './hour-display.component.scss' styleUrl: './hour-display.component.scss',
standalone: false,
}) })
export class HourDisplayComponent { export class HourDisplayComponent {
@Input() value = ""; @Input() value = ''
style () { style() {
if (/(0+[0-9]|1[0-9]|2[0-3]):(0+[0-9]|[1-5][0-9])/g.test(this.value)) { if (/(0+[0-9]|1[0-9]|2[0-3]):(0+[0-9]|[1-5][0-9])/g.test(this.value)) {
var diff = moment(this.value, 'HH:mm').diff(moment(), 'minutes'); var diff = DateTime.fromFormat(this.value, 'HH:mm').diffNow('minutes')
if (diff > 30) { if (diff.as('minutes') > 30) {
return { "background-color": "red" } return { 'background-color': 'red' }
} else if (diff > 0) { } else if (diff.as('minutes') > 0) {
return { "background-color": "yellow", "color": "black"} return { 'background-color': 'yellow', color: 'black' }
} else { } else {
return { "background-color": "green"} return { 'background-color': 'green' }
} }
} else { } else {
return { "color": "gray"} return { color: 'gray' }
} }
} }
} }

View File

@@ -11,6 +11,10 @@
</div> </div>
} }
</div> </div>
<mat-form-field>
<mat-label>Notatki</mat-label>
<input type="text" matInput formControlName="notes">
</mat-form-field>
</form> </form>
</mat-dialog-content> </mat-dialog-content>
<mat-dialog-actions> <mat-dialog-actions>

View File

@@ -1,23 +1,52 @@
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing'
import { AttendenceComponent } from './attendence.component'; import { AttendenceComponent } from './attendence.component'
import {
MAT_DIALOG_DATA,
MatDialogModule,
MatDialogRef,
} from '@angular/material/dialog'
import { MatFormFieldModule } from '@angular/material/form-field'
import { of } from 'rxjs'
import { FormsModule, ReactiveFormsModule } from '@angular/forms'
import { MatInputModule } from '@angular/material/input'
import { NoopAnimationsModule } from '@angular/platform-browser/animations'
describe('AttendenceComponent', () => { xdescribe('AttendenceComponent', () => {
let component: AttendenceComponent; let component: AttendenceComponent
let fixture: ComponentFixture<AttendenceComponent>; let fixture: ComponentFixture<AttendenceComponent>
beforeEach(async () => { beforeEach(async () => {
const acMock = {
clean: {
attendence: {
getUsers: jasmine.createSpy('getUsers').and.returnValue(of()),
},
},
}
await TestBed.configureTestingModule({ await TestBed.configureTestingModule({
declarations: [AttendenceComponent] declarations: [AttendenceComponent],
}) providers: [
.compileComponents(); { provide: MAT_DIALOG_DATA, useValue: {} },
{ provide: MatDialogRef, useValue: {} },
fixture = TestBed.createComponent(AttendenceComponent); // { provide: AdminCommService, useValue: acMock },
component = fixture.componentInstance; ],
fixture.detectChanges(); imports: [
}); MatDialogModule,
MatFormFieldModule,
FormsModule,
ReactiveFormsModule,
MatInputModule,
NoopAnimationsModule,
],
}).compileComponents()
fixture = TestBed.createComponent(AttendenceComponent)
component = fixture.componentInstance
fixture.detectChanges()
})
it('should create', () => { it('should create', () => {
expect(component).toBeTruthy(); expect(component).toBeTruthy()
}); })
}); })

View File

@@ -1,43 +1,54 @@
import { Component, Inject, OnInit } from '@angular/core'; import { Component, Inject, OnInit } from '@angular/core'
import { FormArray, FormBuilder, FormGroup } from '@angular/forms'; import { FormArray, FormBuilder, FormGroup } from '@angular/forms'
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog'; import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog'
import { AdminCommService } from '../../admin-comm.service'; import { GradesService } from '../grades.service'
@Component({ @Component({
selector: 'app-attendence', selector: 'app-attendence',
templateUrl: './attendence.component.html', templateUrl: './attendence.component.html',
styleUrl: './attendence.component.scss' styleUrl: './attendence.component.scss',
standalone: false,
}) })
export class AttendenceComponent implements OnInit { export class AttendenceComponent implements OnInit {
constructor(
constructor (private fb: FormBuilder, @Inject(MAT_DIALOG_DATA) public data: {room: string}, public dialogRef: MatDialogRef<AttendenceComponent>, private ac: AdminCommService) {} private fb: FormBuilder,
@Inject(MAT_DIALOG_DATA) public data: { room: string },
public dialogRef: MatDialogRef<AttendenceComponent>,
private ac: GradesService
) {}
ngOnInit(): void { ngOnInit(): void {
this.room = this.data.room this.room = this.data.room
this.ac.clean.attendence.getUsers(this.room).subscribe(query => { this.ac.attendence.getUsers(this.room).subscribe(query => {
query.users.forEach(v => { query.users.forEach(v => {
var att = query.attendence ? query.attendence.find(z => z.id == v._id) : false var att = query.attendence
this.users.push(this.fb.group({ ? query.attendence.auto.find(z => z.id == v._id)
id: v._id, : false
label: `${v.fname} ${v.surname}`, this.users.push(
att: this.fb.control(att), this.fb.group({
hour: this.fb.control(att ? att.hour : ""), id: v._id,
})) label: `${v.fname} ${v.surname}`,
att: this.fb.control(att),
hour: this.fb.control(att ? att.hour : ''),
})
)
}) })
this.form.get('notes')?.setValue(query.attendence?.notes)
}) })
} }
save() { save() {
this.dialogRef.close({ this.dialogRef.close({
room: this.room, room: this.room,
...this.form.value ...this.form.value,
}) })
} }
room: string = ""; room: string = ''
form: FormGroup = this.fb.group({ form: FormGroup = this.fb.group({
users: this.fb.array([]) users: this.fb.array([]),
notes: this.fb.control(''),
}) })
get users() { get users() {

View File

@@ -1,28 +1,34 @@
<app-date-selector [(date)]="date" [filter]="filter" (dateChange)="downloadData()"></app-date-selector> <app-date-selector [(date)]="date" [filter]="filter" (dateChange)="downloadData()"></app-date-selector>
<app-room-chooser [rooms]="rooms" (room)="roomNumber($event)"/> <app-room-chooser [rooms]="rooms" (room)="roomNumber($event)"/>
<form [formGroup]="form"> <form [formGroup]="form">
<p>Czystość pokoju {{room}} na dzień {{date.format("dddd")}}</p> <p>Czystość pokoju {{room}} na {{date().toFormat("cccc, D")}}</p>
<p>Ocena: {{grade}}</p> <p>Ocena: <span [appGradeColor]="grade">{{grade}}</span></p>
<div id="buttons"> <div id="buttons">
<button mat-mini-fab (click)="downloadData()" color="accent"><mat-icon>cancel</mat-icon></button> <button mat-mini-fab (click)="downloadData()" color="accent"><mat-icon>cancel</mat-icon></button>
<button mat-mini-fab (click)="attendence()" color="accent"><mat-icon>overview</mat-icon></button> <button mat-mini-fab (click)="attendence()" color="accent"><mat-icon>overview</mat-icon></button>
<button mat-mini-fab (click)="save()" color="accent"><mat-icon>save</mat-icon></button> <button mat-mini-fab (click)="save()" color="accent"><mat-icon>save</mat-icon></button>
<button mat-mini-fab color="warn" (click)="remove()" *ngIf="id"><mat-icon>delete</mat-icon></button> @if (id) {
<button mat-mini-fab color="warn" (click)="remove()"><mat-icon>delete</mat-icon></button>
}
</div>
@for (item of things.controls; track item; let i = $index) {
<div formArrayName="things" id="things">
<div formGroupName="{{i}}">
<mat-checkbox formControlName="cb" #cb>
<span control="label"></span>
@if (cb.checked) {
<span>
<button mat-icon-button (click)="group.sub(i)"><mat-icon>remove</mat-icon></button>
<span control="weight"></span>
<button mat-icon-button (click)="group.add(i)"><mat-icon>add</mat-icon></button>
</span>
}
</mat-checkbox>
</div>
</div> </div>
<div *ngFor="let item of things.controls; let i = index" formArrayName="things" id="things"> }
<div formGroupName="{{i}}"> <mat-form-field style="width: 100%;">
<mat-checkbox formControlName="cb" #cb> <mat-label>Dodatkowe uwagi</mat-label>
<span control="label"></span> <textarea matNativeControl cdkTextareaAutosize formControlName="tips"></textarea>
<span *ngIf="cb.checked"> </mat-form-field>
<button mat-icon-button (click)="group.sub(i)"><mat-icon>remove</mat-icon></button> </form>
<span control="weight"></span>
<button mat-icon-button (click)="group.add(i)"><mat-icon>add</mat-icon></button>
</span>
</mat-checkbox>
</div>
</div>
<mat-form-field style="width: 100%;">
<mat-label>Dodatkowe uwagi</mat-label>
<textarea matNativeControl cdkTextareaAutosize formControlName="tips"></textarea>
</mat-form-field>
</form>

View File

@@ -1,10 +1,10 @@
div#things { div#things {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
} }
div#buttons { div#buttons {
* { * {
margin: 0 2px 0 2px; margin: 0 2px 0 2px;
} }
} }

View File

@@ -1,23 +1,68 @@
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing'
import { GradesComponent } from './grades.component'; import { GradesComponent } from './grades.component'
import { RouterModule } from '@angular/router'
import { Component, EventEmitter, Input, Output } from '@angular/core'
import { MatIconModule } from '@angular/material/icon'
import { MatFormFieldModule } from '@angular/material/form-field'
import { of } from 'rxjs'
import { FormsModule, ReactiveFormsModule } from '@angular/forms'
import { MatInputModule } from '@angular/material/input'
import { NoopAnimationsModule } from '@angular/platform-browser/animations'
import { DateTime } from 'luxon'
describe('GradesComponent', () => { @Component({
let component: GradesComponent; selector: 'app-date-selector',
let fixture: ComponentFixture<GradesComponent>; template: '',
standalone: false,
})
class DateSelectorStub {
@Input() date: string = DateTime.now().toISODate()
@Output() dateChange = new EventEmitter<string>()
@Input() filter: (date: DateTime | null) => boolean = () => true
}
@Component({
selector: 'app-room-chooser',
template: '',
standalone: false,
})
class RoomSelectorStub {
@Input() rooms: string[] = []
@Output() room: EventEmitter<string> = new EventEmitter<string>()
}
xdescribe('GradesComponent', () => {
let component: GradesComponent
let fixture: ComponentFixture<GradesComponent>
let acMock
beforeEach(async () => { beforeEach(async () => {
acMock = {
clean: {
getConfig: jasmine.createSpy('getConfig').and.returnValue(of()),
},
}
await TestBed.configureTestingModule({ await TestBed.configureTestingModule({
imports: [GradesComponent] declarations: [GradesComponent, DateSelectorStub, RoomSelectorStub],
}) // providers: [{ provide: AdminCommService, useValue: acMock }],
.compileComponents(); imports: [
RouterModule.forRoot([]),
fixture = TestBed.createComponent(GradesComponent); MatIconModule,
component = fixture.componentInstance; MatFormFieldModule,
fixture.detectChanges(); FormsModule,
}); ReactiveFormsModule,
MatInputModule,
NoopAnimationsModule,
],
}).compileComponents()
fixture = TestBed.createComponent(GradesComponent)
component = fixture.componentInstance
fixture.detectChanges()
})
it('should create', () => { it('should create', () => {
expect(component).toBeTruthy(); expect(component).toBeTruthy()
}); })
}); })

View File

@@ -1,39 +1,46 @@
import { Component, OnDestroy, OnInit } from '@angular/core'; import { Component, OnDestroy, OnInit, signal } from '@angular/core'
import { AdminCommService } from '../admin-comm.service'; import { FormArray, FormBuilder } from '@angular/forms'
import * as moment from 'moment'; import { filterLook, weekendFilter } from 'src/app/util'
import { FormArray, FormBuilder } from '@angular/forms'; import { MatSnackBar } from '@angular/material/snack-bar'
import { weekendFilter } from 'src/app/fd.da'; import { ToolbarService } from '../toolbar/toolbar.service'
import { MatSnackBar } from '@angular/material/snack-bar'; import { ActivatedRoute, Router } from '@angular/router'
import { ToolbarService } from '../toolbar.service'; import { MatDialog } from '@angular/material/dialog'
import { ActivatedRoute, Router } from '@angular/router'; import { AttendenceComponent } from './attendence/attendence.component'
import { MatDialog } from '@angular/material/dialog'; import { DateTime } from 'luxon'
import { AttendenceComponent } from './attendence/attendence.component'; import { GradesService } from './grades.service'
@Component({ @Component({
selector: 'app-grades', selector: 'app-grades',
templateUrl: './grades.component.html', templateUrl: './grades.component.html',
styleUrl: './grades.component.scss' styleUrl: './grades.component.scss',
standalone: false,
}) })
export class GradesComponent implements OnInit, OnDestroy { export class GradesComponent implements OnInit, OnDestroy {
rooms!: string[] rooms!: string[]
room: string = "0"; room: string = '0'
date: moment.Moment;
grade: number = 6 grade: number = 6
gradeDate?: moment.Moment; gradeDate?: DateTime
id?: string id?: string
filter = weekendFilter filter = weekendFilter
date = signal<DateTime>(filterLook(this.filter, "behind", DateTime.now(), 7)!)
get notes(): { label: string, weight: number }[] { get notes(): { label: string; weight: number }[] {
var th = this.things.value as { cb: boolean, label: string, weight: number }[] var th = this.things.value as {
return th.filter((v) => v.cb).map((v) => { cb: boolean
return { ...v, cb: undefined } label: string
}) weight: number
}[]
return th
.filter(v => v.cb)
.map(v => {
return { ...v, cb: undefined }
})
} }
set notes(value: { label: string, weight: number }[]) { set notes(value: { label: string; weight: number }[]) {
var things = this.things.controls var things = this.things.controls
things.forEach((v) => { things.forEach(v => {
var thing = value.find((s) => s.label == v.get('label')?.value) var thing = value.find(s => s.label == v.get('label')?.value)
if (thing) { if (thing) {
v.get('cb')?.setValue(true) v.get('cb')?.setValue(true)
v.get('weight')?.setValue(thing.weight) v.get('weight')?.setValue(thing.weight)
@@ -44,22 +51,34 @@ export class GradesComponent implements OnInit, OnDestroy {
}) })
} }
constructor(private ac: AdminCommService, private fb: FormBuilder, private sb: MatSnackBar, private toolbar: ToolbarService, private router: Router, private route: ActivatedRoute, private dialog: MatDialog) { constructor(
this.date = moment.utc().startOf('day') private ac: GradesService,
if (!this.filter(this.date)) this.date.isoWeekday(8); private fb: FormBuilder,
private sb: MatSnackBar,
private toolbar: ToolbarService,
private router: Router,
private route: ActivatedRoute,
private dialog: MatDialog
) {
// if (!this.filter(this.date)) this.date.isoWeekday(8);
this.toolbar.comp = this this.toolbar.comp = this
this.toolbar.menu = [ this.toolbar.menu = [
{ title: "Podsumowanie", check: true, fn: "summary", icon: "analytics" }, {
{ title: "Obecność", check: true, fn: "attendenceSummary", icon: "overview"} title: 'Pokoje do sprawdzenia',
check: true,
fn: 'attendenceSummary',
icon: 'overview',
},
{ title: 'Podsumowanie', check: true, fn: 'summary', icon: 'analytics' },
] ]
this.form.valueChanges.subscribe((v) => { this.form.valueChanges.subscribe(v => {
this.calculate() this.calculate()
}) })
} }
form = this.fb.group({ form = this.fb.group({
things: this.fb.array([]), things: this.fb.array([]),
tips: this.fb.control("") tips: this.fb.control(''),
}) })
get things() { get things() {
@@ -67,21 +86,25 @@ export class GradesComponent implements OnInit, OnDestroy {
} }
summary() { summary() {
this.router.navigate(["summary"], { relativeTo: this.route }) this.router.navigate(['summary'], { relativeTo: this.route })
} }
attendenceSummary() { attendenceSummary() {
this.router.navigate(["attendenceSummary"], {relativeTo: this.route}) this.router.navigate(['attendenceSummary'], { relativeTo: this.route })
} }
ngOnInit(): void { ngOnInit(): void {
this.ac.clean.getConfig().subscribe((s) => { this.ac.getConfig().subscribe(s => {
this.rooms = s.rooms this.rooms = s.rooms
s.things.forEach((s) => this.things.push(this.fb.group({ s.things.forEach(s =>
cb: this.fb.control(false), this.things.push(
label: this.fb.control(s), this.fb.group({
weight: this.fb.control(1) cb: this.fb.control(false),
}))) label: this.fb.control(s),
weight: this.fb.control(1),
})
)
)
}) })
} }
@@ -91,19 +114,19 @@ export class GradesComponent implements OnInit, OnDestroy {
} }
downloadData() { downloadData() {
this.ac.clean.getClean(this.date, this.room).subscribe((v) => { this.ac.getClean(this.date(), this.room).subscribe(v => {
if (v) { if (v) {
this.notes = v.notes this.notes = v.notes
this.gradeDate = moment(v.gradeDate) this.gradeDate = DateTime.fromISO(v.gradeDate)
this.grade = v.grade this.grade = v.grade
this.id = v._id this.id = v._id
this.form.get("tips")?.setValue(v.tips) this.form.get('tips')?.setValue(v.tips)
} else { } else {
this.gradeDate = undefined this.gradeDate = undefined
this.grade = 6 this.grade = 6
this.notes = [] this.notes = []
this.id = undefined this.id = undefined
this.form.get("tips")?.setValue("") this.form.get('tips')?.setValue('')
} }
}) })
} }
@@ -132,26 +155,26 @@ export class GradesComponent implements OnInit, OnDestroy {
weight.setValue(weight.value - 1) weight.setValue(weight.value - 1)
} }
} }
} },
} }
save() { save() {
this.calculate() this.calculate()
var obj = { var obj = {
grade: this.grade, grade: this.grade,
date: this.date.toDate(), date: this.date,
room: this.room, room: this.room,
notes: this.notes, notes: this.notes,
tips: this.form.get("tips")?.value tips: this.form.get('tips')?.value,
} }
this.ac.clean.postClean(obj).subscribe((s) => { this.ac.postClean(obj).subscribe(s => {
this.sb.open("Zapisano!", undefined, { duration: 1500 }) this.sb.open('Zapisano!', undefined, { duration: 1500 })
this.downloadData() this.downloadData()
}) })
} }
remove() { remove() {
this.ac.clean.delete(this.id!).subscribe((s) => { this.ac.delete(this.id!).subscribe(s => {
if (s.status == 200) { if (s.status == 200) {
this.downloadData() this.downloadData()
} }
@@ -164,21 +187,35 @@ export class GradesComponent implements OnInit, OnDestroy {
} }
attendence() { attendence() {
this.dialog.open(AttendenceComponent, {data: {room: this.room}}).afterClosed().subscribe((v: {room: string, users: {att: boolean, id: string, hour: string}[]}) => { this.dialog
let x: {room: string, users: {id: string, hour?: string}[]} = { .open(AttendenceComponent, { data: { room: this.room } })
room: v.room, .afterClosed()
users: [] .subscribe(
} (v: {
v.users.forEach(i => { room: string
if (i.att && i.hour) { users: { att: boolean; id: string; hour: string }[]
x.users.push({id: i.id, hour: i.hour}) notes: string
}) => {
if (!v) return
let x: { room: string; users: { id: string; hour?: string }[] } = {
room: v.room,
users: [],
}
v.users.forEach(i => {
if (i.att && i.hour) {
x.users.push({ id: i.id, hour: i.hour })
}
})
this.ac.attendence
.postAttendence(x.room, { auto: x.users, notes: v.notes })
.subscribe(s => {
if (s.status == 200) {
this.sb.open('Zapisano obecność!', undefined, {
duration: 1500,
})
}
})
} }
}) )
this.ac.clean.attendence.postAttendence(x.room, x.users).subscribe((s) => {
if (s.status == 200) {
this.sb.open("Zapisano obecność!", undefined, {duration: 1500})
}
})
})
} }
} }

View File

@@ -0,0 +1,23 @@
import { TestBed } from '@angular/core/testing';
import { GradesService } from './grades.service';
import { provideHttpClient } from '@angular/common/http';
import { provideHttpClientTesting } from '@angular/common/http/testing';
describe('GradesService', () => {
let service: GradesService;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
provideHttpClient(),
provideHttpClientTesting()
]
});
service = TestBed.inject(GradesService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
});

View File

@@ -0,0 +1,93 @@
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { DateTime } from 'luxon';
import { Status } from 'src/app/types/status';
import { environment } from 'src/environments/environment';
@Injectable({
providedIn: 'root'
})
export class GradesService {
constructor(private http: HttpClient) { }
getConfig() {
return this.http.get<{ rooms: string[]; things: string[] }>(
environment.apiEndpoint + `/admin/clean/config`,
{ withCredentials: true }
)
}
getClean(date: DateTime, room: string) {
return this.http.get<{
_id: string
date: string
grade: number
gradeDate: string
notes: { label: string; weight: number }[]
room: string
tips: string
} | null>(environment.apiEndpoint + `/admin/clean/${date.toISODate()}/${room}`, {
withCredentials: true,
})
}
postClean(obj: Object) {
return this.http.post<Status>(
environment.apiEndpoint + `/admin/clean/`,
obj,
{ withCredentials: true }
)
}
delete(id: string) {
return this.http.delete<Status>(
environment.apiEndpoint + `/admin/clean/${id}`,
{ withCredentials: true }
)
}
summary = {
getSummary: (start: DateTime, end: DateTime) => {
return this.http.get<{ room: string; avg: number }[]>(
environment.apiEndpoint +
`/admin/clean/summary/${start.toISO()}/${end.toISO()}`,
{ withCredentials: true }
)
},
}
attendence = {
getUsers: (room: string) => {
return this.http.get<{
users: { fname: string; surname: string; _id: string }[]
attendence?: { auto: { id: string; hour?: string }[]; notes: string }
}>(environment.apiEndpoint + `/admin/clean/attendence/${room}`, {
withCredentials: true,
})
},
postAttendence: (
room: string,
attendence: { auto: { id: string; hour?: string }[]; notes: string }
) => {
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; 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,23 +1,52 @@
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing'
import { SummaryComponent } from './summary.component'; import { SummaryComponent } from './summary.component'
import { RouterModule } from '@angular/router'
import { MatFormFieldModule } from '@angular/material/form-field'
import { MatDatepickerModule } from '@angular/material/datepicker'
import { MatIconModule } from '@angular/material/icon'
import { of } from 'rxjs'
import { FormsModule, ReactiveFormsModule } from '@angular/forms'
import { MatTableModule } from '@angular/material/table'
import { NoopAnimationsModule } from '@angular/platform-browser/animations'
import { provideLuxonDateAdapter } from '@angular/material-luxon-adapter'
describe('SummaryComponent', () => { xdescribe('SummaryComponent', () => {
let component: SummaryComponent; let component: SummaryComponent
let fixture: ComponentFixture<SummaryComponent>; let fixture: ComponentFixture<SummaryComponent>
beforeEach(async () => { beforeEach(async () => {
const acMock = {
clean: {
summary: {
getSummary: jasmine.createSpy('getSummary').and.returnValue(of()),
},
},
}
await TestBed.configureTestingModule({ await TestBed.configureTestingModule({
imports: [SummaryComponent] declarations: [SummaryComponent],
}) providers: [
.compileComponents(); // { provide: AdminCommService, useValue: acMock },
provideLuxonDateAdapter(),
fixture = TestBed.createComponent(SummaryComponent); ],
component = fixture.componentInstance; imports: [
fixture.detectChanges(); RouterModule.forRoot([]),
}); MatFormFieldModule,
MatDatepickerModule,
MatIconModule,
FormsModule,
ReactiveFormsModule,
MatTableModule,
NoopAnimationsModule,
],
}).compileComponents()
fixture = TestBed.createComponent(SummaryComponent)
component = fixture.componentInstance
fixture.detectChanges()
})
it('should create', () => { it('should create', () => {
expect(component).toBeTruthy(); expect(component).toBeTruthy()
}); })
}); })

View File

@@ -1,57 +1,68 @@
import { Component, OnDestroy, OnInit, ViewChild } from '@angular/core'; 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 { ActivatedRoute, Router } from '@angular/router'
import { AdminCommService } from '../../admin-comm.service'; import { MatTableDataSource } from '@angular/material/table'
import * as moment from 'moment'; import { FormBuilder } from '@angular/forms'
import { MatTableDataSource } from '@angular/material/table'; import { MatSort } from '@angular/material/sort'
import { FormBuilder } from '@angular/forms'; import { DateTime } from 'luxon'
import { MatSort } from '@angular/material/sort'; import { GradesService } from '../grades.service'
@Component({ @Component({
selector: 'app-summary', selector: 'app-summary',
templateUrl: './summary.component.html', templateUrl: './summary.component.html',
styleUrl: './summary.component.scss' styleUrl: './summary.component.scss',
standalone: false,
}) })
export class SummaryComponent implements OnInit, OnDestroy { export class SummaryComponent implements OnInit, OnDestroy {
data: MatTableDataSource<{ room: string; avg: number }> =
data: MatTableDataSource<{room: string, avg: number}> = new MatTableDataSource<{room: string, avg: number}>(); new MatTableDataSource<{ room: string; avg: number }>()
collumns = ['room', 'avg'] collumns = ['room', 'avg']
dateSelector = this.fb.group({ dateSelector = this.fb.group({
start: this.fb.control(moment.utc().startOf('day')), start: this.fb.control(DateTime.utc().startOf('day')),
end: this.fb.control(moment.utc().endOf('day')) end: this.fb.control(DateTime.utc().endOf('day')),
}) })
@ViewChild(MatSort, {static: false}) set content(sort: MatSort) { @ViewChild(MatSort, { static: false }) set content(sort: MatSort) {
this.data.sort = sort this.data.sort = sort
} }
constructor (private toolbar: ToolbarService, private router: Router, private route: ActivatedRoute, private ac: AdminCommService, private fb: FormBuilder) { constructor(
private toolbar: ToolbarService,
private router: Router,
private route: ActivatedRoute,
private ac: GradesService,
private fb: FormBuilder
) {
this.toolbar.comp = this this.toolbar.comp = this
this.toolbar.menu = [ this.toolbar.menu = [
{check: true, title: "Ocenianie", fn: "goBack", icon: "arrow_back"} { check: true, title: 'Ocenianie', fn: 'goBack', icon: 'arrow_back' },
] ]
this.dateSelector.valueChanges.subscribe((v) => { this.dateSelector.valueChanges.subscribe(v => {
this.download() this.download()
}) })
} }
ngOnInit(): void { ngOnInit(): void {
this.download() this.download()
} }
download() { download() {
this.ac.clean.summary.getSummary(this.dateSelector.get('start')?.value!.startOf('day')!, this.dateSelector.get('end')?.value!.endOf('day')!).subscribe((v) => { this.ac.summary
this.data.data = v .getSummary(
}) this.dateSelector.get('start')?.value!.startOf('day')!,
this.dateSelector.get('end')?.value!.endOf('day')!
)
.subscribe(v => {
this.data.data = v
})
} }
goBack() { goBack() {
this.router.navigate(['../'], {relativeTo: this.route}) this.router.navigate(['../'], { relativeTo: this.route })
} }
ngOnDestroy(): void { ngOnDestroy(): void {
this.toolbar.comp = undefined this.toolbar.comp = undefined
this.toolbar.menu = undefined this.toolbar.menu = undefined
} }
} }

View File

@@ -1,9 +1,11 @@
<button mat-raised-button color="accent" (click)="newGroup()">Nowa grupa</button> <button mat-raised-button color="accent" (click)="newGroup()">Nowa grupa</button>
<mat-card *ngFor="let item of groups"> @for (item of groups; track item) {
<mat-card>
<mat-card-header> <mat-card-header>
<mat-card-title contenteditable appCe (edit)="nameEdit(item._id, $event)">{{item.name}}</mat-card-title> <mat-card-title contenteditable appCe (edit)="nameEdit(item._id, $event)">{{item.name}}</mat-card-title>
</mat-card-header> </mat-card-header>
<mat-card-actions> <mat-card-actions>
<button mat-button color="warn" (click)="remove(item._id)">Usuń</button> <button mat-button color="warn" (click)="remove(item._id)">Usuń</button>
</mat-card-actions> </mat-card-actions>
</mat-card> </mat-card>
}

View File

@@ -1,12 +1,12 @@
:host { :host {
display: flex; display: flex;
} }
mat-card { mat-card {
margin: 15px; margin: 15px;
padding: 1ch; padding: 1ch;
} }
mat-card-title { mat-card-title {
font-size: 1.5rem; font-size: 1.5rem;
} }

View File

@@ -1,21 +1,28 @@
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing'
import { GroupsComponent } from './groups.component'; import { GroupsComponent } from './groups.component'
import { of } from 'rxjs'
describe('GroupsComponent', () => { xdescribe('GroupsComponent', () => {
let component: GroupsComponent; let component: GroupsComponent
let fixture: ComponentFixture<GroupsComponent>; let fixture: ComponentFixture<GroupsComponent>
beforeEach(() => { beforeEach(() => {
const acMock = {
groups: {
getGroups: jasmine.createSpy('getGroups').and.returnValue(of()),
},
}
TestBed.configureTestingModule({ TestBed.configureTestingModule({
declarations: [GroupsComponent] declarations: [GroupsComponent],
}); // providers: [{ provide: AdminCommService, useValue: acMock }],
fixture = TestBed.createComponent(GroupsComponent); })
component = fixture.componentInstance; fixture = TestBed.createComponent(GroupsComponent)
fixture.detectChanges(); component = fixture.componentInstance
}); fixture.detectChanges()
})
it('should create', () => { it('should create', () => {
expect(component).toBeTruthy(); expect(component).toBeTruthy()
}); })
}); })

View File

@@ -1,20 +1,24 @@
import { Component, OnInit } from '@angular/core'; import { Component, OnInit } from '@angular/core'
import { AdminCommService } from '../admin-comm.service'; import { Group } from 'src/app/types/group'
import { Group } from 'src/app/types/group'; import { Status } from 'src/app/types/status'
import { Status } from 'src/app/types/status'; import { MatDialog } from '@angular/material/dialog'
import { MatDialog } from '@angular/material/dialog'; import { RemoveConfirmComponent } from './remove-confirm/remove-confirm.component'
import { RemoveConfirmComponent } from './remove-confirm/remove-confirm.component'; import { GroupsService } from './groups.service'
@Component({ @Component({
selector: 'app-groups', selector: 'app-groups',
templateUrl: './groups.component.html', templateUrl: './groups.component.html',
styleUrls: ['./groups.component.scss'] styleUrls: ['./groups.component.scss'],
standalone: false,
}) })
export class GroupsComponent implements OnInit { export class GroupsComponent implements OnInit {
groups?: Group[] groups?: Group[]
constructor (protected readonly acs: AdminCommService, private readonly dialog: MatDialog) {} constructor(
protected readonly acs: GroupsService,
private readonly dialog: MatDialog
) {}
ngOnInit(): void { ngOnInit(): void {
this.acs.groups.getGroups().subscribe((v) => { this.acs.getGroups().subscribe(v => {
this.groups = v this.groups = v
}) })
} }
@@ -25,36 +29,41 @@ export class GroupsComponent implements OnInit {
} }
} }
get groupOptions(): {id: string, text: string}[] { get groupOptions(): { id: string; text: string }[] {
return this.groups!.map((v)=> {return {id: v._id as string, text: v.name as string}}) return this.groups!.map(v => {
return { id: v._id as string, text: v.name as string }
})
} }
protected getId(g: Group[] | undefined) { protected getId(g: Group[] | undefined) {
if (!g) return undefined if (!g) return undefined
return g.map((v)=>v._id) return g.map(v => v._id)
} }
groupNames(groups: Group[]) { groupNames(groups: Group[]) {
return groups.flatMap((g) => g.name) return groups.flatMap(g => g.name)
} }
protected nameEdit(id: string, name: string | string[]) { protected nameEdit(id: string, name: string | string[]) {
name = name as string name = name as string
this.acs.groups.editName(id, name).subscribe((s) => this.refreshIfGood(s)) this.acs.editName(id, name).subscribe(s => this.refreshIfGood(s))
} }
protected newGroup() { protected newGroup() {
let name = prompt("Nazwa grupy") let name = prompt('Nazwa grupy')
if (name) { if (name) {
this.acs.groups.newGroup(name).subscribe((s) => this.refreshIfGood(s)) this.acs.newGroup(name).subscribe(s => this.refreshIfGood(s))
} }
} }
protected remove(id: string) { protected remove(id: string) {
this.dialog.open(RemoveConfirmComponent).afterClosed().subscribe((v) => { this.dialog
if (v) { .open(RemoveConfirmComponent)
this.acs.groups.remove(id).subscribe((s) => this.refreshIfGood(s)) .afterClosed()
} .subscribe(v => {
}) if (v) {
this.acs.remove(id).subscribe(s => this.refreshIfGood(s))
}
})
} }
} }

View File

@@ -0,0 +1,23 @@
import { TestBed } from '@angular/core/testing';
import { GroupsService } from './groups.service';
import { provideHttpClient } from '@angular/common/http';
import { provideHttpClientTesting } from '@angular/common/http/testing';
describe('GroupsService', () => {
let service: GroupsService;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
provideHttpClient(),
provideHttpClientTesting()
]
});
service = TestBed.inject(GroupsService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
});

View File

@@ -0,0 +1,46 @@
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Group } from 'src/app/types/group';
import { Status } from 'src/app/types/status';
import { environment } from 'src/environments/environment';
@Injectable({
providedIn: 'root'
})
export class GroupsService {
constructor(private http: HttpClient) { }
getGroups() {
return this.http.get<Group[]>(environment.apiEndpoint + `/admin/groups`, {
withCredentials: true,
})
}
newGroup(name: string) {
return this.http.post<Status>(
environment.apiEndpoint + `/admin/groups`,
{ name: name },
{ withCredentials: true }
)
}
editName(id: string, name: string) {
return this.putGroups(id, { name: name.trim() })
}
remove(id: string) {
return this.http.delete<Status>(
environment.apiEndpoint + `/admin/groups/${id}`,
{ withCredentials: true }
)
}
private putGroups(id: string, update: Partial<Group>) {
return this.http.put<Status>(
environment.apiEndpoint + `/admin/groups/${id}`,
update,
{ withCredentials: true }
)
}
}

View File

@@ -1,21 +1,23 @@
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing'
import { RemoveConfirmComponent } from './remove-confirm.component'; import { RemoveConfirmComponent } from './remove-confirm.component'
import { MatDialogModule } from '@angular/material/dialog'
describe('RemoveConfirmComponent', () => { describe('RemoveConfirmComponent', () => {
let component: RemoveConfirmComponent; let component: RemoveConfirmComponent
let fixture: ComponentFixture<RemoveConfirmComponent>; let fixture: ComponentFixture<RemoveConfirmComponent>
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
declarations: [RemoveConfirmComponent] declarations: [RemoveConfirmComponent],
}); imports: [MatDialogModule],
fixture = TestBed.createComponent(RemoveConfirmComponent); })
component = fixture.componentInstance; fixture = TestBed.createComponent(RemoveConfirmComponent)
fixture.detectChanges(); component = fixture.componentInstance
}); fixture.detectChanges()
})
it('should create', () => { it('should create', () => {
expect(component).toBeTruthy(); expect(component).toBeTruthy()
}); })
}); })

View File

@@ -1,10 +1,9 @@
import { Component } from '@angular/core'; import { Component } from '@angular/core'
@Component({ @Component({
selector: 'app-remove-confirm', selector: 'app-remove-confirm',
templateUrl: './remove-confirm.component.html', templateUrl: './remove-confirm.component.html',
styleUrls: ['./remove-confirm.component.scss'] styleUrls: ['./remove-confirm.component.scss'],
standalone: false,
}) })
export class RemoveConfirmComponent { export class RemoveConfirmComponent {}
}

View File

@@ -1,42 +1,46 @@
<div id="upper-bar"> <div id="upper-bar">
<mat-form-field> <mat-form-field>
<mat-label>Wyszukaj</mat-label> <mat-label>Wyszukaj</mat-label>
<input matInput (keyup)="filter($event)"> <input matInput (keyup)="filter($event)">
</mat-form-field> </mat-form-field>
<mat-chip-listbox [(ngModel)]="filters" multiple> <mat-chip-listbox [(ngModel)]="filters" multiple>
<mat-chip-option value="showAll">Pokaż wszystko</mat-chip-option> <mat-chip-option value="showAll">Pokaż wszystko</mat-chip-option>
</mat-chip-listbox> </mat-chip-listbox>
<button mat-icon-button (click)="new()"><mat-icon>add</mat-icon></button> <button mat-icon-button (click)="new()"><mat-icon>add</mat-icon></button>
</div> </div>
<mat-spinner *ngIf="loading"></mat-spinner> @if (loading) {
<mat-spinner color="accent"></mat-spinner>
}
<table mat-table [dataSource]="keys"> <table mat-table [dataSource]="keys">
<div matColumnDef="room"> <div matColumnDef="room">
<th mat-header-cell *matHeaderCellDef>Sala</th> <th mat-header-cell *matHeaderCellDef>Sala</th>
<td mat-cell *matCellDef="let element">{{element.room}}</td> <td mat-cell *matCellDef="let element">{{element.room}}</td>
</div> </div>
<div matColumnDef="whom"> <div matColumnDef="whom">
<th mat-header-cell *matHeaderCellDef>Wypożyczający</th> <th mat-header-cell *matHeaderCellDef>Wypożyczający</th>
<td mat-cell *matCellDef="let element">{{element.whom.uname}}</td> <td mat-cell *matCellDef="let element">{{element.whom.uname}}</td>
</div> </div>
<div matColumnDef="borrow"> <div matColumnDef="borrow">
<th mat-header-cell *matHeaderCellDef>Data wypożyczenia</th> <th mat-header-cell *matHeaderCellDef>Data wypożyczenia</th>
<td mat-cell *matCellDef="let element">{{element.borrow.format("HH:mm, ddd D.MM.")}}</td> <td mat-cell *matCellDef="let element">{{element.borrow.format("HH:mm, ddd D.MM.")}}</td>
</div> </div>
<div matColumnDef="tb"> <div matColumnDef="tb">
<th mat-header-cell *matHeaderCellDef>Data zwrotu</th> <th mat-header-cell *matHeaderCellDef>Data zwrotu</th>
<td mat-cell *matCellDef="let element"> <td mat-cell *matCellDef="let element">
@if (element.tb) { @if (element.tb) {
{{element.tb.format("HH:mm, ddd D.MM.")}} {{element.tb.format("HH:mm, ddd D.MM.")}}
} }
</td> </td>
</div> </div>
<div matColumnDef="actions"> <div matColumnDef="actions">
<th mat-header-cell *matHeaderCellDef>Akcje</th> <th mat-header-cell *matHeaderCellDef>Akcje</th>
<td mat-cell *matCellDef="let element"> <td mat-cell *matCellDef="let element">
<button mat-mini-fab (click)="tb(element._id)" *ngIf="!element.tb"><mat-icon>person_cancel</mat-icon></button> @if (!element.tb) {
</td> <button mat-mini-fab (click)="tb(element._id)"><mat-icon>person_cancel</mat-icon></button>
</div> }
<tr mat-header-row *matHeaderRowDef="collumns"></tr> </td>
<tr mat-row *matRowDef="let row; columns: collumns"></tr> </div>
<tr mat-header-row *matHeaderRowDef="collumns"></tr>
<tr mat-row *matRowDef="let row; columns: collumns"></tr>
</table> </table>
<mat-paginator pageSize="9" [pageSizeOptions]="[9, 15, 20, 50, 160]"></mat-paginator> <mat-paginator pageSize="9" [pageSizeOptions]="[9, 15, 20, 50, 160]"></mat-paginator>

View File

@@ -1,5 +1,5 @@
#upper-bar { #upper-bar {
display: flex; display: flex;
align-items: baseline; align-items: baseline;
gap: 4pt; gap: 4pt;
} }

View File

@@ -1,23 +1,50 @@
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing'
import { AdminKeyComponent } from './key.component'; import { AdminKeyComponent } from './key.component'
import { of } from 'rxjs'
import { MatFormFieldModule } from '@angular/material/form-field'
import { MatChipsModule } from '@angular/material/chips'
import { MatIconModule } from '@angular/material/icon'
import { MatPaginatorModule } from '@angular/material/paginator'
import { FormsModule } from '@angular/forms'
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner'
import { MatTableModule } from '@angular/material/table'
import { MatInputModule } from '@angular/material/input'
import { NoopAnimationsModule } from '@angular/platform-browser/animations'
describe('KeyComponent', () => { xdescribe('AdminKeyComponent', () => {
let component: AdminKeyComponent; let component: AdminKeyComponent
let fixture: ComponentFixture<AdminKeyComponent>; let fixture: ComponentFixture<AdminKeyComponent>
let acMock
beforeEach(async () => { beforeEach(async () => {
acMock = {
keys: {
getKeys: jasmine.createSpy('getKeys').and.returnValue(of()),
},
}
await TestBed.configureTestingModule({ await TestBed.configureTestingModule({
imports: [AdminKeyComponent] declarations: [AdminKeyComponent],
}) // providers: [{ provide: AdminCommService, useValue: acMock }],
.compileComponents(); imports: [
MatFormFieldModule,
fixture = TestBed.createComponent(AdminKeyComponent); MatChipsModule,
component = fixture.componentInstance; MatIconModule,
fixture.detectChanges(); MatPaginatorModule,
}); FormsModule,
MatProgressSpinnerModule,
MatTableModule,
MatInputModule,
NoopAnimationsModule,
],
}).compileComponents()
fixture = TestBed.createComponent(AdminKeyComponent)
component = fixture.componentInstance
fixture.detectChanges()
})
it('should create', () => { it('should create', () => {
expect(component).toBeTruthy(); expect(component).toBeTruthy()
}); })
}); })

View File

@@ -1,47 +1,50 @@
import { AfterViewInit, Component, OnInit, ViewChild } from '@angular/core'; import { AfterViewInit, Component, OnInit, ViewChild } from '@angular/core'
import { MatPaginator } from '@angular/material/paginator'; import { MatPaginator } from '@angular/material/paginator'
import { MatTableDataSource } from '@angular/material/table'; import { MatTableDataSource } from '@angular/material/table'
import * as moment from 'moment'; import { AKey } from 'src/app/types/key'
import { AKey } from 'src/app/types/key'; import { MatDialog } from '@angular/material/dialog'
import { AdminCommService } from '../admin-comm.service'; import { NewKeyComponent } from './new-key/new-key.component'
import { FormControl } from '@angular/forms'; import { catchError, throwError } from 'rxjs'
import { MatDialog } from '@angular/material/dialog'; import { MatSnackBar } from '@angular/material/snack-bar'
import { NewKeyComponent } from './new-key/new-key.component'; import { KeyService } from './key.service'
import { catchError, throwError } from 'rxjs';
import { MatSnackBar } from '@angular/material/snack-bar';
@Component({ @Component({
selector: 'app-admin-key', selector: 'app-admin-key',
templateUrl: './key.component.html', templateUrl: './key.component.html',
styleUrl: './key.component.scss' styleUrl: './key.component.scss',
standalone: false,
}) })
export class AdminKeyComponent implements AfterViewInit, OnInit { export class AdminKeyComponent implements AfterViewInit, OnInit {
keys: MatTableDataSource<AKey> = new MatTableDataSource<AKey>(); keys: MatTableDataSource<AKey> = new MatTableDataSource<AKey>()
pureData: AKey[] = [] pureData: AKey[] = []
private _filters: string[] = []; private _filters: string[] = []
public get filters(): string[] { public get filters(): string[] {
return this._filters; return this._filters
} }
collumns = ['room', 'whom', 'borrow', 'tb', 'actions'] collumns = ['room', 'whom', 'borrow', 'tb', 'actions']
public set filters(value: string[]) { public set filters(value: string[]) {
if (value.includes("showAll")) { if (value.includes('showAll')) {
this.collumns = ['room', 'whom', 'borrow', 'tb', 'actions'] this.collumns = ['room', 'whom', 'borrow', 'tb', 'actions']
} else { } else {
this.collumns = ['room', 'whom', 'borrow', 'actions'] this.collumns = ['room', 'whom', 'borrow', 'actions']
} }
this._filters = value; this._filters = value
this.transformData(); this.transformData()
} }
loading = true loading = true
@ViewChild(MatPaginator) paginator!: MatPaginator @ViewChild(MatPaginator) paginator!: MatPaginator
constructor (private ac: AdminCommService, private dialog: MatDialog, private sb: MatSnackBar) { constructor(
private ac: KeyService,
private dialog: MatDialog,
private sb: MatSnackBar
) {
this.filters = [] this.filters = []
} }
fetchData() { fetchData() {
this.loading = true this.loading = true
this.ac.keys.getKeys().subscribe((r) => { this.ac.getKeys().subscribe(r => {
this.loading = false this.loading = false
this.pureData = r this.pureData = r
this.transformData() this.transformData()
@@ -50,45 +53,53 @@ export class AdminKeyComponent implements AfterViewInit, OnInit {
transformData() { transformData() {
var finalData: AKey[] = this.pureData var finalData: AKey[] = this.pureData
if (!this.filters.includes('showAll')) finalData = finalData.filter((v) => v.tb == undefined) if (!this.filters.includes('showAll'))
finalData = finalData.filter(v => v.tb == undefined)
this.keys.data = finalData this.keys.data = finalData
} }
filter(event: Event) { filter(event: Event) {
const value = (event.target as HTMLInputElement).value const value = (event.target as HTMLInputElement).value
this.keys.filter = value.toLowerCase().trim() this.keys.filter = value.toLowerCase().trim()
} }
ngAfterViewInit(): void { ngAfterViewInit(): void {
this.keys.paginator = this.paginator this.keys.paginator = this.paginator
} }
ngOnInit(): void { ngOnInit(): void {
this.fetchData() this.fetchData()
// [
// {room: "Kawiarenka", borrow: moment().subtract(15, "minutes"), whom: {_id: "test", room: 303, uname: "sk"}}
// ]
} }
new() { new() {
this.dialog.open(NewKeyComponent).afterClosed().subscribe(v => { this.dialog
if (v) { .open(NewKeyComponent)
this.ac.keys.postKey(v.room, v.user).pipe(catchError((err,caught)=>{ .afterClosed()
if (err.status == 404) { .subscribe(v => {
this.sb.open("Nie znaleziono użytkownika", undefined, {duration: 2500}) if (v) {
} this.ac
return throwError(() => new Error(err.message)) .postKey(v.room, v.user)
})).subscribe((s) => { .pipe(
if (s.status == 201) { catchError((err, caught) => {
this.fetchData() if (err.status == 404) {
} this.sb.open('Nie znaleziono użytkownika', undefined, {
}) duration: 2500,
} })
}) }
return throwError(() => new Error(err.message))
})
)
.subscribe(s => {
if (s.status == 201) {
this.fetchData()
}
})
}
})
} }
tb(id: string) { tb(id: string) {
this.ac.keys.returnKey(id).subscribe((r) => { this.ac.returnKey(id).subscribe(r => {
if (r.status == 200) { if (r.status == 200) {
this.fetchData() this.fetchData()
} }

View File

@@ -0,0 +1,23 @@
import { TestBed } from '@angular/core/testing';
import { KeyService } from './key.service';
import { provideHttpClient } from '@angular/common/http';
import { provideHttpClientTesting } from '@angular/common/http/testing';
describe('KeyService', () => {
let service: KeyService;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
provideHttpClient(),
provideHttpClientTesting()
]
});
service = TestBed.inject(KeyService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
});

View File

@@ -0,0 +1,62 @@
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { DateTime } from 'luxon';
import { map } from 'rxjs';
import { AKey } from 'src/app/types/key';
import { Status } from 'src/app/types/status';
import { environment } from 'src/environments/environment';
@Injectable({
providedIn: 'root'
})
export class KeyService {
constructor(
private http: HttpClient
) { }
getKeys() {
return this.http
.get<
(Omit<AKey, 'borrow' | 'tb'> & { borrow: string; tb?: string })[]
>(environment.apiEndpoint + `/admin/keys`, { withCredentials: true })
.pipe(
map(v => {
return v.map(r => {
let newkey: any = { ...r }
newkey.borrow = DateTime.fromISO(r.borrow!)
if (newkey.tb) newkey.tb = DateTime.fromISO(r.tb!)
return newkey as AKey
})
})
)
}
avalKeys() {
return this.http.get<string[]>(
environment.apiEndpoint + `/admin/keys/available`,
{ withCredentials: true }
)
}
postKey(room: string, uname: string) {
return this.http.post<Status>(
environment.apiEndpoint + `/admin/keys/`,
{ room: room, whom: uname },
{ withCredentials: true }
)
}
returnKey(id: string) {
return this.putKeys(id, { tb: DateTime.now() })
}
private putKeys(id: string, update: Partial<AKey>) {
return this.http.put<Status>(
environment.apiEndpoint + `/admin/keys/${id}`,
update,
{ withCredentials: true }
)
}
}

View File

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

View File

@@ -1,4 +1,4 @@
form { form {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
} }

View File

@@ -1,23 +1,98 @@
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing'
import { NewKeyComponent } from './new-key.component'; import { NewKeyComponent } from './new-key.component'
import { MatDialogModule, MatDialogRef } from '@angular/material/dialog'
import {
MatFormFieldControl,
MatFormFieldModule,
} from '@angular/material/form-field'
import { MatSelectModule } from '@angular/material/select'
import { Component, forwardRef, Optional, Self } from '@angular/core'
import { Observable, of } from 'rxjs'
import {
AbstractControlDirective,
ControlValueAccessor,
FormsModule,
NG_VALUE_ACCESSOR,
NgControl,
ReactiveFormsModule,
} from '@angular/forms'
import { NoopAnimationsModule } from '@angular/platform-browser/animations'
describe('NewKeyComponent', () => { @Component({
let component: NewKeyComponent; selector: 'app-user-search',
let fixture: ComponentFixture<NewKeyComponent>; template: '',
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => UserSearchStub),
multi: true,
},
{
provide: MatFormFieldControl,
useExisting: UserSearchStub,
},
],
standalone: false,
})
class UserSearchStub
implements ControlValueAccessor, MatFormFieldControl<never>
{
value: null = null
stateChanges: Observable<void> = of()
id: string = ''
placeholder: string = ''
ngControl: NgControl | AbstractControlDirective | null = null
focused: boolean = false
empty: boolean = true
shouldLabelFloat: boolean = true
required: boolean = false
disabled: boolean = false
errorState: boolean = false
controlType?: string | undefined
autofilled?: boolean | undefined
userAriaDescribedBy?: string | undefined
setDescribedByIds(ids: string[]): void {}
onContainerClick(event: MouseEvent): void {}
writeValue(obj: any): void {}
registerOnChange(fn: any): void {}
registerOnTouched(fn: any): void {}
setDisabledState?(isDisabled: boolean): void {}
}
xdescribe('NewKeyComponent', () => {
let component: NewKeyComponent
let fixture: ComponentFixture<NewKeyComponent>
let acMock
beforeEach(async () => { beforeEach(async () => {
acMock = {
keys: {
avalKeys: jasmine.createSpy('avalKeys').and.returnValue(of()),
},
}
await TestBed.configureTestingModule({ await TestBed.configureTestingModule({
imports: [NewKeyComponent] declarations: [NewKeyComponent, UserSearchStub],
}) providers: [
.compileComponents(); // { provide: AdminCommService, useValue: acMock },
{ provide: MatDialogRef, useValue: {} },
fixture = TestBed.createComponent(NewKeyComponent); ],
component = fixture.componentInstance; imports: [
fixture.detectChanges(); MatDialogModule,
}); MatFormFieldModule,
MatSelectModule,
FormsModule,
ReactiveFormsModule,
NoopAnimationsModule,
],
}).compileComponents()
fixture = TestBed.createComponent(NewKeyComponent)
component = fixture.componentInstance
fixture.detectChanges()
})
it('should create', () => { it('should create', () => {
expect(component).toBeTruthy(); expect(component).toBeTruthy()
}); })
}); })

View File

@@ -1,49 +1,36 @@
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 { MatDialogRef } from '@angular/material/dialog'; import { FormControl, FormGroup } from '@angular/forms'
import { FormControl, FormGroup } from '@angular/forms'; import { UserSearchResult } from 'src/app/commonComponents/user-search/user-search.component'
import { startWith } from 'rxjs'; import { KeyService } from '../key.service'
@Component({ @Component({
selector: 'app-new-key', selector: 'app-new-key',
templateUrl: './new-key.component.html', templateUrl: './new-key.component.html',
styleUrl: './new-key.component.scss' styleUrl: './new-key.component.scss',
standalone: false,
}) })
export class NewKeyComponent implements OnInit { export class NewKeyComponent implements OnInit {
// @ViewChild('input') input!: ElementRef<HTMLInputElement>
rooms: string[] = [] rooms: string[] = []
form = new FormGroup({ form = new FormGroup({
room: new FormControl<string>(""), room: new FormControl<string>(''),
user: new FormControl<string>("") user: new FormControl<UserSearchResult | null>(null),
}) })
unames: any[] = [] unames: any[] = []
constructor ( private ac: AdminCommService, public dialogRef: MatDialogRef<NewKeyComponent> ) {} constructor(
private ac: KeyService,
public dialogRef: MatDialogRef<NewKeyComponent>
) {}
ngOnInit(): void { ngOnInit(): void {
this.ac.keys.avalKeys().subscribe((v) => { this.ac.avalKeys().subscribe(v => {
this.rooms = v 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() { send() {
if (this.form.valid) { if (this.form.valid) {
this.dialogRef.close(this.form.value) this.dialogRef.close(this.form.value)
} else {
this.form.controls['user'].setErrors({unf: true})
} }
} }
} }

View File

@@ -1,4 +1,4 @@
<h1 mat-dialog-title>Dodawanie</h1> <h1 mat-dialog-title>Tworzenie wpisów do jadłospisu</h1>
<mat-dialog-content> <mat-dialog-content>
<mat-radio-group [(ngModel)]="type"> <mat-radio-group [(ngModel)]="type">
<mat-radio-button value="day">Dzień</mat-radio-button> <mat-radio-button value="day">Dzień</mat-radio-button>
@@ -28,6 +28,6 @@
</div> </div>
</mat-dialog-content> </mat-dialog-content>
<mat-dialog-actions> <mat-dialog-actions>
<button mat-raised-button color="accent" (click)="submit()">Wyślij</button> <button mat-raised-button color="accent" (click)="submit()">Utwórz pozycje</button>
<button mat-button mat-dialog-close>Anuluj</button> <button mat-button mat-dialog-close>Anuluj</button>
</mat-dialog-actions> </mat-dialog-actions>

View File

@@ -0,0 +1,39 @@
import { ComponentFixture, TestBed } from '@angular/core/testing'
import { MenuAddComponent } from './menu-add.component'
import {
MAT_DIALOG_DATA,
MatDialogModule,
MatDialogRef,
} from '@angular/material/dialog'
import { MatRadioModule } from '@angular/material/radio'
import { FormsModule, ReactiveFormsModule } from '@angular/forms'
describe('MenuAddComponent', () => {
let component: MenuAddComponent
let fixture: ComponentFixture<MenuAddComponent>
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [MenuAddComponent],
providers: [
{ provide: MAT_DIALOG_DATA, useValue: {} },
{ provide: MatDialogRef, useValue: {} },
],
imports: [
MatDialogModule,
MatRadioModule,
ReactiveFormsModule,
FormsModule,
],
}).compileComponents()
fixture = TestBed.createComponent(MenuAddComponent)
component = fixture.componentInstance
fixture.detectChanges()
})
it('should create', () => {
expect(component).toBeTruthy()
})
})

View File

@@ -0,0 +1,61 @@
import { Component, signal } from '@angular/core'
import { MenuUploadComponent } from '../menu-upload/menu-upload.component'
import { MatDialog, MatDialogRef } from '@angular/material/dialog'
import { FDSelection } from 'src/app/fd.da'
import { FormControl, FormGroup } from '@angular/forms'
import { MAT_DATE_RANGE_SELECTION_STRATEGY } from '@angular/material/datepicker'
import { DateTime } from 'luxon'
import { weekendFilter } from 'src/app/util'
@Component({
selector: 'app-menu-add',
templateUrl: './menu-add.component.html',
styleUrl: './menu-add.component.scss',
providers: [
{ provide: MAT_DATE_RANGE_SELECTION_STRATEGY, useClass: FDSelection },
],
standalone: false,
})
export class MenuAddComponent {
type: string | undefined
filter = weekendFilter
day = signal<DateTime>(DateTime.now())
range = new FormGroup({
start: new FormControl<DateTime | null>(null),
end: new FormControl<DateTime | null>(null),
})
constructor(
public dialogRef: MatDialogRef<MenuAddComponent>,
private dialog: MatDialog
) {}
submit() {
switch (this.type) {
case 'day':
this.dialogRef.close({ type: 'day', value: this.day().toISODate() })
break
case 'week':
this.dialogRef.close({
type: 'week',
value: { start: this.range.value.start?.toISODate(), count: 5 },
})
break
default:
break
}
}
activateUpload() {
this.dialog
.open(MenuUploadComponent)
.afterClosed()
.subscribe(data => {
if (data) {
this.dialogRef.close({ type: 'file', ...data })
}
})
}
}

View File

@@ -0,0 +1,155 @@
<div id="upper-bar">
<mat-form-field subscriptSizing="dynamic">
<mat-label>Wybierz tydzień</mat-label>
<mat-date-range-input [rangePicker]="picker" [formGroup]="range">
<input matStartDate formControlName="start">
<input matEndDate formControlName="end">
</mat-date-range-input>
<mat-datepicker-toggle matIconSuffix [for]="picker"></mat-datepicker-toggle>
<mat-date-range-picker #picker></mat-date-range-picker>
</mat-form-field>
<button mat-icon-button (click)="ac.refresh()"><mat-icon>search</mat-icon></button>
<button mat-icon-button (click)="addDate()"><mat-icon>add</mat-icon></button>
<button mat-icon-button (click)="print()"><mat-icon>print</mat-icon></button>
</div>
@if (loading) {
<mat-spinner></mat-spinner>
}
<div class="mainc">
@switch (ac.state()) {
@case (0) {
<p>Wybierz zakres dat powyżej i kliknij szukaj</p>
}
@case (1) {
<div class="spinner">
<mat-spinner color="accent"/>
</div>
}
@case (2) {
<table mat-table [dataSource]="dataSource">
<div matColumnDef="day">
<th mat-header-cell *matHeaderCellDef>Dzień</th>
<td mat-cell *matCellDef="let element">
<span>{{element.day.toFormat('dd.LL.yyyy')}}r.</span>
<p>{{element.day.toFormat('cccc') | titlecase }}</p>
<app-field-editor category="Nazwa" [(word)]="element.dayTitle" (wordChange)="editTitle(element._id)"/><br><hr>
<button (click)="remove(element._id)">Usuń dzień</button>
</td>
</div>
<div matColumnDef="sn">
<th mat-header-cell *matHeaderCellDef>Śniadanie</th>
<td mat-cell *matCellDef="let element">
<ul class="non-editable">
@for (i of ls.defaultItems.sn; track i) {
<li>{{i}}</li>
}
</ul><hr>
<app-list-editor [(list)]="element.sn.fancy" (edit)="editSn(element._id)" dataList="sn-fancy"/><hr>
<ul>
<li><app-field-editor category="II Śniadanie" [(word)]="element.sn.second" list="sn-second" (wordChange)="editSn(element._id)"/></li>
</ul>
</td>
</div>
<div matColumnDef="ob">
<th mat-header-cell *matHeaderCellDef>Obiad</th>
<td mat-cell *matCellDef="let element">
<ul>
<li><app-field-editor category="Zupa" [(word)]="element.ob.soup" list="ob-soup" (wordChange)="editOb(element._id)"/></li>
<li><app-field-editor category="Vege" [(word)]="element.ob.vege" list="ob-vege" (wordChange)="editOb(element._id)"/></li>
<li><app-field-editor category="Danie główne" [(word)]="element.ob.meal" list="ob-meal" (wordChange)="editOb(element._id)"/></li>
</ul><hr>
<app-list-editor [(list)]="element.ob.condiments" (edit)="editOb(element._id)" dataList="ob-condiments"/><hr>
<ul>
<li><app-field-editor category="Napój" [(word)]="element.ob.drink" list="ob-drink" (wordChange)="editOb(element._id)"/></li>
</ul><hr>
<app-list-editor [(list)]="element.ob.other" (edit)="editOb(element._id)" dataList="ob-other"/>
<button (click)="getStat(element.day, 'ob')">
Opinie wychowanków
</button>
</td>
</div>
<div matColumnDef="kol">
<th mat-header-cell *matHeaderCellDef>Kolacja</th>
<td mat-cell *matCellDef="let element">
<div>
@switch (element.day.weekday) {
@default {
<div>
<ul class="non-editable">
@for (i of ls.defaultItems.kol; track i) {
<li>{{i}}</li>
}
</ul><hr>
<ul>
<li><app-field-editor category="Kolacja" [(word)]="element.kol" list="kol" (wordChange)="editKol(element._id)"/></li>
</ul>
<button (click)="getStat(element.day, 'kol')">
Opinie wychowanków
</button>
</div>
}
@case (5) {
<div class="non-editable">
<p>Kolacja w domu!</p>
<p>(Nie edytowalne)</p>
</div>
}
}
</div>
</td>
</div>
<tr mat-header-row *matHeaderRowDef="dcols"></tr>
<tr mat-row *matRowDef="let row; columns: dcols"></tr>
</table>
}
}
</div>
@if (options) {
<datalist id="sn-fancy">
@for (i of options.sn.fancy; track i) {
<option>{{i}}</option>
}
</datalist>
<datalist id="sn-second">
@for (i of options.sn.second; track i) {
<option>{{i}}</option>
}
</datalist>
<datalist id="ob-soup">
@for (i of options.ob.soup; track i) {
<option>{{i}}</option>
}
</datalist>
<datalist id="ob-vege">
@for (i of options.ob.vege; track i) {
<option>{{i}}</option>
}
</datalist>
<datalist id="ob-meal">
@for (i of options.ob.meal; track i) {
<option>{{i}}</option>
}
</datalist>
<datalist id="ob-condiments">
@for (i of options.ob.condiments; track i) {
<option>{{i}}</option>
}
</datalist>
<datalist id="ob-drink">
@for (i of options.ob.drink; track i) {
<option>{{i}}</option>
}
</datalist>
<datalist id="ob-other">
@for (i of options.ob.other; track i) {
<option>{{i}}</option>
}
</datalist>
<datalist id="kol">
@for (i of options.kol; track i) {
<option>{{i}}</option>
}
</datalist>
}

View File

@@ -0,0 +1,34 @@
#upper-bar {
display: flex;
}
mat-form-field {
flex-grow: 1;
}
button[mat-icon-button] {
margin-left: 4pt;
margin-right: 4pt;
margin-top: 4pt;
}
.non-editable {
color: gray;
font-style: italic;
}
.mainc {
height: 100%;
position: relative;
}
.spinner {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
display: flex;
align-items: center;
justify-content: center;
}

View File

@@ -0,0 +1,51 @@
import { ComponentFixture, TestBed } from '@angular/core/testing'
import { MenuEditComponent } from './menu-edit.component'
import { MatTableModule } from '@angular/material/table'
import { MatInputModule } from '@angular/material/input'
import {
MAT_DATE_RANGE_SELECTION_STRATEGY,
MatDatepickerModule,
} from '@angular/material/datepicker'
import { BrowserAnimationsModule } from '@angular/platform-browser/animations'
import { FDSelection } from 'src/app/fd.da'
import { ReactiveFormsModule } from '@angular/forms'
import { of } from 'rxjs'
import { MatDialogModule } from '@angular/material/dialog'
import { MatIconModule } from '@angular/material/icon'
import { provideLuxonDateAdapter } from '@angular/material-luxon-adapter'
xdescribe('MenuEditComponent', () => {
let component: MenuEditComponent
let fixture: ComponentFixture<MenuEditComponent>
beforeEach(() => {
const acMock = jasmine.createSpyObj('AdminCommService', {
getMenu: of(),
})
TestBed.configureTestingModule({
declarations: [MenuEditComponent],
imports: [
MatTableModule,
MatInputModule,
MatDatepickerModule,
BrowserAnimationsModule,
ReactiveFormsModule,
MatDialogModule,
MatIconModule,
],
providers: [
provideLuxonDateAdapter(),
{ provide: MAT_DATE_RANGE_SELECTION_STRATEGY, useClass: FDSelection },
// { provide: AdminCommService, useValue: acMock },
],
})
fixture = TestBed.createComponent(MenuEditComponent)
component = fixture.componentInstance
fixture.detectChanges()
})
it('should create', () => {
expect(component).toBeTruthy()
})
})

View File

@@ -0,0 +1,152 @@
import { Component } from '@angular/core'
import { FormControl, FormGroup } from '@angular/forms'
import { MAT_DATE_RANGE_SELECTION_STRATEGY } from '@angular/material/datepicker'
import { FDSelection } from 'src/app/fd.da'
import { Menu } from 'src/app/types/menu'
import { MatTableDataSource } from '@angular/material/table'
import { MatDialog } from '@angular/material/dialog'
import { MenuUploadComponent } from './menu-upload/menu-upload.component'
import { Status } from 'src/app/types/status'
import { MatSnackBar } from '@angular/material/snack-bar'
import { MenuAddComponent } from './menu-add/menu-add.component'
import { LocalStorageService } from 'src/app/services/local-storage.service'
import { DateTime } from 'luxon'
import { MenuEditService } from './menu-edit.service'
@Component({
selector: 'app-menu-edit',
templateUrl: './menu-edit.component.html',
styleUrls: ['./menu-edit.component.scss'],
providers: [
{ provide: MAT_DATE_RANGE_SELECTION_STRATEGY, useClass: FDSelection },
],
standalone: false,
})
export class MenuEditComponent {
dcols: string[] = ['day', 'sn', 'ob', 'kol']
dataSource: MatTableDataSource<Menu> = new MatTableDataSource<Menu>()
range = new FormGroup({
start: new FormControl<DateTime | null>(null),
end: new FormControl<DateTime | null>(null),
})
loading = false
public options: any
constructor(
protected ac: MenuEditService,
private dialog: MatDialog,
private sb: MatSnackBar,
readonly ls: LocalStorageService
) {
this.range.valueChanges.subscribe(v => {
ac.setDates(v.start!, v.end!)
})
ac.menuItems.subscribe(v => {
this.dataSource.data = v
})
}
print() {
this.ac
.print(this.range.value.start, this.range.value.end)
?.subscribe(r => {
if (r && r.length > 0) {
var mywindow = window.open(
undefined,
'Drukowanie',
'height=400,width=400'
)
mywindow?.document.write(r)
mywindow?.print()
mywindow?.close()
}
})
}
addDate() {
this.dialog
.open(MenuAddComponent)
.afterClosed()
.subscribe(data => {
if (data) {
switch (data.type) {
case 'day':
this.ac.new
.single(data.value)
.subscribe(s => this.refreshIfGood(s))
break
case 'week':
this.ac.new
.range(data.value.start, data.value.count)
.subscribe(s => this.refreshIfGood(s))
break
case 'file':
this.refresh()
break
default:
break
}
}
})
}
refresh() {
this.ac.refresh()
this.ac.getOpts().subscribe(o => {
this.options = o
})
}
private refreshIfGood(s: Status) {
if (s.status.toString().match(/2\d\d/)) this.refresh()
}
activateUpload() {
this.dialog
.open(MenuUploadComponent)
.afterClosed()
.subscribe(data => {
if (data) this.refresh()
})
}
editSn(id: string) {
this.ac
.editSn(id, this.dataSource.data.find(v => v._id == id)!.sn)
.subscribe(s => this.refreshIfGood(s))
}
editOb(id: string) {
this.ac
.editOb(id, this.dataSource.data.find(v => v._id == id)!.ob)
.subscribe(s => this.refreshIfGood(s))
}
editKol(id: string) {
this.ac
.editKol(id, this.dataSource.data.find(v => v._id == id)?.kol)
.subscribe(s => this.refreshIfGood(s))
}
editTitle(id: string) {
this.ac
.editTitle(id, this.dataSource.data.find(v => v._id == id)?.dayTitle)
.subscribe(s => this.refreshIfGood(s))
}
getStat(day: DateTime, m: 'ob' | 'kol') {
this.ac
.stat(day, m)
.subscribe(s =>
this.sb.open(
`${s.y} / ${s.y + s.n} = ${((s.y / (s.y + s.n)) * 100).toFixed(2)}%`,
'Zamknij',
{ duration: 2500 }
)
)
}
remove(id: string) {
this.ac.rm(id).subscribe(s => this.refreshIfGood(s))
}
}

View File

@@ -0,0 +1,23 @@
import { TestBed } from '@angular/core/testing';
import { MenuEditService } from './menu-edit.service';
import { provideHttpClient } from '@angular/common/http';
import { provideHttpClientTesting } from '@angular/common/http/testing';
describe('MenuEditService', () => {
let service: MenuEditService;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
provideHttpClient(),
provideHttpClientTesting()
]
});
service = TestBed.inject(MenuEditService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
});

View File

@@ -0,0 +1,150 @@
import { HttpClient } from '@angular/common/http';
import { Injectable, signal } from '@angular/core';
import { DateTime } from 'luxon';
import { BehaviorSubject, catchError, map, of } from 'rxjs';
import { Menu, MenuAPI } from 'src/app/types/menu';
import { STATE } from 'src/app/types/state';
import { Status } from 'src/app/types/status';
import { environment } from 'src/environments/environment';
@Injectable({
providedIn: 'root'
})
export class MenuEditService {
private _menuItems = new BehaviorSubject<Menu[]>([])
public readonly menuItems = this._menuItems.asObservable()
private _state = signal(STATE.NOT_LOADED);
public readonly state = this._state.asReadonly();
private _error = signal<string | undefined>(undefined);
public readonly error = this._error.asReadonly();
private seDates: {
start: DateTime | null,
end: DateTime | null
} = {
start: null,
end: null
}
public setDates(start: DateTime | null, end: DateTime | null) {
this.seDates.start = start
this.seDates.end = end
}
public refresh() {
this.getMenu()
}
private getMenu() {
if (!(this.seDates.start && this.seDates.end)) return
this._state.set(STATE.PENDING)
const body = { start: this.seDates.start.toString(), end: this.seDates.end.toString() }
this.http.get
<MenuAPI[]>
(environment.apiEndpoint + `/admin/menu`, { withCredentials: true, params: body })
.pipe(
catchError((err: Error) => {
this._state.set(STATE.ERROR)
this._error.set(err.message)
return of()
}),
map<MenuAPI[], Menu[]>(v =>
v.map(i => ({
...i,
day: DateTime.fromISO(i.day)
})))
).subscribe(v => {
this._error.set(undefined)
this._menuItems.next(v ?? [])
this._state.set(STATE.LOADED)
})
}
constructor(private http: HttpClient) { }
getOpts() {
return this.http.get<any>(environment.apiEndpoint + `/admin/menu/opts`, {
withCredentials: true,
})
}
postMenu(file: File) {
if (file) {
const formData = new FormData()
formData.append('menu', file)
return this.http.post<Status>(
environment.apiEndpoint + '/admin/menu/upload',
formData,
{ withCredentials: true }
)
}
return
}
editSn(id: string, content: Menu['sn']) {
return this.putMenu(id, { sn: content })
}
editOb(id: string, content: Menu['ob']) {
return this.putMenu(id, { ob: content })
}
editKol(id: string, content: Menu['kol']) {
return this.putMenu(id, { kol: content })
}
editTitle(id: string, content: Menu['dayTitle']) {
return this.putMenu(id, { dayTitle: content })
}
print(start?: DateTime | null, end?: DateTime | null) {
if (start && end) {
const body = { start: start.toString(), end: end.toString() }
return this.http.get(environment.apiEndpoint + '/admin/menu/print', {
withCredentials: true,
params: body,
responseType: 'text',
})
}
return
}
stat(day: DateTime, m: 'ob' | 'kol') {
return this.http.get<{ y: number; n: number }>(
environment.apiEndpoint + `/admin/menu/${day.toISO()}/votes/${m}`,
{ withCredentials: true }
)
}
new = {
single: (day: DateTime) => {
return this.http.post<Status>(
environment.apiEndpoint + `/admin/menu/${day.toISO()}`,
null,
{ withCredentials: true }
)
},
range: (start: DateTime, count: number) => {
return this.http.post<Status>(
environment.apiEndpoint + `/admin/menu/${start.toISO()}/${count}/`,
null,
{ withCredentials: true }
)
},
}
rm(id: string) {
return this.http.delete<Status>(
environment.apiEndpoint + `/admin/menu/${id}`,
{ withCredentials: true }
)
}
private putMenu(id: string, update: Partial<Menu>) {
return this.http.put<Status>(
environment.apiEndpoint + `/admin/menu/${id}`,
update,
{ withCredentials: true }
)
}
}

View File

@@ -0,0 +1,4 @@
:host {
margin: 8pt;
display: block;
}

View File

@@ -0,0 +1,28 @@
import { ComponentFixture, TestBed } from '@angular/core/testing'
import { MenuUploadComponent } from './menu-upload.component'
import { MatDialogModule, MatDialogRef } from '@angular/material/dialog'
xdescribe('MenuUploadComponent', () => {
let component: MenuUploadComponent
let fixture: ComponentFixture<MenuUploadComponent>
beforeEach(() => {
const acMock = jasmine.createSpyObj('AdminCommService', ['postMenu'])
TestBed.configureTestingModule({
declarations: [MenuUploadComponent],
providers: [
// { provide: AdminCommService, useValue: acMock },
{ provide: MatDialogRef, useValue: {} },
],
imports: [MatDialogModule],
})
fixture = TestBed.createComponent(MenuUploadComponent)
component = fixture.componentInstance
fixture.detectChanges()
})
it('should create', () => {
expect(component).toBeTruthy()
})
})

View File

@@ -0,0 +1,31 @@
import { Component } from '@angular/core'
import { MatDialogRef } from '@angular/material/dialog'
import { MenuEditService } from '../menu-edit.service'
@Component({
selector: 'app-upload-edit',
templateUrl: './menu-upload.component.html',
styleUrls: ['./menu-upload.component.scss'],
standalone: false,
})
export class MenuUploadComponent {
constructor(
private ac: MenuEditService,
public dialogRef: MatDialogRef<MenuUploadComponent>
) {}
protected file: File | undefined
onFileChange(event: Event) {
const file: File = (event.target as HTMLInputElement).files![0]
if (file) {
this.file = file
} else {
this.file = undefined
}
}
submit() {
this.ac.postMenu(this.file!)?.subscribe(value => {
this.dialogRef.close(value)
})
}
}

View File

@@ -1,51 +0,0 @@
import { Component } from '@angular/core';
import { MenuUploadComponent } from '../menu-upload/menu-upload.component';
import { MatDialog, MatDialogRef } from '@angular/material/dialog';
import { FDSelection, weekendFilter } from 'src/app/fd.da';
import { FormControl, FormGroup } from '@angular/forms';
import { Moment } from 'moment';
import { MAT_DATE_RANGE_SELECTION_STRATEGY } from '@angular/material/datepicker';
import * as moment from 'moment';
@Component({
selector: 'app-menu-add',
templateUrl: './menu-add.component.html',
styleUrl: './menu-add.component.scss',
providers: [
{provide: MAT_DATE_RANGE_SELECTION_STRATEGY, useClass: FDSelection}
]
})
export class MenuAddComponent {
type: string | undefined;
filter = weekendFilter
day: Moment = moment.utc();
range = new FormGroup({
start: new FormControl<Moment|null>(null),
end: new FormControl<Moment|null>(null),
})
constructor (public dialogRef: MatDialogRef<MenuAddComponent>, private dialog: MatDialog) { }
submit() {
switch (this.type) {
case "day":
this.dialogRef.close({type: "day", value: this.day.utc()})
break;
case "week":
this.dialogRef.close({type: "week", value: {start: this.range.value.start?.utc().hours(24), count: 5}})
break;
default:
break;
}
}
activateUpload() {
this.dialog.open(MenuUploadComponent).afterClosed().subscribe((data) => {
if (data) {
this.dialogRef.close({type: "file", ...data});
}
})
}
}

View File

@@ -1,111 +0,0 @@
<div id="upper-bar">
<mat-form-field>
<mat-label>Wybierz tydzień</mat-label>
<mat-date-range-input [rangePicker]="picker" [formGroup]="range">
<input matStartDate formControlName="start" (dateChange)="requestData()">
<input matEndDate formControlName="end" (dateChange)="requestData()">
</mat-date-range-input>
<mat-datepicker-toggle matIconSuffix [for]="picker"></mat-datepicker-toggle>
<mat-date-range-picker #picker></mat-date-range-picker>
</mat-form-field>
<button mat-icon-button (click)="requestData()"><mat-icon>refresh</mat-icon></button>
<button mat-icon-button (click)="addDate()"><mat-icon>add</mat-icon></button>
<button mat-icon-button (click)="print()"><mat-icon>print</mat-icon></button>
</div>
<mat-spinner *ngIf="loading"></mat-spinner>
<table mat-table [dataSource]="dataSource">
<div matColumnDef="day">
<th mat-header-cell *matHeaderCellDef>Dzień</th>
<td mat-cell *matCellDef="let element">
<span>{{element.day.format('DD.MM.YYYY')}}r.</span>
<p>{{element.day.format('dddd')}}</p>
<app-field-editor category="Nazwa" [(word)]="element.dayTitle" (wordChange)="editTitle(element._id)"/><br><hr>
<button (click)="remove(element._id)">Usuń dzień</button>
</td>
</div>
<div matColumnDef="sn">
<th mat-header-cell *matHeaderCellDef>Śniadanie</th>
<td mat-cell *matCellDef="let element">
<ul class="non-editable">
<li *ngFor="let i of ls.defaultItems.sn">{{i}}</li>
</ul><hr>
<app-list-editor [(list)]="element.sn.fancy" (edit)="editSn(element._id)" dataList="sn-fancy"/><hr>
<ul>
<li><app-field-editor category="II Śniadanie" [(word)]="element.sn.second" list="sn-second" (wordChange)="editSn(element._id)"/></li>
</ul>
</td>
</div>
<div matColumnDef="ob">
<th mat-header-cell *matHeaderCellDef>Obiad</th>
<td mat-cell *matCellDef="let element">
<ul>
<li><app-field-editor category="Zupa" [(word)]="element.ob.soup" list="ob-soup" (wordChange)="editOb(element._id)"/></li>
<li><app-field-editor category="Vege" [(word)]="element.ob.vege" list="ob-vege" (wordChange)="editOb(element._id)"/></li>
<li><app-field-editor category="Danie główne" [(word)]="element.ob.meal" list="ob-meal" (wordChange)="editOb(element._id)"/></li>
</ul><hr>
<app-list-editor [(list)]="element.ob.condiments" (edit)="editOb(element._id)" dataList="ob-condiments"/><hr>
<ul>
<li><app-field-editor category="Napój" [(word)]="element.ob.drink" list="ob-drink" (wordChange)="editOb(element._id)"/></li>
</ul><hr>
<app-list-editor [(list)]="element.ob.other" (edit)="editOb(element._id)" dataList="ob-other"/>
<button (click)="getStat(element.day, 'ob')">
Opinie wychowanków
</button>
</td>
</div>
<div matColumnDef="kol">
<th mat-header-cell *matHeaderCellDef>Kolacja</th>
<td mat-cell *matCellDef="let element">
<div [ngSwitch]="element.day.isoWeekday()">
<div *ngSwitchDefault>
<ul class="non-editable">
<li *ngFor="let i of ls.defaultItems.kol">{{i}}</li>
</ul><hr>
<ul>
<li><app-field-editor category="Kolacja" [(word)]="element.kol" list="kol" (wordChange)="editKol(element._id)"/></li>
</ul>
<button (click)="getStat(element.day, 'kol')">
Opinie wychowanków
</button>
</div>
<div *ngSwitchCase="5" class="non-editable">
<p>Kolacja w domu!</p>
<p>(Nie edytowalne)</p>
</div>
</div>
</td>
</div>
<tr mat-header-row *matHeaderRowDef="dcols"></tr>
<tr mat-row *matRowDef="let row; columns: dcols"></tr>
</table>
<ng-container *ngIf="options">
<datalist id="sn-fancy">
<option *ngFor="let i of options.sn.fancy">{{i}}</option>
</datalist>
<datalist id="sn-second">
<option *ngFor="let i of options.sn.second">{{i}}</option>
</datalist>
<datalist id="ob-soup">
<option *ngFor="let i of options.ob.soup">{{i}}</option>
</datalist>
<datalist id="ob-vege">
<option *ngFor="let i of options.ob.vege">{{i}}</option>
</datalist>
<datalist id="ob-meal">
<option *ngFor="let i of options.ob.meal">{{i}}</option>
</datalist>
<datalist id="ob-condiments">
<option *ngFor="let i of options.ob.condiments">{{i}}</option>
</datalist>
<datalist id="ob-drink">
<option *ngFor="let i of options.ob.drink">{{i}}</option>
</datalist>
<datalist id="ob-other">
<option *ngFor="let i of options.ob.other">{{i}}</option>
</datalist>
<datalist id="kol">
<option *ngFor="let i of options.kol">{{i}}</option>
</datalist>
</ng-container>

View File

@@ -1,18 +0,0 @@
#upper-bar {
display: flex;
}
mat-form-field {
flex-grow: 1;
}
button[mat-icon-button] {
margin-left: 4pt;
margin-right: 4pt;
margin-top: 4pt;
}
.non-editable {
color: gray;
font-style: italic;
}

View File

@@ -1,45 +0,0 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { MenuNewComponent } from './menu-new.component';
import { MatTableModule } from '@angular/material/table';
import { MatInputModule } from '@angular/material/input';
import { MAT_DATE_RANGE_SELECTION_STRATEGY, MatDatepickerModule } from '@angular/material/datepicker';
import { DateAdapter, MAT_DATE_FORMATS, MAT_DATE_LOCALE } from '@angular/material/core';
import { MAT_MOMENT_DATE_ADAPTER_OPTIONS, MAT_MOMENT_DATE_FORMATS, MomentDateAdapter } from '@angular/material-moment-adapter';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { FDSelection } from 'src/app/fd.da';
import { ReactiveFormsModule } from '@angular/forms';
import { AdminCommService } from '../admin-comm.service';
import { of } from 'rxjs';
import { MatDialogModule } from '@angular/material/dialog';
import { MatIconModule } from '@angular/material/icon';
describe('MenuNewComponent', () => {
let component: MenuNewComponent;
let fixture: ComponentFixture<MenuNewComponent>;
beforeEach(() => {
const acMock = jasmine.createSpyObj('AdminCommService', {
getMenu: of()
})
TestBed.configureTestingModule({
declarations: [MenuNewComponent],
imports: [MatTableModule, MatInputModule, MatDatepickerModule, BrowserAnimationsModule, ReactiveFormsModule, MatDialogModule, MatIconModule],
providers: [
{provide: DateAdapter, useClass: MomentDateAdapter},
{provide: MAT_DATE_LOCALE, useValue: "pl-PL"},
{provide: MAT_DATE_FORMATS, useValue: MAT_MOMENT_DATE_FORMATS},
{provide: MAT_MOMENT_DATE_ADAPTER_OPTIONS, useValue: {useUtc: true}},
{provide: MAT_DATE_RANGE_SELECTION_STRATEGY, useClass: FDSelection},
{provide: AdminCommService, useValue: acMock}
],
});
fixture = TestBed.createComponent(MenuNewComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@@ -1,131 +0,0 @@
import { AfterViewInit, Component, ViewChild } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';
import { MAT_DATE_RANGE_SELECTION_STRATEGY } from '@angular/material/datepicker';
import { Moment } from 'moment';
import { FDSelection } from 'src/app/fd.da';
import { Menu } from 'src/app/types/menu';
import { AdminCommService } from '../admin-comm.service';
import { MatTableDataSource } from '@angular/material/table';
import * as moment from 'moment';
import { MatDialog } from '@angular/material/dialog';
import { MenuUploadComponent } from './menu-upload/menu-upload.component';
import { Status } from 'src/app/types/status';
import { MatSnackBar } from '@angular/material/snack-bar';
import { MenuAddComponent } from './menu-add/menu-add.component';
import { LocalStorageService } from 'src/app/services/local-storage.service';
@Component({
selector: 'app-menu-new',
templateUrl: './menu-new.component.html',
styleUrls: ['./menu-new.component.scss'],
providers: [
{provide: MAT_DATE_RANGE_SELECTION_STRATEGY, useClass: FDSelection}
]
})
export class MenuNewComponent {
dcols: string[] = ['day', 'sn', 'ob', 'kol']
dataSource: MatTableDataSource<Menu> = new MatTableDataSource<Menu>()
range = new FormGroup({
start: new FormControl<Moment|null>(null),
end: new FormControl<Moment|null>(null),
})
loading = false
public options: any;
constructor (private ac: AdminCommService, private dialog: MatDialog, private sb: MatSnackBar, readonly ls: LocalStorageService) {
moment.updateLocale('pl', {
weekdays: ["Niedziela", "Poniedziałek", "Wtorek", "Środa", "Czwartek", "Piątek", "Sobota"]
})
}
print() {
this.ac.menu.print(this.range.value.start, this.range.value.end)?.subscribe((r) => {
if (r && r.length > 0) {
var mywindow = window.open(undefined, 'Drukowanie', 'height=400,width=400')
mywindow?.document.write(r)
mywindow?.print()
mywindow?.close()
}
})
}
addDate() {
this.dialog.open(MenuAddComponent).afterClosed().subscribe((data) => {
if (data) {
switch (data.type) {
case "day":
this.ac.menu.new.single(data.value).subscribe()
break;
case "week":
this.ac.menu.new.range(data.value.start, data.value.count).subscribe()
break;
case "file":
this.requestData()
break;
default:
break;
}
}
})
}
requestData() {
this.loading = true
this.ac.menu.getOpts().subscribe((o) => {
this.options = o;
})
this.ac.menu.getMenu(this.range.value.start, this.range.value.end)?.subscribe((data) => {
this.loading = false
this.dataSource.data = data.map((v) => {
let newMenu: Menu = {
...v,
day: moment.utc(v.day)
}
return newMenu
})
})
}
private refreshIfGood(s: Status) {
if (s.status == 200) {
this.requestData()
}
}
activateUpload() {
this.dialog.open(MenuUploadComponent).afterClosed().subscribe((data) => {
if (data) {
this.requestData()
}
})
}
editDay(v: string | string[], element: Menu) {
v = v as string
element.day = moment(v, "DD.MM.YYYY", true).utc(true).startOf('day')
}
editSn(id: string) {
this.ac.menu.editSn(id, this.dataSource.data.find(v => v._id == id)?.sn).subscribe(this.refreshIfGood)
}
editOb(id: string) {
this.ac.menu.editOb(id, this.dataSource.data.find(v => v._id == id)?.ob).subscribe(this.refreshIfGood)
}
editKol(id: string) {
this.ac.menu.editKol(id, this.dataSource.data.find(v => v._id == id)?.kol).subscribe(this.refreshIfGood)
}
editTitle(id: string) {
this.ac.menu.editTitle(id, this.dataSource.data.find(v => v._id == id)?.dayTitle).subscribe(this.refreshIfGood)
}
getStat(day: moment.Moment, m: "ob" | "kol") {
this.ac.menu.stat(day, m).subscribe((s) => this.sb.open(`${s.y} / ${s.y+s.n} = ${((s.y/(s.y+s.n))*100).toFixed(2)}%`, "Zamknij", {duration: 2500}))
}
remove(id: string) {
this.ac.menu.rm(id).subscribe(this.refreshIfGood)
}
}

View File

@@ -1,4 +0,0 @@
:host {
margin: 8pt;
display: block;
}

View File

@@ -1,29 +0,0 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { MenuUploadComponent } from './menu-upload.component';
import { AdminCommService } from '../../admin-comm.service';
import { MatDialogModule, MatDialogRef } from '@angular/material/dialog';
describe('MenuUploadComponent', () => {
let component: MenuUploadComponent;
let fixture: ComponentFixture<MenuUploadComponent>;
beforeEach(() => {
const acMock = jasmine.createSpyObj('AdminCommService', ['postMenu'])
TestBed.configureTestingModule({
declarations: [MenuUploadComponent],
providers: [
{provide: AdminCommService, useValue: acMock},
{provide: MatDialogRef, useValue: {}}
],
imports: [MatDialogModule]
});
fixture = TestBed.createComponent(MenuUploadComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@@ -1,27 +0,0 @@
import { Component } from '@angular/core';
import { AdminCommService } from '../../admin-comm.service';
import { MatDialogRef } from '@angular/material/dialog';
@Component({
selector: 'app-upload-edit',
templateUrl: './menu-upload.component.html',
styleUrls: ['./menu-upload.component.scss'],
})
export class MenuUploadComponent {
constructor(private ac:AdminCommService, public dialogRef: MatDialogRef<MenuUploadComponent>) {}
protected file: File | undefined;
onFileChange(event: Event) {
const file:File = (event.target as HTMLInputElement).files![0];
if (file) {
this.file = file
} else {
this.file = undefined
}
}
submit() {
this.ac.menu.postMenu(this.file!)?.subscribe((value) => {
this.dialogRef.close(value)
})
}
}

View File

@@ -1,10 +1,10 @@
:host { :host {
padding: 8pt; padding: 8pt;
display: block; display: block;
} }
form { form {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
align-items: stretch; align-items: stretch;
} }

View File

@@ -1,31 +1,41 @@
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing'
import { NewPostComponent } from './edit-post.component'; import { NewPostComponent } from './edit-post.component'
import { MAT_DIALOG_DATA, MatDialogModule, MatDialogRef } from '@angular/material/dialog'; import {
import { MatFormFieldModule } from '@angular/material/form-field'; MAT_DIALOG_DATA,
import { MatInputModule } from '@angular/material/input'; MatDialogModule,
import { ReactiveFormsModule } from '@angular/forms'; MatDialogRef,
import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; } from '@angular/material/dialog'
import { MatFormFieldModule } from '@angular/material/form-field'
import { MatInputModule } from '@angular/material/input'
import { ReactiveFormsModule } from '@angular/forms'
import { BrowserAnimationsModule } from '@angular/platform-browser/animations'
describe('NewPostComponent', () => { describe('NewPostComponent', () => {
let component: NewPostComponent; let component: NewPostComponent
let fixture: ComponentFixture<NewPostComponent>; let fixture: ComponentFixture<NewPostComponent>
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
declarations: [NewPostComponent], declarations: [NewPostComponent],
imports: [MatDialogModule, MatFormFieldModule, MatInputModule, ReactiveFormsModule, BrowserAnimationsModule], imports: [
MatDialogModule,
MatFormFieldModule,
MatInputModule,
ReactiveFormsModule,
BrowserAnimationsModule,
],
providers: [ providers: [
{provide: MatDialogRef, useValue: {}}, { provide: MatDialogRef, useValue: {} },
{provide: MAT_DIALOG_DATA, useValue: {}} { provide: MAT_DIALOG_DATA, useValue: {} },
] ],
}); })
fixture = TestBed.createComponent(NewPostComponent); fixture = TestBed.createComponent(NewPostComponent)
component = fixture.componentInstance; component = fixture.componentInstance
fixture.detectChanges(); fixture.detectChanges()
}); })
it('should create', () => { it('should create', () => {
expect(component).toBeTruthy(); expect(component).toBeTruthy()
}); })
}); })

View File

@@ -1,31 +1,35 @@
import { Component, Inject } from '@angular/core'; import { Component, Inject } from '@angular/core'
import { FormControl, FormGroup } from '@angular/forms'; import { FormControl, FormGroup } from '@angular/forms'
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog'; import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog'
@Component({ @Component({
selector: 'app-edit-post', selector: 'app-edit-post',
templateUrl: './edit-post.component.html', templateUrl: './edit-post.component.html',
styleUrls: ['./edit-post.component.scss'] styleUrls: ['./edit-post.component.scss'],
standalone: false,
}) })
export class NewPostComponent { export class NewPostComponent {
form: FormGroup; form: FormGroup
constructor (public dialogRef: MatDialogRef<NewPostComponent>, @Inject(MAT_DIALOG_DATA) public data: any) { constructor(
public dialogRef: MatDialogRef<NewPostComponent>,
@Inject(MAT_DIALOG_DATA) public data: any
) {
if (data == null) { if (data == null) {
data = { data = {
title:"", title: '',
content:"", content: '',
} }
} }
this.form = new FormGroup({ this.form = new FormGroup({
title: new FormControl(data.title), title: new FormControl(data.title),
content: new FormControl(data.content) content: new FormControl(data.content),
}) })
} }
protected makePost() { protected makePost() {
this.dialogRef.close({ this.dialogRef.close({
title: this.form.get('title')?.value, title: this.form.get('title')?.value,
content: this.form.get('content')?.value content: this.form.get('content')?.value,
}) })
} }
} }

View File

@@ -1,25 +1,43 @@
<button mat-raised-button (click)="newPost()" color="accent">Nowy post</button> <button mat-raised-button (click)="newPost()" color="accent" class="newPost">Nowy post</button>
<mat-spinner *ngIf="loading"></mat-spinner> <div class="mainc">
<mat-card *ngFor="let item of news"> @if (ac.state() != 2) {
<mat-card-header> <app-load-shade [state]="ac.state()" [error]="ac.error()" (refresh)="ac.refresh()"/>
}
@for (item of ac.news | async; track item) {
<mat-card>
<mat-card-header>
<mat-card-title>{{item.title}}</mat-card-title> <mat-card-title>{{item.title}}</mat-card-title>
<mat-icon *ngIf="item.pinned">push_pin</mat-icon> @if (item.pinned) {
<mat-card-subtitle>{{item._id}}</mat-card-subtitle> <mat-icon>push_pin</mat-icon>
</mat-card-header> }
<mat-card-content [innerHTML]="item.formatted"> </mat-card-header>
</mat-card-content> <mat-card-content [innerHTML]="item.formatted"></mat-card-content>
<mat-card-actions> <mat-card-actions>
<button mat-mini-fab (click)="editPost(item)"><mat-icon>edit</mat-icon></button> <button mat-mini-fab (click)="editPost(item)"><mat-icon>edit</mat-icon></button>
<button mat-mini-fab (click)="pinToggle(item)"><mat-icon>push_pin</mat-icon></button> <button mat-mini-fab (click)="pinToggle(item)"><mat-icon>push_pin</mat-icon></button>
<button mat-mini-fab (click)="visibleToggle(item)"> @switch (item.visible) {
<div [ngSwitch]="item.visible"> @case (true) {
<mat-icon *ngSwitchCase="true">visibility</mat-icon> <button mat-mini-fab (click)="visibleToggle(item)">
<mat-icon *ngSwitchDefault>visibility_off</mat-icon> <mat-icon>visibility</mat-icon>
</div> </button>
</button> }
@default {
<button mat-mini-fab (click)="visibleToggle(item)" color="warn">
<mat-icon>visibility_off</mat-icon>
</button>
}
}
<button mat-mini-fab (click)="delete(item._id)"><mat-icon>delete_forever</mat-icon></button> <button mat-mini-fab (click)="delete(item._id)"><mat-icon>delete_forever</mat-icon></button>
</mat-card-actions> </mat-card-actions>
<mat-card-footer> <mat-card-footer>
<p>{{item.date | date:'d-LL-yyyy HH:mm'}}</p> <p>{{fullName(item)}} {{item.date | date:'d-LL-yyyy HH:mm'}}</p>
</mat-card-footer> </mat-card-footer>
</mat-card> </mat-card>
} @empty {
<mat-card>
<p>
Brak wiadomości.
</p>
</mat-card>
}
</div>

View File

@@ -1,34 +1,48 @@
mat-card { mat-card {
margin: 15px; margin: 15px;
padding: 1ch; padding: 1ch;
width: 100%;
} }
mat-card-title { mat-card-title {
font-size: 1.5rem; font-size: 1.5rem;
} }
mat-card-footer p { mat-card-footer p {
font-size: 0.8rem; font-size: 0.8rem;
color: #4a4a4a; color: #4a4a4a;
@media (prefers-color-scheme: dark) { margin-bottom: 0;
color: #999999 text-align: end;
} @media (prefers-color-scheme: dark) {
margin-bottom: 0; color: #999999;
text-align: end; }
} }
mat-card-content p { mat-card-content p {
white-space: pre-line; white-space: pre-line;
}
mat-card p {
margin: 15px;
} }
button { button {
margin-right: 4pt; margin-right: 4pt;
} }
:host { :host {
padding: 8pt; display: flex;
display: flex; flex-direction: column;
flex-direction: column; align-items: center;
align-items: center; height: 100%;
width: 100%;
}
.mainc {
position: relative;
height: 100%;
width: 100%;
}
.newPost {
margin: 1ch;
} }

View File

@@ -1,32 +1,33 @@
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing'
import { NewsEditComponent } from './news-edit.component'; import { NewsEditComponent } from './news-edit.component'
import { AdminCommService } from '../admin-comm.service'; import { MatDialogModule } from '@angular/material/dialog'
import { MatDialogModule } from '@angular/material/dialog'; import { MatSnackBarModule } from '@angular/material/snack-bar'
import { MatSnackBarModule } from '@angular/material/snack-bar'; import { of } from 'rxjs'
import { of } from 'rxjs'; import { MatCardModule } from '@angular/material/card'
describe('NewsEditComponent', () => { xdescribe('NewsEditComponent', () => {
let component: NewsEditComponent; let component: NewsEditComponent
let fixture: ComponentFixture<NewsEditComponent>; let fixture: ComponentFixture<NewsEditComponent>
let acMock
beforeEach(() => { beforeEach(() => {
const acMock = jasmine.createSpyObj('AdminCommService', { acMock = {
getNews: of() news: {
}) getNews: jasmine.createSpy('getNews').and.returnValue(of([])),
},
}
TestBed.configureTestingModule({ TestBed.configureTestingModule({
declarations: [NewsEditComponent], declarations: [NewsEditComponent],
providers: [ // providers: [{ provide: AdminCommService, useValue: acMock }],
{provide: AdminCommService, useValue: acMock} imports: [MatDialogModule, MatSnackBarModule, MatCardModule],
], })
imports: [MatDialogModule, MatSnackBarModule] fixture = TestBed.createComponent(NewsEditComponent)
}); component = fixture.componentInstance
fixture = TestBed.createComponent(NewsEditComponent); fixture.detectChanges()
component = fixture.componentInstance; })
fixture.detectChanges();
});
it('should create', () => { it('should create', () => {
expect(component).toBeTruthy(); expect(component).toBeTruthy()
}); })
}); })

View File

@@ -1,71 +1,79 @@
import { Component, OnInit } from '@angular/core'; import { Component, OnInit } from '@angular/core'
import { AdminCommService } from '../admin-comm.service'; import { MatDialog } from '@angular/material/dialog'
import { MatDialog } from '@angular/material/dialog'; import { NewPostComponent } from './new-post/edit-post.component'
import { NewPostComponent } from './new-post/edit-post.component'; import { catchError, throwError } from 'rxjs'
import { catchError, throwError } from 'rxjs'; import { MatSnackBar } from '@angular/material/snack-bar'
import { MatSnackBar } from '@angular/material/snack-bar'; import { News } from 'src/app/types/news.model'
import { News } from 'src/app/types/news'; import { NewsEditService } from './news-edit.service'
import { marked } from 'marked';
@Component({ @Component({
selector: 'app-news-edit', selector: 'app-news-edit',
templateUrl: './news-edit.component.html', templateUrl: './news-edit.component.html',
styleUrls: ['./news-edit.component.scss'] styleUrls: ['./news-edit.component.scss'],
standalone: false,
}) })
export class NewsEditComponent implements OnInit { export class NewsEditComponent implements OnInit {
news:Array<News & {formatted: string}> = new Array<News & {formatted: string}>
loading = true
constructor(private ac:AdminCommService, private dialog:MatDialog, private sb:MatSnackBar) {} constructor(
protected ac: NewsEditService,
private dialog: MatDialog,
private sb: MatSnackBar
) { }
ngOnInit() { ngOnInit() {
this.loading = true this.ac.refresh()
this.ac.news.getNews().subscribe(data => {
this.loading = false
this.news = data.map(v => {
var nd: News & {formatted: string} = {
...v,
formatted: marked.parse(v.content, {breaks: true}).toString()
}
return nd
})
})
} }
newPost() { newPost() {
this.dialog.open(NewPostComponent, {width: "90vw"}).afterClosed().subscribe(result=> { this.dialog
if (result == undefined) return .open(NewPostComponent, { width: '90vw' })
this.ac.news.postNews(result.title, result.content).pipe(catchError((err)=>{ .afterClosed()
this.sb.open("Wystąpił błąd. Skontaktuj się z obsługą programu.") .subscribe(result => {
return throwError(() => new Error(err.message)) if (result == undefined) return
})).subscribe((data)=>{ this.ac
if (data.status == 201) { .postNews(result.title, result.content)
this.ngOnInit() .pipe(
} else { catchError(err => {
this.sb.open("Wystąpił błąd. Skontaktuj się z obsługą programu.") 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.ngOnInit()
} else {
this.sb.open('Wystąpił błąd. Skontaktuj się z obsługą programu.')
}
})
}) })
})
} }
editPost(item: any) { editPost(item: any) {
this.dialog.open(NewPostComponent, {data: item, width: "90vh"}).afterClosed().subscribe(result=>{ this.dialog
if (result == undefined) return .open(NewPostComponent, { data: item, width: '90vh' })
this.ac.news.updateNews(item._id, result.title, result.content).pipe(catchError((err)=>{ .afterClosed()
this.sb.open("Wystąpił błąd. Skontaktuj się z obsługą programu.") .subscribe(result => {
return throwError(()=> new Error(err.message)) if (result == undefined) return
})).subscribe((data)=> { this.ac
if (data.status == 200) { .updateNews(item._id, result.title, result.content)
this.ngOnInit() .pipe(
} else { catchError(err => {
this.sb.open("Wystąpił błąd. Skontaktuj się z obsługą programu.") 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.ngOnInit()
} else {
this.sb.open('Wystąpił błąd. Skontaktuj się z obsługą programu.')
}
})
}) })
})
} }
delete(id: string) { delete(id: string) {
this.ac.news.deleteNews(id).subscribe(data => { this.ac.deleteNews(id).subscribe(data => {
if (data.status == 200) { if (data.status == 200) {
this.ngOnInit() this.ngOnInit()
} }
@@ -73,29 +81,47 @@ export class NewsEditComponent implements OnInit {
} }
visibleToggle(item: any) { visibleToggle(item: any) {
this.ac.news.toggleNews(item._id, item.visible).pipe(catchError((err)=>{ this.ac
this.sb.open("Wystąpił błąd. Skontaktuj się z obsługą programu.") .toggleNews(item._id, item.visible)
return throwError(()=> new Error(err.message)) .pipe(
})).subscribe((data)=> { catchError(err => {
if (data.status == 200) { this.sb.open('Wystąpił błąd. Skontaktuj się z obsługą programu.')
this.ngOnInit() return throwError(() => new Error(err.message))
} else { })
this.sb.open("Wystąpił błąd. Skontaktuj się z obsługą programu.") )
} .subscribe(data => {
}) if (data.status == 200) {
this.ngOnInit()
} else {
this.sb.open('Wystąpił błąd. Skontaktuj się z obsługą programu.')
}
})
} }
pinToggle(item:any) { pinToggle(item: any) {
console.log(item.pinned) console.log(item.pinned)
this.ac.news.togglePin(item._id, item.pinned).pipe(catchError((err)=>{ this.ac
this.sb.open("Wystąpił błąd. Skontaktuj się z obsługą programu.") .togglePin(item._id, item.pinned)
return throwError(()=> new Error(err.message)) .pipe(
})).subscribe((data)=> { catchError(err => {
if (data.status == 200) { this.sb.open('Wystąpił błąd. Skontaktuj się z obsługą programu.')
this.ngOnInit() return throwError(() => new Error(err.message))
} else { })
this.sb.open("Wystąpił błąd. Skontaktuj się z obsługą programu.") )
} .subscribe(data => {
}) if (data.status == 200) {
this.ngOnInit()
} else {
this.sb.open('Wystąpił błąd. Skontaktuj się z obsługą programu.')
}
})
}
fullName(n: News): string {
const { author: { fname, surname, uname } } = n;
if (fname || surname) {
return [fname, surname].filter(Boolean).join(' ');
}
return uname;
} }
} }

View File

@@ -0,0 +1,23 @@
import { TestBed } from '@angular/core/testing';
import { NewsEditService } from './news-edit.service';
import { provideHttpClient } from '@angular/common/http';
import { provideHttpClientTesting } from '@angular/common/http/testing';
describe('NewsEditService', () => {
let service: NewsEditService;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
provideHttpClient(),
provideHttpClientTesting()
]
});
service = TestBed.inject(NewsEditService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
});

View File

@@ -0,0 +1,90 @@
import { HttpClient } from '@angular/common/http';
import { Injectable, signal } from '@angular/core';
import { marked } from 'marked';
import { BehaviorSubject, catchError, map, of } from 'rxjs';
import { News } from 'src/app/types/news.model';
import { STATE } from 'src/app/types/state';
import { environment } from 'src/environments/environment';
@Injectable({
providedIn: 'root'
})
export class NewsEditService {
private _news = new BehaviorSubject<(News & {formatted: string})[]>([])
public readonly news = this._news.asObservable()
private _state = signal(STATE.NOT_LOADED);
public readonly state = this._state.asReadonly();
private _error = signal<string | undefined>(undefined);
public readonly error = this._error.asReadonly();
constructor(private http: HttpClient) { }
public refresh() {
this.getNews()
}
private getNews() {
this._state.set(STATE.PENDING)
this.http.get
<News[]>
(environment.apiEndpoint + `/admin/news`, { withCredentials: true, })
.pipe(
catchError((err: Error) => {
this._state.set(STATE.ERROR)
this._error.set(err.message)
return of()
}),
map(i => {
return i.map(v => ({
...v,
formatted: marked.parse(v.content, { breaks: true }).toString()
}))
})
).subscribe(v => {
this._error.set(undefined)
this._news.next(v ?? [])
this._state.set(STATE.LOADED)
})
}
postNews(title: string, content: string) {
return this.http.post<any>(
environment.apiEndpoint + `/admin/news`,
{ title: title, content: content },
{ withCredentials: true }
)
}
deleteNews(id: string) {
return this.http.delete<any>(
environment.apiEndpoint + `/admin/news/${id}`,
{ withCredentials: true }
)
}
toggleNews(id: string, inverter: boolean) {
return this.putNews(id, { visible: !inverter })
}
togglePin(id: string, inverter: boolean) {
return this.putNews(id, { pinned: !inverter })
}
updateNews(id: string, title: string, content: string) {
return this.putNews(id, {
title: title,
content: content,
date: Date.now,
})
}
private putNews(id: string, update: object) {
return this.http.put<any>(
environment.apiEndpoint + `/admin/news/${id}`,
update,
{ withCredentials: true }
)
}
}

View File

@@ -1,43 +1,48 @@
<!-- TODO: Remake the notifications module -->
<form [formGroup]="form" (ngSubmit)="submit()"> <form [formGroup]="form" (ngSubmit)="submit()">
<div formGroupName="recp"> <div formGroupName="recp">
<mat-radio-group formControlName="type"> <mat-radio-group formControlName="type">
<mat-radio-button value="uname"> <mat-radio-button value="uid">
<mat-form-field> <mat-form-field>
<mat-label>Nazwa użytkownika</mat-label> <mat-label>Użytkownik</mat-label>
<input matInput type="text" formControlName="uname"> <app-user-search formControlName="uid" required/>
</mat-form-field> </mat-form-field>
</mat-radio-button> </mat-radio-button>
<mat-radio-button value="room"> <mat-radio-button value="room">
<mat-form-field> <mat-form-field>
<mat-label>Pokój</mat-label> <mat-label>Pokój</mat-label>
<input matInput type="text" formControlName="room"> <input matInput type="text" formControlName="room">
</mat-form-field> </mat-form-field>
</mat-radio-button> </mat-radio-button>
<mat-radio-button value="group" *ngIf="ls.capCheck(8)"> @if (ls.capCheck(8)) {
<mat-form-field> <mat-radio-button value="group">
<mat-label>Grupa</mat-label> <mat-form-field>
<mat-select formControlName="group"> <mat-label>Grupa</mat-label>
<mat-option *ngFor="let item of groups" [value]="item._id">{{item.name}}</mat-option> <mat-select formControlName="group">
</mat-select> @for (item of groups; track item) {
</mat-form-field> <mat-option [value]="item._id">{{item.name}}</mat-option>
</mat-radio-button> }
</mat-radio-group> </mat-select>
</div> </mat-form-field>
</mat-radio-button>
}
</mat-radio-group>
</div>
<mat-form-field>
<mat-label>Tytuł</mat-label>
<input matInput type="text" formControlName="title">
</mat-form-field>
<br>
<mat-form-field> <mat-form-field>
<mat-label>Tytuł</mat-label> <mat-label>Zawartość wiadomości</mat-label>
<input matInput type="text" formControlName="title"> <textarea matInput cdkTextareaAutosize formControlName="body"></textarea>
</mat-form-field> </mat-form-field>
<br> <br>
<mat-form-field> <button mat-fab extended type="submit">
<mat-label>Zawartość wiadomości</mat-label>
<textarea matInput cdkTextareaAutosize formControlName="body"></textarea>
</mat-form-field>
<br>
<button mat-fab extended type="submit">
<mat-icon>send</mat-icon> <mat-icon>send</mat-icon>
Wyślij Wyślij
</button> </button>
</form> </form>
<p *ngIf="success">Udało się wysłać {{success.sent}} z {{success.possible}} = {{success.sent/success.possible | percent}}</p> @if (success) {
<p>Udało się wysłać {{success.sent}} z {{success.possible}} = {{success.sent/success.possible | percent}}</p>
}

View File

@@ -1,3 +1,3 @@
mat-radio-button { mat-radio-button {
display: block; display: block;
} }

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