put in ignore file
This commit is contained in:
@@ -0,0 +1,54 @@
|
||||
import { FormControl, FormGroup } from '@angular/forms';
|
||||
|
||||
export class CommonUtilities {
|
||||
/** Display the blob */
|
||||
static displayFileInNewTab(response:any, defaultFileName:string) {
|
||||
const contentType = response.headers.get('content-type');
|
||||
const blob = new Blob([response.body], { type: contentType });
|
||||
const fileName = this.getFileName(response,defaultFileName);
|
||||
const nav = (window.navigator as any);
|
||||
if (nav.msSaveOrOpenBlob) {
|
||||
nav.msSaveOrOpenBlob(blob, fileName);
|
||||
} else {
|
||||
const data = window.URL.createObjectURL(blob);
|
||||
const link = document.createElement('a');
|
||||
link.href = data;
|
||||
link.target = '_blank';
|
||||
link.click();
|
||||
}
|
||||
}
|
||||
/*** Download the blob ***/
|
||||
static downloadFile(response:any, defaultFileName:string) {
|
||||
const contentType = response.headers.get('content-type');
|
||||
const blob = new Blob([response.body], { type: contentType });
|
||||
const fileName = this.getFileName(response,defaultFileName);
|
||||
const nav = (window.navigator as any);
|
||||
if (typeof nav.msSaveBlob === 'function')
|
||||
{
|
||||
console.log("download the report saveblob");
|
||||
nav.msSaveBlob(blob, fileName);
|
||||
console.log("download the report saveblob done");
|
||||
}
|
||||
else {
|
||||
const link = document.createElement('a');
|
||||
link.href = window.URL.createObjectURL(blob);
|
||||
console.log("no msSaveBlob download the report saveblob done");
|
||||
//link.download? = fileName;
|
||||
link.download = fileName;
|
||||
link.click();
|
||||
}
|
||||
}
|
||||
/** Get the attachment file name */
|
||||
static getFileName(response:any, defaultFileName:string) {
|
||||
const contentDis = response.headers.get('content-disposition');
|
||||
let fileName =defaultFileName;
|
||||
if (contentDis && contentDis.indexOf('attachment') !== -1) {
|
||||
const filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
|
||||
const matches = filenameRegex.exec(contentDis);
|
||||
if (matches != null && matches[1]) {
|
||||
fileName = matches[1].replace(/['"]/g, '');
|
||||
}
|
||||
}
|
||||
return fileName;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
import { inject, Injectable } from '@angular/core';
|
||||
import { HttpClient } from '@angular/common/http';
|
||||
import { firstValueFrom, Observable } from 'rxjs';
|
||||
export function initializeApp_old(appInitService: AppSettingService) {
|
||||
return (): Promise<any> => {
|
||||
return appInitService.loadAppSetting_p();
|
||||
}
|
||||
|
||||
};
|
||||
export function initializeApp() {
|
||||
return (): Promise<any> => {
|
||||
return inject(AppSettingService).loadAppSetting_p();
|
||||
}
|
||||
// return () => inject(AppSettingService).loadAppSetting();
|
||||
};
|
||||
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class AppSettingService {
|
||||
private _appsetting: any;
|
||||
constructor(private http: HttpClient
|
||||
) { }
|
||||
|
||||
public loadAppSetting_p(): Promise<any> {
|
||||
const source$ = this.http.get("config/appsetting.json")
|
||||
const rs$ = firstValueFrom(source$)
|
||||
.then(x => {
|
||||
this._appsetting = x;
|
||||
console.log("[AppSettingService] assign", x);
|
||||
});
|
||||
return rs$;
|
||||
}
|
||||
public loadAppSetting(): Observable<any> {
|
||||
const source$ = this.http.get("config/appsetting.json")
|
||||
return source$;
|
||||
}
|
||||
set appSetting(value: any) {
|
||||
this._appsetting = value;
|
||||
}
|
||||
get appSetting(): any {
|
||||
return this._appsetting;
|
||||
}
|
||||
|
||||
}
|
||||
/* angular 19 new one in app.config.ts
|
||||
provideAppInitializer(initializeApp()),
|
||||
|
||||
/* module put this
|
||||
to use it
|
||||
in app.module.ts
|
||||
add
|
||||
1)
|
||||
providers: [
|
||||
{ provide : APP_INITIALIZER, multi : true, deps : [AppSettingService],
|
||||
useFactory: initializeApp
|
||||
},
|
||||
]
|
||||
|
||||
2)
|
||||
other this one work too.
|
||||
providers: [
|
||||
{
|
||||
provide : APP_INITIALIZER,
|
||||
multi : true,
|
||||
deps : [AppSettingService],
|
||||
useFactory : (appConfigService : AppSettingService) => () => appConfigService.loadAppSetting()
|
||||
}
|
||||
]
|
||||
|
||||
to use it calling something like this
|
||||
export class TestComponent {
|
||||
public test1ServiceUrl: string;
|
||||
|
||||
constructor(public configService: AppConfigService) {
|
||||
this.test1ServiceUrl = this.configService.appSetting.test1ServiceUrl;
|
||||
}
|
||||
}
|
||||
*/
|
||||
@@ -0,0 +1,97 @@
|
||||
import { Injectable, inject } from '@angular/core';
|
||||
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor, HttpInterceptorFn, HttpHandlerFn } from '@angular/common/http';
|
||||
import { Observable, throwError } from 'rxjs';
|
||||
import { catchError } from 'rxjs/operators';
|
||||
|
||||
import { AuthenticationService } from '../user-services';
|
||||
//import { ToastrService } from 'ngx-toastr';
|
||||
import { NavigationExtras, Router } from '@angular/router';
|
||||
/*
|
||||
@Injectable()
|
||||
export class ErrorInterceptor implements HttpInterceptor {
|
||||
//private authenticationService: AuthenticationService;
|
||||
constructor(
|
||||
private router: Router,
|
||||
// private toastr: ToastrService,
|
||||
) { }
|
||||
|
||||
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
|
||||
// console.log("I am intercept to catch error status = 401...", request);
|
||||
return next.handle(request).pipe(catchError(err => {
|
||||
/* no use yet
|
||||
if (err) {
|
||||
switch(err.status) {
|
||||
case 400:
|
||||
if (err.error.errors) {
|
||||
const modalStateErrors = [];
|
||||
for (const key in err.error.errors) {
|
||||
if (err.error.errors[key]) {
|
||||
modalStateErrors.push(err.error.errors[key]);
|
||||
}
|
||||
}
|
||||
throw modalStateErrors;
|
||||
} else {
|
||||
this.toastr.error(err.statusText, err.status);
|
||||
}
|
||||
break;
|
||||
case 401:
|
||||
this.toastr.error(err.statusText, err.status);
|
||||
break;
|
||||
case 404:
|
||||
this.router.navigateByUrl('/not-found');
|
||||
break;
|
||||
case 500:
|
||||
const navigationExtras: NavigationExtras = {state:{error:err.error}};
|
||||
this.router.navigateByUrl('/server-error', navigationExtras);
|
||||
break;
|
||||
default:
|
||||
this.toastr.error('Something unexpected went wrong');
|
||||
console.log("this error interceptor",err);
|
||||
break;
|
||||
}
|
||||
}
|
||||
*/
|
||||
/*
|
||||
if (err.status === 401) {
|
||||
// auto logout if 401 response returned from api Unauthorized
|
||||
// this.authenticationService.logout();
|
||||
//location.reload();
|
||||
const error = err.error.message || err.statusText;
|
||||
console.log("After I Get Error status = 401...", error, err);
|
||||
return throwError(error);
|
||||
}
|
||||
else {
|
||||
console.log("I Get Error .", err);
|
||||
return throwError(err);
|
||||
}
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
*/
|
||||
//new one
|
||||
//https://blog.ninja-squad.com/2022/11/09/angular-http-in-standalone-applications/
|
||||
////////////////
|
||||
export const ErrorInterceptor: HttpInterceptorFn = (req: HttpRequest<unknown>, next: HttpHandlerFn): Observable<HttpEvent<unknown>> => {
|
||||
const authenticationService = inject(AuthenticationService);
|
||||
|
||||
// logger.log(`Request is on its way to ${req.url}`);
|
||||
return next(req).pipe(catchError(err => {
|
||||
if (err.status === 401) {
|
||||
// auto logout if 401 response returned from api Unauthorized
|
||||
// this.authenticationService.logout();
|
||||
//location.reload();
|
||||
const error = err.error.message || err.statusText;
|
||||
// console.log("After I Get Error status = 401...", error, err);
|
||||
return throwError(() => error);
|
||||
}
|
||||
else {
|
||||
console.log("I Get Error .", err);
|
||||
return throwError(() => err);
|
||||
}
|
||||
|
||||
}));
|
||||
}
|
||||
|
||||
////////////////
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
import { HttpClient, HttpErrorResponse, HttpParams } from '@angular/common/http';
|
||||
import { Injectable } from '@angular/core';
|
||||
import { Router } from '@angular/router';
|
||||
import { Observable, throwError } from 'rxjs';
|
||||
import { catchError } from 'rxjs/operators';
|
||||
import { ConfigureUrl } from '../models';
|
||||
import { AppSettingService } from './appsetting';
|
||||
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class HttpUtility {
|
||||
private baseApiUrl: string = "";
|
||||
constructor(private http: HttpClient,
|
||||
private appSetting :AppSettingService,
|
||||
private router: Router) {
|
||||
}
|
||||
/**
|
||||
* getFile
|
||||
* @param url
|
||||
*/
|
||||
public getFileAsText(url: string): Observable<any> {
|
||||
return this.http
|
||||
.get(this.getApiUrl(url), { responseType: 'blob' as 'text' })
|
||||
.pipe(catchError(e => this.handleError(e)));
|
||||
}
|
||||
/**
|
||||
* getFile
|
||||
* @param url
|
||||
*/
|
||||
public getFile(url: string): Observable<any> {
|
||||
return this.http
|
||||
.get(this.getApiUrl(url), { responseType: 'blob' as 'json' })
|
||||
.pipe(catchError(e => this.handleError(e)));
|
||||
}
|
||||
|
||||
/**
|
||||
* handleError
|
||||
* @param response
|
||||
*/
|
||||
private handleError(errorResponse: HttpErrorResponse) {
|
||||
// in a real world app, we may send the server to some remote logging infrastructure
|
||||
// instead of just logging it to the console
|
||||
return throwError(errorResponse);
|
||||
}
|
||||
//get excel file zip file etc ..
|
||||
/*
|
||||
allowedToDisplay = [
|
||||
this.mimeConstant.png,
|
||||
this.mimeConstant.jpeg,
|
||||
this.mimeConstant.jpg,
|
||||
this.mimeConstant.gif,
|
||||
this.mimeConstant.txt,
|
||||
this.mimeConstant.pdf
|
||||
];
|
||||
*/
|
||||
/* how to use it
|
||||
this.http.getFileResponse(`Person/GetPhoto?recordId=${personId}`).pipe(
|
||||
catchError(err => {
|
||||
this.snackBar.error(err || this.constants.error_Getting_photo);
|
||||
return EMPTY;
|
||||
}),
|
||||
finalize(() => {
|
||||
this.spinner.hide();
|
||||
})).subscribe(response => {
|
||||
if (response) {
|
||||
if (isDownload) {
|
||||
CommonUtilities.downloadFile(response);
|
||||
} else {
|
||||
if (response.body && response.body.type) {
|
||||
if (this.allowedToDisplay.includes(response.body.type)) {
|
||||
CommonUtilities.displayFileInNewTab(response);
|
||||
} else {
|
||||
this.temporaryFile = response;
|
||||
this.downloadWarning = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
*/
|
||||
public getFileResponse(url: string, data?: any): Observable<any> {
|
||||
if (data) {
|
||||
return this.http.post(this.getApiUrl(url),
|
||||
data,
|
||||
{ responseType: 'blob', observe: 'response' })
|
||||
.pipe(catchError(e => this.handleError(e)));
|
||||
|
||||
}
|
||||
return this.http
|
||||
.get(this.getApiUrl(url), { responseType: 'blob', observe: 'response' })
|
||||
.pipe(catchError(e => this.handleError(e)));
|
||||
}
|
||||
|
||||
public getFileAsPDF(url: string, data: any): Observable<any> {
|
||||
let updateURL;
|
||||
if (data) {
|
||||
updateURL = url + data;
|
||||
} else {
|
||||
updateURL = url;
|
||||
}
|
||||
return this.http
|
||||
.get(this.getApiUrl(updateURL), { responseType: 'blob' as 'text', observe: 'response' })
|
||||
.pipe(catchError(e => this.handleError(e)));
|
||||
}
|
||||
/**
|
||||
* getApiUrl
|
||||
* @param url
|
||||
*/
|
||||
private getApiUrl(url:string) {
|
||||
const baseUrl = this.appSetting.appSetting.baseUrl;
|
||||
return baseUrl + "/"+ url;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
export * from './utils';
|
||||
export {initializeApp, AppSettingService} from './appsetting';
|
||||
export * from './error.interceptor';
|
||||
export * from './jwt.interceptor';
|
||||
export * from './lookup.service';
|
||||
export * from './httpfile.service';
|
||||
export * from './CommonUtilities';
|
||||
export * from './timeinput';
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,47 @@
|
||||
import { Injectable } from '@angular/core';
|
||||
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor, HttpInterceptorFn, HttpHandlerFn } from '@angular/common/http';
|
||||
import { Observable } from 'rxjs';
|
||||
import { Utils } from './utils';
|
||||
/*
|
||||
@Injectable()
|
||||
export class JwtInterceptor implements HttpInterceptor {
|
||||
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
|
||||
// add authorization header with jwt token if available
|
||||
const currentUser = Utils.getCurrentUser();//localStorage.getItem('currentUser')!;
|
||||
console.log('I am interceptor debug for currentUser obj', currentUser);
|
||||
if (currentUser && currentUser.token) {
|
||||
//console.log('I am interceptor add authorization header with jwt token');
|
||||
request = request.clone({
|
||||
setHeaders: {
|
||||
Authorization: `Bearer ${currentUser.token}`
|
||||
}
|
||||
});
|
||||
}
|
||||
return next.handle(request);
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
new one
|
||||
////////////////
|
||||
*/
|
||||
export const JwtInterceptor: HttpInterceptorFn = (request: HttpRequest<unknown>, next: HttpHandlerFn): Observable<HttpEvent<unknown>> => {
|
||||
//const logger = inject(Logger);
|
||||
//logger.log(`Request is on its way to ${req.url}`);
|
||||
const currentUser = Utils.getCurrentUser();//localStorage.getItem('currentUser')!;
|
||||
// console.log('I am interceptor debug for currentUser obj', currentUser);
|
||||
if (currentUser && currentUser.token && currentUser.token != "") {
|
||||
// console.log('I am interceptor add authorization header with jwt token');
|
||||
request = request.clone({
|
||||
setHeaders: {
|
||||
Authorization: `Bearer ${currentUser.token}`
|
||||
}
|
||||
});
|
||||
}
|
||||
return next(request);
|
||||
}
|
||||
|
||||
////////////////
|
||||
/*
|
||||
providers: [provideHttpClient(withInterceptors([loggerInterceptor]))]
|
||||
*/
|
||||
@@ -0,0 +1,136 @@
|
||||
import { Injectable, Inject , Output} from '@angular/core';
|
||||
import { HttpClient, HttpParams } from '@angular/common/http';
|
||||
import { map } from 'rxjs/operators';
|
||||
import { Observable, of } from 'rxjs';
|
||||
import { ConfigureUrl,Lookup,LookupEdit,ResultModel
|
||||
} from '../models';
|
||||
import { Utils,AppSettingService } from '../shares';
|
||||
|
||||
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class LookupService {
|
||||
msg: string = "[lookupService] ";
|
||||
_lookupByStatus:any;
|
||||
_staffList:any;
|
||||
_clientList:any;
|
||||
_jobList:any;
|
||||
constructor(private http: HttpClient,
|
||||
private appSetting :AppSettingService
|
||||
) {
|
||||
// this default when load look for previous login information
|
||||
// if no need then comment out downthere
|
||||
this.setAllNull();
|
||||
}
|
||||
setAllNull() :void {
|
||||
// this._lhdList = undefined;
|
||||
this._lookupByStatus = {};
|
||||
this._staffList = null;
|
||||
this._clientList = null;
|
||||
this._jobList = null;
|
||||
}
|
||||
loadLookupEditBystatus(type:string): Observable<ResultModel<LookupEdit[]>> {
|
||||
const baseUrl = this.appSetting.appSetting.baseUrl + "/"+ ConfigureUrl.lookupUrl + "/LoadLookupEdit";
|
||||
const params = new HttpParams().append('type', type);
|
||||
console.log(this.msg + "go server this loadLookupEditBystatus is in cache ", type);
|
||||
return this.http.get<ResultModel<LookupEdit[]>>(baseUrl, {params});
|
||||
}
|
||||
loadLookupById(id:number, type:string): Observable<ResultModel<LookupEdit>> {
|
||||
const baseUrl = this.appSetting.appSetting.baseUrl + "/"+ ConfigureUrl.lookupUrl;
|
||||
const params = new HttpParams()
|
||||
.append('id', id)
|
||||
.append('type', type);
|
||||
return this.http.get<ResultModel<LookupEdit>>(baseUrl,{params});
|
||||
}
|
||||
saveLookup(item:LookupEdit): Observable<ResultModel<number>> { //insert Lookup
|
||||
this.setAllNull();
|
||||
let config = { headers : { 'Content-Type': 'application/json' } };
|
||||
const baseUrl = this.appSetting.appSetting.baseUrl + "/"+ ConfigureUrl.lookupUrl;
|
||||
return this.http.post<ResultModel<number>>(baseUrl, item, config);
|
||||
}
|
||||
deleteLookup(id:number): Observable<ResultModel<number>>{
|
||||
const baseUrl = this.appSetting.appSetting.baseUrl + "/"+ ConfigureUrl.lookupUrl;
|
||||
return this.http.delete<ResultModel<number>>(baseUrl + "/" + id );
|
||||
}
|
||||
|
||||
loadLookupBystatus(type:string): Observable<ResultModel<Lookup[]>> {
|
||||
const baseUrl = this.appSetting.appSetting.baseUrl + "/"+ ConfigureUrl.lookupUrl + "/LoadJobs";
|
||||
console.log(this.msg + "loadLookupBystatus", this._lookupByStatus);
|
||||
if (this._lookupByStatus[type])
|
||||
{
|
||||
console.log(this.msg + "Not go server this LoadJobs is in cache ",type);
|
||||
return of(this._lookupByStatus[type]);
|
||||
}
|
||||
else
|
||||
{
|
||||
const params = new HttpParams().append('type', type);
|
||||
console.log(this.msg + "go server this loadLookupBystatus is in cache ", type);
|
||||
return this.http.get<ResultModel<Lookup[]>>(baseUrl, {params})
|
||||
.pipe(map(resultModel => {
|
||||
this._lookupByStatus[type] = resultModel;
|
||||
return resultModel;
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
loadStaffs(): Observable<ResultModel<Lookup[]>> {
|
||||
const baseUrl = this.appSetting.appSetting.baseUrl + "/"+ ConfigureUrl.lookupUrl + "/GetStaffs";
|
||||
/* const params = new HttpParams()
|
||||
.append('id', id)
|
||||
.append('type', type);
|
||||
return this.http.get<ResultModel<LookupEdit>>(baseUrl,{params});
|
||||
*/
|
||||
if (this._staffList != null)
|
||||
{
|
||||
return of(this._staffList);
|
||||
}
|
||||
else
|
||||
{
|
||||
return this.http.get<ResultModel<Lookup[]>>(baseUrl)
|
||||
.pipe(map( x => {
|
||||
this._staffList = x;
|
||||
return x;
|
||||
}));
|
||||
}
|
||||
}
|
||||
loadClients(): Observable<ResultModel<Lookup[]>> {
|
||||
const baseUrl = this.appSetting.appSetting.baseUrl + "/"+ ConfigureUrl.lookupUrl + "/GetClients";
|
||||
/* const params = new HttpParams()
|
||||
.append('id', id)
|
||||
.append('type', type);
|
||||
return this.http.get<ResultModel<LookupEdit>>(baseUrl,{params});
|
||||
*/
|
||||
if (this._clientList != null)
|
||||
{
|
||||
return of(this._clientList);
|
||||
}
|
||||
else
|
||||
{
|
||||
return this.http.get<ResultModel<Lookup[]>>(baseUrl)
|
||||
.pipe(map(resultModel => {
|
||||
this._clientList = resultModel;
|
||||
return resultModel;
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
loadJobs(): Observable<ResultModel<Lookup[]>> {
|
||||
const baseUrl = this.appSetting.appSetting.baseUrl + "/"+ ConfigureUrl.lookupUrl + "/GetJobs";
|
||||
/* const params = new HttpParams()
|
||||
.append('id', id)
|
||||
.append('type', type);
|
||||
return this.http.get<ResultModel<LookupEdit>>(baseUrl,{params});
|
||||
*/
|
||||
if (this._jobList != null)
|
||||
{
|
||||
return of(this._jobList);
|
||||
}
|
||||
else
|
||||
{
|
||||
return this.http.get<ResultModel<Lookup[]>>(baseUrl)
|
||||
.pipe(map(x => {
|
||||
this._jobList = x;
|
||||
return x;
|
||||
}))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { Component, Input, forwardRef, OnInit, OnDestroy } from '@angular/core';
|
||||
import { ControlValueAccessor, NG_VALUE_ACCESSOR,ReactiveFormsModule, FormControl, Validators } from '@angular/forms';
|
||||
import { Subject, takeUntil } from 'rxjs';
|
||||
|
||||
@Component({
|
||||
selector: 'time-input',
|
||||
imports:[ReactiveFormsModule,CommonModule],
|
||||
template: `
|
||||
<input
|
||||
type="text"
|
||||
[formControl]="timeControl"
|
||||
(input)="onInput($event)"
|
||||
(blur)="onBlur()"
|
||||
class="time-input"
|
||||
style="width: 80px; text-align: center;"
|
||||
/>
|
||||
`,
|
||||
providers: [
|
||||
{
|
||||
provide: NG_VALUE_ACCESSOR,
|
||||
useExisting: forwardRef(() => TimeInputComponent),
|
||||
multi: true,
|
||||
},
|
||||
],
|
||||
})
|
||||
export class TimeInputComponent implements ControlValueAccessor, OnInit, OnDestroy {
|
||||
@Input() placeholder: string = 'HH:MM';
|
||||
@Input() initialValue: string = ''; // Added initialValue input
|
||||
@Input() disabled: boolean = false;
|
||||
|
||||
timeControl = new FormControl('', [
|
||||
Validators.pattern(/^([0-2][0-9]:[0-5][0-9])?$/), // Added more precise regex
|
||||
]);
|
||||
|
||||
private destroy$ = new Subject<void>();
|
||||
private _value: string = '';
|
||||
private onChange: (value: string) => void = () => {};
|
||||
private onTouched: () => void = () => {};
|
||||
|
||||
constructor() {}
|
||||
|
||||
ngOnInit(): void {
|
||||
this.timeControl.valueChanges.pipe(takeUntil(this.destroy$)).subscribe((value) => {
|
||||
this.onChange(value || ''); // Pass the value to the parent form
|
||||
});
|
||||
if (this.initialValue) {
|
||||
this.writeValue(this.initialValue);
|
||||
}
|
||||
this.timeControl.disable();
|
||||
if(!this.disabled){
|
||||
this.timeControl.enable();
|
||||
}
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.destroy$.next();
|
||||
this.destroy$.complete();
|
||||
}
|
||||
|
||||
get value(): string {
|
||||
return this._value;
|
||||
}
|
||||
|
||||
set value(val: string) {
|
||||
this._value = val;
|
||||
this.onChange(val);
|
||||
this.onTouched();
|
||||
}
|
||||
|
||||
writeValue(value: string): void {
|
||||
this._value = value || '';
|
||||
this.formatInput(this._value); // Use the formatting function
|
||||
}
|
||||
|
||||
registerOnChange(fn: (value: string) => void): void {
|
||||
this.onChange = fn;
|
||||
}
|
||||
|
||||
registerOnTouched(fn: () => void): void {
|
||||
this.onTouched = fn;
|
||||
}
|
||||
|
||||
setDisabledState(isDisabled: boolean): void {
|
||||
this.disabled = isDisabled;
|
||||
if (isDisabled) {
|
||||
this.timeControl.disable();
|
||||
} else {
|
||||
this.timeControl.enable();
|
||||
}
|
||||
}
|
||||
|
||||
onInput(event: Event): void {
|
||||
let input = (event.target as HTMLInputElement).value;
|
||||
input = input.replace(/[^0-9]/g, ''); // Remove non-numeric characters.
|
||||
|
||||
if (input.length > 4) {
|
||||
input = input.slice(0, 4); // Limit to 4 digits
|
||||
}
|
||||
|
||||
let formatted = '';
|
||||
if (input.length > 2) {
|
||||
formatted = input.slice(0, 2) + ':' + input.slice(2);
|
||||
} else {
|
||||
formatted = input;
|
||||
}
|
||||
this.timeControl.setValue(formatted, { emitEvent: false }); // Prevent infinite loop
|
||||
this.value = formatted;
|
||||
}
|
||||
|
||||
onBlur(): void {
|
||||
this.onTouched();
|
||||
if (this.timeControl.valid) {
|
||||
return;
|
||||
}
|
||||
if (this.timeControl.value?.length === 0) {
|
||||
this.timeControl.setValue('', {emitEvent: false});
|
||||
this.value = '';
|
||||
return
|
||||
}
|
||||
this.formatInput(this.timeControl.value);
|
||||
}
|
||||
|
||||
private formatInput(val: string | null): void {
|
||||
if (!val) {
|
||||
this.timeControl.setValue('', {emitEvent: false});
|
||||
this.value = '';
|
||||
return;
|
||||
}
|
||||
let numbersOnly = val.replace(/[^0-9]/g, '');
|
||||
let formatted = '';
|
||||
|
||||
if (numbersOnly.length > 2) {
|
||||
formatted = numbersOnly.slice(0, 2) + ':' + numbersOnly.slice(2, 4);
|
||||
} else {
|
||||
formatted = numbersOnly;
|
||||
}
|
||||
if (formatted.length === 5 && this.timeControl.valid) {
|
||||
this.timeControl.setValue(formatted, {emitEvent: false});
|
||||
this.value = formatted;
|
||||
} else if (numbersOnly.length <= 2) {
|
||||
this.timeControl.setValue(formatted, {emitEvent: false});
|
||||
this.value = formatted;
|
||||
} else {
|
||||
this.timeControl.setValue('00:00', {emitEvent: false});
|
||||
this.value = '00:00'
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
import moment from "moment";
|
||||
import { Person, User, userRole } from "../models"
|
||||
import { TreeNode } from "primeng/api";
|
||||
|
||||
type MyProName = "fatherId" | "motherId";
|
||||
|
||||
export class Utils {
|
||||
static toBase64 (file:any)
|
||||
{
|
||||
let promise = new Promise((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
reader.readAsDataURL(file);
|
||||
reader.onload = () => resolve(reader.result);
|
||||
reader.onerror = reject;
|
||||
});
|
||||
return promise;
|
||||
}
|
||||
static getBase64(file: any) {
|
||||
let result: any;
|
||||
var reader = new FileReader();
|
||||
reader.readAsDataURL(file);
|
||||
reader.onload = function () {
|
||||
result = reader.result;
|
||||
console.log('tobase64 ', result);
|
||||
};
|
||||
reader.onerror = function (error) {
|
||||
console.log('Error: ', error);
|
||||
};
|
||||
}
|
||||
static getCurrentUser(): User {
|
||||
|
||||
let myUser = new User();
|
||||
myUser.username = "";
|
||||
const obj = sessionStorage.getItem('currentUser');
|
||||
//const obj = localStorage.getItem('currentUser');
|
||||
if (obj != undefined) {
|
||||
let user = JSON.parse(obj);
|
||||
myUser.firstName = user.firstName;
|
||||
myUser.id = user.id;
|
||||
myUser.lastName = user.lastName;
|
||||
myUser.role = user.role;
|
||||
myUser.username = user.username;
|
||||
myUser.email = user.email;
|
||||
myUser.token = user.token;
|
||||
myUser.phone = user.phone;
|
||||
myUser.department = user.department;
|
||||
myUser.position = user.position;
|
||||
myUser.managerEmail = user.managerEmail;
|
||||
|
||||
|
||||
|
||||
}
|
||||
// console.log("[util] getcurrentUser",myUser);
|
||||
return myUser;
|
||||
}
|
||||
static setLocalStore(user: User): void {
|
||||
if (user && user.token) {
|
||||
// store user details and jwt token in local storage to keep user logged in between page refreshes
|
||||
// localStorage.setItem('currentUser', JSON.stringify(user));
|
||||
sessionStorage.setItem('currentUser', JSON.stringify(user));
|
||||
}
|
||||
}
|
||||
|
||||
static getLastMonth(): Date {
|
||||
let result = moment().subtract(1, 'months').toDate();
|
||||
result.setDate(1);
|
||||
return result;
|
||||
}
|
||||
static getHome(): string {
|
||||
let result ="";
|
||||
const user = this.getCurrentUser();
|
||||
const urole = user.role;
|
||||
if (urole == userRole.Accounting)
|
||||
{
|
||||
result = "staffworkw";
|
||||
}
|
||||
else if (urole == userRole.Admin)
|
||||
{
|
||||
result = "staff";
|
||||
}
|
||||
else if (urole == userRole.ServiceManager)
|
||||
{
|
||||
result = "servicetask";
|
||||
}
|
||||
else if (urole == userRole.WorkShop)
|
||||
{
|
||||
result = "staffwork";
|
||||
}
|
||||
else if (urole == userRole.Normal)
|
||||
{
|
||||
result = "staff";
|
||||
}
|
||||
return result;
|
||||
}
|
||||
static getTimeStr(val:Date): string {
|
||||
let result = "00:00";
|
||||
if (val)
|
||||
{
|
||||
const hh = val.getHours();
|
||||
const min = val.getMinutes();
|
||||
if (hh < 10)
|
||||
result = '0' + hh.toString();
|
||||
else
|
||||
result = hh.toString();
|
||||
if (min < 10)
|
||||
result = result + ":0" + min.toString();
|
||||
else
|
||||
result = result + ":" + min.toString();
|
||||
|
||||
}
|
||||
return result;
|
||||
}
|
||||
static canRunReport(role: number): boolean {
|
||||
let result = false;
|
||||
if (role == userRole.Admin)
|
||||
result = true;
|
||||
return result;
|
||||
}
|
||||
static getUserRole(user: User): number {
|
||||
/*
|
||||
sysadmin
|
||||
request_manager
|
||||
ward_user
|
||||
*/
|
||||
let ret = 0;
|
||||
if (user) {
|
||||
// console.log("utils user", user);
|
||||
if (user.role)
|
||||
ret = user.role;
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
static getIsAuth(): boolean {
|
||||
const user = this.getCurrentUser();
|
||||
if (user.username != "") {
|
||||
return true;
|
||||
}
|
||||
else
|
||||
return false;
|
||||
}
|
||||
static getAdminRoleName(): number {
|
||||
return userRole.Admin;
|
||||
}
|
||||
static clearCurrentUser(): void {
|
||||
sessionStorage.clear();
|
||||
//localStorage.clear();
|
||||
}
|
||||
|
||||
static formatNode(item:Person): TreeNode
|
||||
{
|
||||
let label = item.lastName + " " + item.firstName;
|
||||
let key = item.id.toString();
|
||||
let node: TreeNode ={
|
||||
key,
|
||||
label,
|
||||
type: 'person',
|
||||
data: {title: item.title, name: label, image: item.image},
|
||||
icon: 'pi pi-user'
|
||||
};
|
||||
|
||||
return node;
|
||||
}
|
||||
|
||||
static getChildForParentId(proName: MyProName , pid: number,childressNodes: Person[]): TreeNode[] {
|
||||
let result: TreeNode[] =[];
|
||||
let tree_node_child: TreeNode[];
|
||||
let node:TreeNode;
|
||||
let item: Person;
|
||||
const children = childressNodes.filter(x => x[proName] == pid);
|
||||
for (let c = 0; c < children.length; c++)
|
||||
{
|
||||
item = children[c];
|
||||
node = this.formatNode(item);
|
||||
tree_node_child = this.getChildForParentId(proName,item.id, childressNodes);
|
||||
console.log("getChildForParentId childressNodes item tree_node_child ", childressNodes, item, tree_node_child);
|
||||
if (tree_node_child.length > 0)
|
||||
{
|
||||
node.expanded = true;
|
||||
node.children = tree_node_child;
|
||||
}
|
||||
result.push(node);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
static populateNode(proName: MyProName, familyList: Person[]): TreeNode[] {
|
||||
let familyTree: TreeNode[] = [];
|
||||
let node:TreeNode;
|
||||
let child_nodes:TreeNode[];
|
||||
|
||||
let childressNodes:Person[];
|
||||
|
||||
let item: Person;
|
||||
const topNodes = familyList.filter(x => x[proName]! < 1);
|
||||
childressNodes = familyList.filter(x => x[proName]! > 0);
|
||||
for(let i = 0; i < topNodes.length; i++)
|
||||
{
|
||||
item = topNodes[i];
|
||||
node = Utils.formatNode(item);
|
||||
child_nodes = this.getChildForParentId(proName, item.id,childressNodes);
|
||||
console.log("populate getchildrenForParentId", child_nodes);
|
||||
if (child_nodes.length > 0)
|
||||
{
|
||||
node.expanded = true;
|
||||
node.children = child_nodes;
|
||||
}
|
||||
familyTree.push(node);
|
||||
//childressNodes =
|
||||
}
|
||||
return familyTree;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user