Skip to content

Commit

Permalink
admin: craete/delete user
Browse files Browse the repository at this point in the history
  • Loading branch information
NewGrafon committed Dec 22, 2023
1 parent 1c7b56b commit 03ea85d
Show file tree
Hide file tree
Showing 3 changed files with 257 additions and 10 deletions.
72 changes: 69 additions & 3 deletions src/app/pages/admin/admin.component.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,78 @@
import { Component } from '@angular/core';
import { Component, OnInit } from '@angular/core';
import { IAppUser } from '../../static/types/app-user.type';
import { RouterLink } from '@angular/router';
import { ApiService } from '../../services/api/api.service';
import { AppComponent } from '../../app.component';
import { UserRole } from '../../static/enums/user.enums';
import { TelegramService } from '../../services/telegram/telegram.service';

@Component({
selector: 'app-admin',
standalone: true,
imports: [],
imports: [
RouterLink,
],
templateUrl: './admin.component.html',
styleUrl: './admin.component.scss',
})
export class AdminComponent {
export class AdminComponent implements OnInit {
users: IAppUser[] | undefined;

deletingUser: boolean = false;
async deleteUser(id: number): Promise<void> {
if (this.deletingUser) {
return;
}
this.deletingUser = true;

this.telegram.showPopup({
title: 'Подтверждение',
message: 'Вы уверены что хотите удалить аккаунт?',
buttons: [
{
id: '64',
type: 'ok',
},
{
id: '0',
type: 'cancel',
},
],
},
async (btnId: string) => {
if (btnId === '64') {
const result = await this.api.deleteUser(id);
if (result) {
this.telegram.showPopup({
title: 'Успех!',
message: 'Пользователь успешно удален',
});
window.location.reload();
}
}
});

this.deletingUser = false;
}

constructor(
private readonly api: ApiService,
private readonly telegram: TelegramService,
) {

}

async ngOnInit() {
const interval = setInterval(async () => {
if (AppComponent.appUser !== undefined) {
clearInterval(interval);
if (AppComponent.appUser.role !== UserRole.Admin) {
window.location.reload();
}

this.users = (await this.api.getAllUsers())?.filter((user: IAppUser) => user?.id !== AppComponent.appUser?.id);
console.log(this.users);
}
}, 16.67);
}
}
139 changes: 139 additions & 0 deletions src/app/pages/create-user/create-user.component.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
import { Component } from '@angular/core';
import { FormControl, FormGroup, FormsModule, ReactiveFormsModule, Validators } from '@angular/forms';
import { Router, RouterLink } from '@angular/router';
import { TelegramService } from '../../services/telegram/telegram.service';
import { ApiService } from '../../services/api/api.service';
import { CookieService } from 'ngx-cookie-service';
import { IApiCreateUser } from '../../static/interfaces/create-user.interfaces';
import { UserRole } from '../../static/enums/user.enums';

@Component({
selector: 'app-create-user',
standalone: true,
imports: [
FormsModule,
ReactiveFormsModule,
RouterLink,
],
templateUrl: './create-user.component.html',
styleUrl: './create-user.component.scss',
})
export class CreateUserComponent {
private static instance: CreateUserComponent;

createUserForm = new FormGroup({
firstname: new FormControl('', [Validators.required, Validators.minLength(1)]),
lastname: new FormControl('', [Validators.required, Validators.minLength(1)]),
password: new FormControl('', [Validators.required, Validators.minLength(1)]),
role: new FormControl('', [Validators.required]),
});

get firstnameValid(): boolean {
const valid = !(this.createUserForm.controls.firstname.invalid && this.createUserForm.controls.firstname.touched);

if (valid) {
this.formCheck();
}

return valid;
}

get lastnameValid(): boolean {
const valid = !(this.createUserForm.controls.lastname.invalid && this.createUserForm.controls.lastname.touched);

if (valid) {
this.formCheck();
}

return valid;
}

get passwordValid(): boolean {
const valid = !(this.createUserForm.controls.password.invalid && this.createUserForm.controls.password.touched);

if (valid) {
this.formCheck();
}

return valid;
}

get roleValid(): boolean {
const valid = (
this.createUserForm.controls.role.value !== '' ||
this.createUserForm.controls.role.untouched
);

if (valid) {
this.formCheck();
}

return valid;
}

formCheck(): void {
if (
this.createUserForm.controls.firstname.valid &&
this.createUserForm.controls.lastname.valid &&
this.createUserForm.controls.password.valid &&
this.createUserForm.controls.role.value !== ''
) {
this.telegram.MainButton.setText('Продолжить');
this.telegram.MainButton.onClick(this.onSubmit);
this.telegram.MainButton.show();
} else {
this.telegram.MainButton.offClick(this.onSubmit);
this.telegram.MainButton.hide();
}
}

onSubmitting: boolean = false;

async onSubmit(): Promise<void> {
const _this = CreateUserComponent.instance;

if (_this.onSubmitting) {
return;
}
_this.onSubmitting = true;

_this.telegram.MainButton.showProgress(false);
const body: IApiCreateUser = {
firstname: _this.createUserForm.controls.firstname.value as string,
lastname: _this.createUserForm.controls.lastname.value as string,
password: _this.createUserForm.controls.password.value as string,
role: _this.createUserForm.controls.role.value as UserRole,
};

const result = await _this.api.createUser(body);
if (result) {
_this.telegram.showPopup({
title: 'Успех!',
message: `Пользователь успешно создан. Сообщите работнику пароль, после закрытия этого окна вы больше не сможете просмотреть его. Пароль: "${body.password}"`,
buttons: [{
type: 'ok',
text: 'Ок',
}],
});
_this.telegram.MainButton.hide();
await _this.router.navigateByUrl('/admin');
window.location.reload();
}

_this.telegram.MainButton.offClick(_this.onSubmit);
_this.telegram.MainButton.hideProgress();

_this.onSubmitting = false;
}

constructor(
private readonly telegram: TelegramService,
private readonly api: ApiService,
private readonly router: Router,
private readonly cookieService: CookieService,
) {
CreateUserComponent.instance = this;
}

protected readonly UserRole = UserRole;
}
56 changes: 49 additions & 7 deletions src/app/services/api/api.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { CookieService } from 'ngx-cookie-service';
import { COOKIE_TOKEN } from '../../static/consts/token.const';
import { TelegramService } from '../telegram/telegram.service';
import { IAppUser } from '../../static/types/app-user.type';
import { IApiCreateUser } from '../../static/interfaces/create-user.interfaces';

@Injectable({
providedIn: 'root',
Expand All @@ -19,7 +20,7 @@ export class ApiService {
private readonly api = ky.create({
prefixUrl: '/api/',
headers: {
authorization: this.cookieService.get(COOKIE_TOKEN)
authorization: this.cookieService.get(COOKIE_TOKEN),
},
retry: 0,
hooks: {
Expand All @@ -32,13 +33,13 @@ export class ApiService {
message: body.message as string,
buttons: [{
type: 'ok',
text: 'Ок'
}]
})
text: 'Ок',
}],
});
}
}
]
}
},
],
},
});

public async auth(body: IApiAuth): Promise<IApiAuthResponse> {
Expand Down Expand Up @@ -78,4 +79,45 @@ export class ApiService {

return result;
}

public async getAllUsers(): Promise<IAppUser[]> {
let result: IAppUser[];

try {
result = await this.api.get('users/get_all').json() || [];
} catch (e) {
console.error(e);
result = [];
}

return result;
}

public async createUser(body: IApiCreateUser): Promise<boolean> {
let result: boolean = false;

try {
result = await this.api.post('users/create', {
json: body,
}).json();
} catch (e) {
console.error(e);
result = false;
}

return result;
}

public async deleteUser(id: number): Promise<boolean> {
let result: boolean;

try {
result = await this.api.delete(`users/${id}`).json();
} catch (e) {
console.error(e);
result = false;
}

return result;
}
}

0 comments on commit 03ea85d

Please sign in to comment.