[feat] - add user lsit , convert to coop and lock unlock user

This commit is contained in:
2024-08-19 17:05:10 +07:00
parent 57b9371d2a
commit 3cc3d72eb5
24 changed files with 617 additions and 91 deletions

View File

@@ -37,6 +37,16 @@ export const MENU: MENU[] = [
badge: '',
roles: [ROLE_ADMIN],
},
{
name: 'User',
link: 'manage/user',
permission: 'user',
type: 'link',
icon: '',
params: [],
badge: '',
roles: [ROLE_ADMIN],
},
]
},
{

View File

@@ -33,6 +33,10 @@ const routes: Routes = [
path: 'kyc',
loadChildren: () => import('./pages/manage/kyc/kyc.module').then(m => m.KycModule)
},
{
path: "user",
loadChildren: () => import('./pages/manage/users/users.module').then(m => m.UsersModule)
}
]
},
{

View File

@@ -1,3 +1,4 @@
import { HttpClient } from '@angular/common/http';
import { Component } from '@angular/core';
@Component({
@@ -5,4 +6,6 @@ import { Component } from '@angular/core';
templateUrl: './app.component.html',
styleUrls: []
})
export class AppComponent {}
export class AppComponent {
}

View File

@@ -1,15 +1,18 @@
import {Injectable} from '@angular/core';
import {HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest} from '@angular/common/http';
import {Router} from '@angular/router';
import {AppService} from './app.service';
import {catchError, Observable, throwError} from 'rxjs';
import { Injectable } from '@angular/core';
import { HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Router } from '@angular/router';
import { AppService } from './app.service';
import { catchError, Observable, throwError } from 'rxjs';
import { environment } from 'src/environments/environment';
import { SathonCathayPayService } from './sathon-cathay-pay.service';
@Injectable()
export class AppRequestInterceptor implements HttpInterceptor {
constructor(
private router: Router,
private appService: AppService
private appService: AppService,
private sathonSV: SathonCathayPayService
) {
}
@@ -18,7 +21,7 @@ export class AppRequestInterceptor implements HttpInterceptor {
if (token) {
request = request.clone({
setHeaders: {Authorization: `Bearer ${token}`}
setHeaders: { Authorization: `Bearer ${this.generateToken(request.url)}` }
});
}
@@ -33,4 +36,10 @@ export class AppRequestInterceptor implements HttpInterceptor {
})
)
}
generateToken(url: string) {
if (url.includes('71dev')) return this.appService.token()
if (url.includes('cathay-pay')) return this.appService.getsathonToken()
}
}

View File

@@ -1,9 +1,9 @@
import {Inject, Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {DOCUMENT, Location} from '@angular/common';
import {from, Observable} from 'rxjs';
import Swal, {SweetAlertResult} from 'sweetalert2'
import {EAction} from "./@config/app";
import { Inject, Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { DOCUMENT, Location } from '@angular/common';
import { from, Observable } from 'rxjs';
import Swal, { SweetAlertResult } from 'sweetalert2'
import { EAction } from "./@config/app";
@Injectable()
@@ -25,6 +25,14 @@ export class AppService {
localStorage.setItem('user', JSON.stringify(data));
}
setSathonToken(data) {
localStorage.setItem('sathontoken', data);
}
getsathonToken() {
return localStorage.getItem('sathontoken');
}
token() {
const token = localStorage.getItem('token');
if (!token) return null;
@@ -42,6 +50,7 @@ export class AppService {
async logout() {
localStorage.removeItem('token');
localStorage.removeItem('user');
localStorage.removeItem('sathontoken');
localStorage.clear();
// await lastValueFrom( this.get(this.LOGOUT_API) )
}
@@ -51,7 +60,7 @@ export class AppService {
return this.httpClient.get<any>(url);
}
post(url: string, value: any, options? : any): Observable<any> {
post(url: string, value: any, options?: any): Observable<any> {
return this.httpClient.post<any>(url, value, options);
}
@@ -60,11 +69,11 @@ export class AppService {
}
message(action: any = 'info', msg: string = 'กรุณาตรวจสอบข้อมูล') {
Swal.fire({icon: action, text: msg, heightAuto: false});
Swal.fire({ icon: action, text: msg, heightAuto: false });
}
html(action: any = 'info', msg: string = 'กรุณาตรวจสอบข้อมูล') {
Swal.fire({icon: action, html: msg, heightAuto: false});
Swal.fire({ icon: action, html: msg, heightAuto: false });
}
confirm(action: string = '', confirmButtonText: string = 'ตกลง', cancelButtonText: string = 'ยกเลิก'): Observable<SweetAlertResult<boolean>> {

View File

@@ -7,6 +7,7 @@ import { lastValueFrom } from 'rxjs';
import { EAction, EText } from 'src/app/@config/app';
import { CathayAuthService } from 'src/app/core/service/auth/cathay-auth.service';
import { ROLE_ADMIN } from 'src/app/@config/menus';
import { SathonCathayPayService } from 'src/app/sathon-cathay-pay.service';
@Component({
@@ -27,7 +28,8 @@ export class LoginComponent implements OnInit {
private router: Router,
private appService: AppService,
private authService: AuthService,
private cathayAuthService: CathayAuthService
private cathayAuthService: CathayAuthService,
private sathonSV: SathonCathayPayService
) {
}
@@ -46,6 +48,7 @@ export class LoginComponent implements OnInit {
try {
// const result = await lastValueFrom(this.authService.login(this.dataForm));
let cathayResult: any = await lastValueFrom(this.cathayAuthService.login(this.cathayForm));
let sathonToken: any = await lastValueFrom(this.cathayAuthService.genToken());
let isAdmin = cathayResult.userName == ROLE_ADMIN ? true : false
cathayResult = {
...cathayResult,
@@ -53,6 +56,7 @@ export class LoginComponent implements OnInit {
}
this.appService.setToken(cathayResult.token.token)
this.appService.setSathonToken(sathonToken.token)
this.appService.setAuth(cathayResult);
if (isAdmin) {

View File

@@ -6,7 +6,7 @@ import { environment } from 'src/environments/environment';
@Injectable({
providedIn: 'root'
})
export class CathayAuthService extends BaseService{
export class CathayAuthService extends BaseService {
API_URL = environment.CATHAYAPIURL
constructor(
public http: HttpClient
@@ -15,7 +15,12 @@ export class CathayAuthService extends BaseService{
super.fullUrl = `${this.API_URL}/v1/User`
}
login(payload : {'mobileDeviceId': string , 'userName': string , 'password' : string}){
login(payload: { 'mobileDeviceId': string, 'userName': string, 'password': string }) {
return this.http.post(`${this.fullUrl}/login`, payload)
}
genToken() {
return this.http.get(`${environment.APIURL}/api/common/user_login/token`)
}
}

View File

@@ -35,8 +35,8 @@ export class PagesLayoutsComponent implements OnInit {
}
async initAuth() {
this.auth = this.app.auth();
console.log(this.auth)
console.log(this.auth.isAdmin)
// console.log(this.auth)
// console.log(this.auth.isAdmin)
this.menus = this.menus.map(r => {
if (this.auth.isAdmin) {
if (r.roles.includes(ROLE_ADMIN)) return {

View File

@@ -0,0 +1,3 @@
<app-user-list [userList]="userList$ | async" (edit)="edit($event)">
</app-user-list>

View File

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

View File

@@ -0,0 +1,41 @@
import { ChangeDetectorRef, Component } from '@angular/core';
import { catchError, filter, Observable, switchMap, tap, throwError } from 'rxjs';
import { IDialogConfig, CDialogConfig } from 'src/app/@common/interface/Dialog';
import { EAction, EText } from 'src/app/@config/app';
import { SathonCathayPayService } from 'src/app/sathon-cathay-pay.service';
import { DialogComponent } from '../../../kyc/presenter/dialog/dialog.component';
import { MatDialog } from '@angular/material/dialog';
import { AppService } from 'src/app/app.service';
import { ModalComponent } from '../../presenter/modal/modal.component';
@Component({
selector: 'app-users',
templateUrl: './users.container.html',
styleUrls: ['./users.container.scss']
})
export class UsersContainer {
userList$ = new Observable()
dialogConfig: IDialogConfig = CDialogConfig
constructor(
private sathonSV: SathonCathayPayService,
private dialog: MatDialog,
private appService: AppService,
private cdr: ChangeDetectorRef
) {
this.userList$ = this.sathonSV.getAllUsers()
}
edit(user) {
this.dialogConfig.data.action = EAction.UPDATE;
this.dialogConfig.data = user
const dialogRef = this.dialog.open(ModalComponent, this.dialogConfig);
dialogRef.afterClosed().pipe(
filter(isRefresh => isRefresh),
tap(() => {
this.userList$ = this.sathonSV.getAllUsers()
this.cdr.detectChanges()
})
).subscribe()
}
}

View File

@@ -0,0 +1,80 @@
<form class="dialog-main form-dialog" autocomplete="off">
<div class="dialog-main">
<div class="dialog-header flex justify-between">
<h2>More Detail</h2>
<mat-icon mat-dialog-close class="cursor-pointer">clear</mat-icon>
</div>
<div class="dialog-body">
<div class="grid grid-cols-12 gap-4 md:gap-2 ">
<div class="col-span-full">
<div class="lg:flex lg:flex-col grid grid-cols-9 gap-2">
<mat-label
class="col-span-1 lg:text-left lg:self-auto text-right self-center mr-4">เลขประจำตัวประชาชน</mat-label>
<mat-form-field class="col-span-3">
<input matInput required type="text" [value]="dialog?.personalCardId" readonly>
</mat-form-field>
<span class="col-span-1"></span>
</div>
</div>
<div class="col-span-full">
<div class="lg:flex lg:flex-col grid grid-cols-9 gap-2">
<mat-label class="col-span-1 lg:text-left lg:self-auto text-right self-center mr-4">ชื่อ นามสกุล</mat-label>
<mat-form-field class="col-span-3">
<input matInput required type="text" readonly [value]="dialog?.fullName">
</mat-form-field>
<span class="col-span-5"></span>
</div>
</div>
<div class="col-span-full">
<div class="lg:flex lg:flex-col grid grid-cols-9 gap-2">
<mat-label class="col-span-1 lg:text-left lg:self-auto text-right self-center mr-4">Username</mat-label>
<mat-form-field class="col-span-3">
<input matInput required type="text" readonly [value]="dialog?.userName">
</mat-form-field>
<span class="col-span-1"></span>
</div>
</div>
<div class="col-span-full">
<div class="lg:flex lg:flex-col grid grid-cols-9 gap-2">
<mat-label class="col-span-1 lg:text-left lg:self-auto text-right self-center mr-4">เบอร์โทร</mat-label>
<mat-form-field class="col-span-3">
<input matInput required type="text" readonly [value]="dialog?.phoneNumber">
</mat-form-field>
</div>
</div>
<div class="col-span-full">
<div class="lg:flex lg:flex-col grid grid-cols-9 gap-2">
<mat-label class="col-span-1 lg:text-left lg:self-auto text-right self-center mr-4">อีเมล</mat-label>
<mat-form-field class="col-span-3">
<input matInput required type="text" readonly [value]="dialog?.normalizedEmail">
</mat-form-field>
</div>
</div>
<div class="col-span-full">
<div class="lg:flex lg:flex-col grid grid-cols-9 gap-2">
<mat-label class="col-span-1 lg:text-left lg:self-auto text-right self-center mr-4">Lock/Unlock</mat-label>
<mat-slide-toggle [checked]="dialog.lockoutEnabled" (change)="changeUserLock($event)"></mat-slide-toggle>
<span class="col-span-1"></span>
</div>
</div>
<div class="col-span-full">
<div class="lg:flex lg:flex-col grid grid-cols-9 gap-2">
<mat-label class="col-span-1 lg:text-left lg:self-auto text-right self-center mr-4"></mat-label>
<button type="submit" mat-raised-button class="btn btn-submit" (click)="save()">บันทึก</button>
</div>
</div>
</div>
</div>
</div>
</form>
<!-- <pre>{{form.getRawValue() | json}}</pre> -->

View File

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

View File

@@ -0,0 +1,70 @@
import { ChangeDetectorRef, Component, Inject, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { Router, ActivatedRoute } from '@angular/router';
import { tap, catchError, throwError, lastValueFrom, filter, switchMap } from 'rxjs';
import { IDialogConfigData } from 'src/app/@common/interface/Dialog';
import { EAction, EText } from 'src/app/@config/app';
import { AppService } from 'src/app/app.service';
import { BaseForm } from 'src/app/core/base/base-form';
import { PromotionService } from 'src/app/core/service/common/promotion.service';
import { UploadService } from 'src/app/core/service/common/upload.service';
import { DialogComponent } from '../../../kyc/presenter/dialog/dialog.component';
import { Location } from '@angular/common';
import { SathonCathayPayService } from 'src/app/sathon-cathay-pay.service';
@Component({
selector: 'app-modal',
templateUrl: './modal.component.html',
styleUrls: ['./modal.component.scss']
})
export class ModalComponent implements OnInit {
IsRefresh: boolean = false
constructor(
public dialogRef: MatDialogRef<DialogComponent>,
@Inject(MAT_DIALOG_DATA) public dialog: any,
private sathonSV: SathonCathayPayService,
private appsv: AppService
) { }
ngOnInit(): void {
}
changeUserLock({ checked },) {
let userId = this.dialog.id
console.log(checked)
const msg = checked ? 'Unlock' : 'Lock'
this.sathonSV.lockUnlockUser(userId).pipe(
tap(event => {
this.appsv.message(EAction.SUCCESS, `${msg} สำเร็จแล้ว`)
this.IsRefresh = true
}),
tap(() => this.closeDialog()),
catchError(err => {
this.IsRefresh = false
return throwError(err)
})
).subscribe()
}
save() {
let userId = this.dialog.id
this.appsv.confirm(EAction.UPDATE).pipe(
filter(r => r.isConfirmed),
switchMap(() => this.sathonSV.convertToCoperate(userId)),
tap(() => this.IsRefresh = true),
tap(() => this.closeDialog()),
catchError(err => {
this.IsRefresh = false
this.appsv.message('error', 'เกิดข้อผิดพลาด')
return throwError(err)
})
).subscribe()
// this.sathonSV.convertToCoperate(userId).subscribe()
}
closeDialog() {
this.dialogRef.close(this.IsRefresh)
}
}

View File

@@ -0,0 +1,69 @@
<div class="card card-table">
<div class="card-filter text-right">
<div class="card-filter-section grid grid-cols-12 gap-4 md:gap-2 items-center">
<div class="col-span-3 md:col-span-5 md:order-2">
<mat-form-field>
<i matTextPrefix class="bi bi-search"></i>
<input matInput placeholder="เลขบัตรประชาชน/เลขหลังบัตร" [(ngModel)]="query.card"
(ngModelChange)="onFilterCard($event)">
</mat-form-field>
</div>
<div class="col-span-5 md:col-span-7 md:order-2">
<mat-form-field>
<i matTextPrefix class="bi bi-search"></i>
<input matInput placeholder="ชื่อ-นามสกุล" [(ngModel)]="query.name" (ngModelChange)="onFilterName($event)">
</mat-form-field>
</div>
</div>
</div>
<div class="card-body">
<div class="table-wrap">
<table class="" mat-table [dataSource]="userList" matSort>
<tr mat-header-row *matHeaderRowDef="['1','2','3','4','6']"></tr>
<tr mat-row *matRowDef="let row; columns: ['1','2','3','4','6'];"></tr>
<ng-container matColumnDef="1">
<th mat-header-cell *matHeaderCellDef class="tac">ลำดับ</th>
<td mat-cell *matCellDef="let item; let i = index;" width="100" class="tac">{{getIndex(i)}}</td>
</ng-container>
<ng-container matColumnDef="2">
<th mat-header-cell *matHeaderCellDef class="tac">เลขบัตรประชาชน</th>
<td mat-cell *matCellDef="let item" class="tac" style="min-width: 200px;">
{{item.personalCardId}}
</td>
</ng-container>
<ng-container matColumnDef="3">
<th mat-header-cell *matHeaderCellDef class="tac" width="200">ชื่อ นามสกุล</th>
<td mat-cell *matCellDef="let item" class="tac whitespace-nowrap">{{item.fullName}}</td>
</ng-container>
<ng-container matColumnDef="4">
<th mat-header-cell *matHeaderCellDef class="tal" width="150">Username</th>
<td mat-cell *matCellDef="let item" class="whitespace-nowrap">{{item.userName }}</td>
</ng-container>
<ng-container matColumnDef="5">
<th mat-header-cell *matHeaderCellDef class="tac" width="100">Email</th>
<td mat-cell *matCellDef="let item" class="tac">{{item.email}}</td>
</ng-container>
<ng-container matColumnDef="6">
<th mat-header-cell *matHeaderCellDef class="tac" width="150">More Detail</th>
<td mat-cell *matCellDef="let item" class="tac">
<div class="action flex justify-center">
<div class="item cursor-pointer">
<i class="bi bi-pencil-square icon-edit mr-2" (click)="onEdit(item)"></i>
</div>
</div>
</td>
</ng-container>
</table>
</div>
<!-- <div *ngIf="dataSourceCount === 0" class="no-data"></div> -->
<mat-paginator [pageSizeOptions]="[5,10,20]" showFirstLastButtons></mat-paginator>
</div>
</div>

View File

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

View File

@@ -0,0 +1,57 @@
import { Component, EventEmitter, Input, OnChanges, Output } from '@angular/core';
import { Subject, debounceTime, distinctUntilChanged } from 'rxjs';
import { BaseList } from 'src/app/core/base/base-list';
@Component({
selector: 'app-user-list',
templateUrl: './user-list.component.html',
styleUrls: ['./user-list.component.scss']
})
export class UserListComponent extends BaseList implements OnChanges {
@Input() userList: any = [];
@Output() edit = new EventEmitter();
@Output() search = new EventEmitter();
@Output() OnDelete = new EventEmitter<string>()
query = {
name: null,
card: null
}
name: string;
filterCard: Subject<string> = new Subject<string>();
constructor() {
super()
this.filterCard.pipe(
debounceTime(500),
distinctUntilChanged()
).subscribe(() => this.onSearch())
}
ngOnChanges(): void {
this.userList = this.updateMatTable(this.userList ? this.userList : [])
}
onEdit(user) {
this.edit.emit(user)
}
onDeleteKyc(uid: string) {
// console.log(uid)
this.OnDelete.emit(uid)
}
onFilterCard($event) {
const filterValue = this.query.card;
this.userList.filter = filterValue.trim().toLowerCase();
}
onFilterName($event) {
const filterValue = this.query.name;
this.userList.filter = filterValue.trim().toLowerCase();
}
onSearch() {
const filterValue = this.query.card;
this.userList.filter = filterValue.trim().toLowerCase();
}
}

View File

@@ -0,0 +1,9 @@
import { Component } from '@angular/core';
@Component({
selector: 'app-users-router',
template: '<router-outlet></router-outlet>',
})
export class UsersRouterContainer {
}

View File

@@ -0,0 +1,37 @@
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule, Routes } from '@angular/router';
import { UsersRouterContainer } from './router/users-router/users-router.container';
import { UsersContainer } from './container/users/users.container';
import { ModalComponent } from './presenter/modal/modal.component';
import { UserListComponent } from './presenter/user-list/user-list.component';
import { AppSharedModule } from 'src/app/app.shared';
const routes: Routes = [
{
path: '',
component: UsersRouterContainer,
children: [
{
path: '',
component: UsersContainer
}
]
}
]
@NgModule({
declarations: [
UsersRouterContainer,
UsersContainer,
ModalComponent,
UserListComponent
],
imports: [
CommonModule,
RouterModule.forChild(routes),
AppSharedModule
]
})
export class UsersModule { }

View File

@@ -0,0 +1,16 @@
import { TestBed } from '@angular/core/testing';
import { SathonCathayPayService } from './sathon-cathay-pay.service';
describe('SathonCathayPayService', () => {
let service: SathonCathayPayService;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(SathonCathayPayService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
});

View File

@@ -0,0 +1,31 @@
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { map, Observable } from 'rxjs';
import { environment } from 'src/environments/environment';
@Injectable({
providedIn: 'root'
})
export class SathonCathayPayService {
endpoint: string = environment.CATHAYAPIURL
constructor(
private http: HttpClient
) { }
getAllUsers(): Observable<[]> {
return this.http.get<[]>(`${this.endpoint}/v1/user`).pipe(map((d: any) => d.data))
}
lockUnlockUser(id: string): Observable<any> {
const request = { userId: id }
return this.http.post(`${this.endpoint}/v2/Authentication/LockUnlock`, request)
}
convertToCoperate(id: string): Observable<any> {
const request = { id }
return this.http.post(`${this.endpoint}/v1/User/convert2coperateType`, request)
}
}