Commit cd544c60 by Ooh-Ao
parents 06fcd6a9 b9e6b4d1
import { CommonModule } from "@angular/common";
import { ChangeDetectionStrategy, Component, ElementRef, ViewChild } from '@angular/core';
import { NgSelectModule } from "@ng-select/ng-select";
import { TranslateModule, TranslateService } from "@ngx-translate/core";
import { FormsModule } from "@angular/forms";
import swal from 'sweetalert';
import { MatPaginator, PageEvent } from "@angular/material/paginator";
import { SharedModule } from "../../../shared/shared.module";
import { UserProfileModel } from "../../models/user.model";
import { TokenService } from "../../../shared/services/token.service";
import { FileUploadModule } from 'ng2-file-upload';
import { FileItem, FileUploader, ParsedResponseHeaders } from "ng2-file-upload";
import { environment } from "../../../../environments/environment";
import { AdminService } from "../../services/admin.service";
@Component({
selector: 'app-admin-manage',
standalone: true,
imports: [
CommonModule,
SharedModule,
TranslateModule,
NgSelectModule,
FormsModule,
FileUploadModule
],
templateUrl: './admin-manage.component.html',
styleUrl: './admin-manage.component.css'
})
export class AdminManageComponent {
@ViewChild('closeModal') public childModal?: ElementRef;
@ViewChild('modalDetail') public modalDetail?: ElementRef;
action = "new";
allSelected = false;
someSelected = false;
confirmPassword = ""
itemsList: UserProfileModel[] = []
filterList: UserProfileModel[] = []
selectedItems = new Map<string, boolean>();
selectModel: UserProfileModel = new UserProfileModel()
empList: UserProfileModel[] = []
descName = 'engName'
pageIndex = 0;
uploaderProfile: FileUploader | undefined;
uploadErrorMsg: string = "";
get searchTerm(): string {
return this._searchTerm;
}
set searchTerm(val: string) {
this.pageIndex = 0;
this.allSelected = false
this._searchTerm = val;
if (val != '') {
this.filterList = this.filter(val);
} else {
this.updatePagedItems()
}
}
_searchTerm = "";
constructor(private adminService: AdminService, public translate: TranslateService, private tokenService: TokenService) {
this.uploadConfig()
}
uploadConfig() {
this.uploaderProfile = new FileUploader({
url: environment.baseUrl + "/api/upload-image",
isHTML5: true,
authToken: this.tokenService.getToken()!,
});
this.uploaderProfile.onAfterAddingFile = (fileItem: FileItem) => {
fileItem.withCredentials = false;
this.uploadErrorMsg = "";
while (this.uploaderProfile!.queue.length > 1) {
this.uploaderProfile!.queue[0].remove();
}
if (fileItem.file.size > 5000000) {
this.uploadErrorMsg = "maximum file size 5mb.";
swal("Opp!!", "ไม่สามารถอัพโหลดได้", "info");
fileItem.isCancel = true;
return;
}
if (fileItem.file.type!.indexOf("image") === -1) {
this.uploadErrorMsg = "please upload image only.";
swal("Opp!!", "ไม่สามารถอัพโหลดได้", "info");
fileItem.isCancel = true;
return;
}
fileItem.upload();
};
this.uploaderProfile.onCompleteItem = (
item: FileItem,
response: string,
status: number,
headers: ParsedResponseHeaders
) => {
if (item.isSuccess) {
const res = JSON.parse(response);
console.log("res", res);
this.selectModel.picture = res.filename
swal(res.message, "บันทึกสำเร็จ", "success");
} else {
this.uploadErrorMsg = "cannot upload file.";
swal("Opp!!", "ไม่สามารถอัพโหลดได้", "info");
}
};
}
ngOnInit(): void {
this.adminService.getLists().subscribe(result => {
this.itemsList = result.filter(e => e.role == 99)
this.updatePagedItems()
})
}
filter(v: string) {
return this.itemsList?.filter(
(x) =>
x.memberId?.toLowerCase().indexOf(v.toLowerCase()) !== -1 ||
x.username?.toLowerCase().indexOf(v.toLowerCase()) !== -1 ||
x.email?.toLowerCase().indexOf(v.toLowerCase()) !== -1 ||
x.phoneNumber?.toLowerCase().indexOf(v.toLowerCase()) !== -1 ||
x.getRole()?.toLowerCase().indexOf(v.toLowerCase()) !== -1 ||
x.getStatus()?.toLowerCase().indexOf(v.toLowerCase()) !== -1 ||
x.getFullname()?.toLowerCase().indexOf(v.toLowerCase()) !== -1
);
}
delete(item: UserProfileModel) {
swal({
title: "Are you sure?",
text: "You won't be able to revert this!",
icon: "warning",
dangerMode: true,
buttons: ["Cancel", "Yes,Delete it!"],
})
.then((willDelete: any) => {
if (willDelete) {
this.adminService.delete(item).subscribe(result => {
swal("Save Success!!", "บันทึกข้อมูลสำเร็จ", "success");
this.ngOnInit()
})
}
});
}
new() {
this.action = 'add'
this.selectModel = new UserProfileModel()
}
view(item: UserProfileModel) {
this.action = 'edit'
this.confirmPassword = ''
this.selectModel = new UserProfileModel(item)
console.log(this.selectModel)
}
save() {
swal({
title: "Are you sure?",
text: "คุณต้องการบันทึกหรือไม่",
icon: "warning",
dangerMode: false,
buttons: ["Cancel", "Confirm"],
})
.then((willDelete: any) => {
if (willDelete) {
this.selectModel.role = 99
if (this.action == 'add') {
this.adminService.save(this.selectModel).subscribe(result => {
console.log(result)
swal("Save Success!!", "บันทึกข้อมูลสมาชิก", "success");
this.ngOnInit()
this.childModal?.nativeElement.click()
})
} else if (this.action == 'edit') {
this.adminService.update(this.selectModel).subscribe(result => {
console.log(result)
swal("Update Success!!", "บันทึกข้อมูลสมาชิก", "success");
this.ngOnInit()
this.childModal?.nativeElement.click()
})
}
}
});
}
updatePagedItems() {
const startIndex = this.pageIndex * 10;
const endIndex = startIndex + 10;
this.filterList = this.itemsList.slice(startIndex, endIndex);
}
toggleAll(event: any) {
this.allSelected = event.target.checked;
this.selectedItems.clear();
this.itemsList.forEach(item => {
this.selectedItems.set(item.memberId, this.allSelected);
});
this.someSelected = this.itemsList.some(item => this.selectedItems.get(item.memberId));
}
onCheckboxChange(memberId: string) {
const isSelected = this.selectedItems.get(memberId) || false;
this.selectedItems.set(memberId, !isSelected);
this.allSelected = this.itemsList.every(item => this.selectedItems.get(item.memberId));
this.someSelected = this.itemsList.some(item => this.selectedItems.get(item.memberId));
}
deleteSelect() {
let employeeInfo = '';
this.selectedItems.forEach((isSelected, memberId) => {
if (isSelected) {
const user = this.itemsList.find(user => user.memberId === memberId);
if (user) {
employeeInfo += `${this.translate.instant('Fullname')}: ${user.getFullname()}\n`;
}
}
});
swal({
title: "Are you sure?",
text: employeeInfo,
icon: "warning",
dangerMode: true,
buttons: ["Cancel", "Yes, Delete it!"],
})
.then((willDelete: any) => {
if (willDelete) {
this.selectedItems.forEach((isSelected, memberId) => {
if (isSelected) {
const user = this.itemsList.find(user => user.memberId === memberId);
if (user) {
this.adminService.delete(user).subscribe(result => {
swal("Save Success!!", "บันทึกข้อมูลสำเร็จ", "success");
this.ngOnInit();
});
}
}
});
}
});
}
adjustSelect(status: number) {
let title = "Are you sure?"
let employeeInfo = ''; // ตัวแปรสำหรับเก็บข้อมูลพนักงาน
this.selectedItems.forEach((isSelected, memberId) => {
if (isSelected) {
const user = this.itemsList.find(user => user.memberId === memberId);
if (user) {
employeeInfo += `${this.translate.instant('Fullname')}: ${user.getFullname()}\n`;
}
}
});
swal({
title: title,
text: employeeInfo,
icon: "warning",
dangerMode: false,
buttons: ["Cancel", "Confirm"],
})
.then((willDelete: any) => {
if (willDelete) {
this.selectedItems.forEach((isSelected, memberId) => {
if (isSelected) {
const user = this.itemsList.find(user => user.memberId === memberId);
if (user) {
user.status = status
this.adminService.update(user).subscribe(result => {
swal("Save Success!!", "บันทึกข้อมูลสำเร็จ", "success");
this.ngOnInit();
});
}
}
});
}
});
}
filterEmp(empId: string) {
this.selectModel = this.empList.filter(e => e.memberId == empId)[0]
}
}
:host {
display: block;
}
.small-html {
font-size: 0.85rem; /* ลดขนาดฟอนต์ */
line-height: 1.2; /* ลดระยะบรรทัด */
max-height: 150px; /* จำกัดความสูง */
overflow-y: auto; /* ถ้าเนื้อหายาวเกิน ให้เลื่อนดูได้ */
display: block;
}
.border-radius-1{
border-radius: 0.50rem;
}
.font-14{
font-size: 14px;
}
.font-16{
font-size: 16px;
}
.font-24{
font-size: 24px;
}
.font-36{
font-size: 36px;
}
.page {
display: flex;
height: auto;
flex-direction: column;
}
.hs-tab-active {
background-color: rgb(21, 76, 156) !important;
border-color: rgb(21, 76, 156) !important;
color: #FFFFFF !important;
}
.active {
background-color: rgb(21, 76, 156) !important;
border-color: rgb(21, 76, 156) !important;
color: #FFFFFF !important;
}
.border-color{
border: 8px solid rgb(255, 255, 255);
}
.ti-btn-amber-full{
background-color: #fcd34d;
color: #FFFFFF;
}
\ No newline at end of file
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-common',
templateUrl: './common.component.html',
styleUrls: ['./common.component.css']
})
export class CommonComponent implements OnInit {
constructor() { }
ngOnInit() {
}
}
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { CommonComponent } from './common.component';
import { RouterModule, Routes } from '@angular/router';
import { SharedModule } from '../../shared/shared.module';
import { QuillModule } from 'ngx-quill';
export const admin: Routes = [
{
path: 'admin', children: [{
//////////////MyJob/////////////////
path: 'home',
loadComponent: () =>
import('./home-common/home-common.component').then((m) => m.HomeCommonComponent),
},
{
path: 'member-manage',
loadComponent: () =>
import('./user-management/user-setting/user-setting.component').then((m) => m.UserSettingComponent),
},
{
path: 'manage-companys',
loadComponent: () =>
import('./company-manage/company-manage.component').then((m) => m.CompanyManageComponent),
},
{
path: 'manage-articles',
loadComponent: () =>
import('./article-manage/article-manage.component').then((m) => m.ArticleManageComponent),
},
{
path: 'admin-manage',
loadComponent: () =>
import('./admin-manage/admin-manage.component').then((m) => m.AdminManageComponent),
},
{
path: 'pdpa-manage',
loadComponent: () =>
import('./pdpa-manage/pdpa-manage.component').then((m) => m.PdpaManageComponent),
},
{
path: 'company-departments',
loadComponent: () =>
import('./company-department/company-department.component').then((m) => m.CompanyDepartmentComponent),
},
{
path: 'country-registration',
loadComponent: () =>
import('./company-department/country-registration/country-registration.component').then((m) => m.CountryRegistrationComponent),
},
{
path: 'category-company',
loadComponent: () =>
import('./company-department/category-company/category-company.component').then((m) => m.CategoryCompanyComponent),
},
{
path: 'degree-manage',
loadComponent: () =>
import('./company-department/degree-manage/degree-manage.component').then((m) => m.DegreeManageComponent),
},
{
path: 'job-types',
loadComponent: () =>
import('./company-department/job-type/job-type.component').then((m) => m.JobTypeComponent),
},
{
path: 'provinces',
loadComponent: () =>
import('./company-department/province/province.component').then((m) => m.ProvinceComponent),
},
{
path: 'admin-manage',
loadComponent: () =>
import('./admin-manage/admin-manage.component').then((m) => m.AdminManageComponent),
},
{
path: 'position',
loadComponent: () =>
import('./company-department/company-position/company-position.component').then((m) => m.CompanyPositionComponent),
},
{
path: 'career-cluster',
loadComponent: () =>
import('./company-department/career-cluster/career-cluster.component').then((m) => m.CareerClusterComponent),
},
//////////////MyPortal/////////////////
{
path: 'portal-category-list',
loadComponent: () =>
import('./myportal/portal-category-list/portal-category-list.component').then((m) => m.PortalCategoryListComponent),
},
{
path: 'view-list-excel',
loadComponent: () =>
import('./myportal/view-list-excel/view-list-excel.component').then((m) => m.ViewListExcelComponent),
},
{
path: 'view-list-doc',
loadComponent: () =>
import('./myportal/view-list-doc/view-list-doc.component').then((m) => m.ViewListDocComponent),
},
{
path: 'view-list-course',
loadComponent: () =>
import('./myportal/view-list-course/view-list-course.component').then((m) => m.ViewListCourseComponent),
},
{
path: 'excel-report',
loadComponent: () =>
import('./myportal/excel-report/excel-report.component').then((m) => m.ExcelReportComponent),
},
{
path: 'portal-create-category',
loadComponent: () =>
import('./myportal/portal-create-category/portal-create-category.component').then((m) => m.PortalCreateCategoryComponent),
},
{
path: 'list-excell',
loadComponent: () =>
import('./myportal/list-excell/list-excell.component').then((m) => m.ListExcelComponent),
},
{
path: 'list-course',
loadComponent: () =>
import('./myportal/list-course/list-course.component').then((m) => m.ListCourseComponent),
},
{
path: 'list-doc',
loadComponent: () =>
import('./myportal/list-doc/list-doc.component').then((m) => m.ListDocComponent),
},
{
path: 'excel-list',
loadComponent: () =>
import('./myportal/set-excel-reports/excel-list/excel-list.component').then((m) => m.ExcelListComponent),
},
{
path: 'datasource-table',
loadComponent: () =>
import('./myportal/datasource-table/datasource-table.component').then((m) => m.DatasourceTableComponent),
},
{
path: 'excel-report-toggle',
loadComponent: () =>
import('./myportal/set-excel-reports/excel-report-toggle/excel-report-toggle.component').then((m) => m.ExcelReportToggleComponent),
},
{
path: 'management',
loadComponent: () =>
import('./myportal/management/management.component').then((m) => m.ManagementComponent),
},
{
path: 'portal-category-list-approve',
loadComponent: () =>
import('./myportal/management/portal-category-list-approve/portal-category-list-approve.component').then((m) => m.PortalCategoryListApproveComponent),
},
{
path: 'approve-excel',
loadComponent: () =>
import('./myportal/management/portal-category-list-approve/approve-excel/approve-excel.component').then((m) => m.ApproveExcelComponent),
},
{
path: 'approve-doc',
loadComponent: () =>
import('./myportal/management/portal-category-list-approve/approve-doc/approve-doc.component').then((m) => m.ApproveDocComponent),
},
{
path: 'approve-course',
loadComponent: () =>
import('./myportal/management/portal-category-list-approve/approve-course/approve-course.component').then((m) => m.ApproveCourseComponent),
},
{
path: 'approved-list',
loadComponent: () =>
import('./myportal/management/approved-list/approved-list.component').then((m) => m.ApprovedListComponent),
},
{
path: 'view-list-excel',
loadComponent: () =>
import('./myportal/management/approved-list/view-list-excel/view-list-excel.component').then((m) => m.ViewListExcelComponent),
},
{
path: 'view-list-excel/:type',
loadComponent: () =>
import('./myportal/management/approved-list/view-list-excel/view-list-excel.component').then((m) => m.ViewListExcelComponent),
},
{
path: 'view-list-doc',
loadComponent: () =>
import('./myportal/management/approved-list/view-list-doc/view-list-doc.component').then((m) => m.ViewListDocComponent),
},
{
path: 'view-list-doc/:type',
loadComponent: () =>
import('./myportal/management/approved-list/view-list-doc/view-list-doc.component').then((m) => m.ViewListDocComponent),
},
{
path: 'view-list-course',
loadComponent: () =>
import('./myportal/management/approved-list/view-list-course/view-list-course.component').then((m) => m.ViewListCourseComponent),
},
{
path: 'view-list-course/:type',
loadComponent: () =>
import('./myportal/management/approved-list/view-list-course/view-list-course.component').then((m) => m.ViewListCourseComponent),
},
//////////////emp/////////////////
{
path: 'emp/department',
loadComponent: () =>
import('./employee/department/department.component').then((m) => m.DepartmentComponent),
},
{
path: 'emp/position',
loadComponent: () =>
import('./employee/position/position.component').then((m) => m.PositionComponent),
},
]
}
];
@NgModule({
imports: [
CommonModule,
RouterModule.forChild(admin),
QuillModule.forRoot(),
],
exports: [RouterModule],
declarations: [CommonComponent]
})
export class CommonManageModule {
static routes = admin;
}
import { Component, ElementRef, ViewChild } from '@angular/core';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
import { Router, RouterModule } from '@angular/router';
import { SharedModule } from '../../../../shared/shared.module';
import { TranslateModule, TranslateService } from '@ngx-translate/core';
import swal from 'sweetalert';
import { MatPaginator } from '@angular/material/paginator';
import { FormsModule } from '@angular/forms';
import { NgSelectModule } from '@ng-select/ng-select';
import { CommonModule } from '@angular/common';
import { FileUploadModule } from 'ng2-file-upload';
import { FileItem, FileUploader, ParsedResponseHeaders } from "ng2-file-upload";
import { environment } from '../../../../../environments/environment';
import { TokenService } from '../../../../shared/services/token.service'
import { QuillModule } from 'ngx-quill';
import { MatDialog, MatDialogModule } from '@angular/material/dialog';
import { CareerClusterService } from '../../../services/career-cluster.service';
import { CareerClusterModel } from '../../../models/career-cluster.model';
@Component({
selector: 'app-career-cluster',
standalone: true,
imports: [
CommonModule,
SharedModule,
TranslateModule,
NgSelectModule,
FormsModule,
MatPaginator,
RouterModule,
FileUploadModule,
QuillModule,
MatDialogModule
],
templateUrl: './career-cluster.component.html',
styleUrl: './career-cluster.component.css',
})
export class CareerClusterComponent {
quillConfig = {
toolbar: [
['link'], // เพิ่มปุ่มลิงก์
['bold', 'italic', 'underline', 'strike'], // toggled buttons
['blockquote', 'code-block'],
[{ 'header': 1 }, { 'header': 2 }], // custom button values
[{ 'list': 'ordered' }, { 'list': 'bullet' }],
[{ 'script': 'sub' }, { 'script': 'super' }], // superscript/subscript
[{ 'indent': '-1' }, { 'indent': '+1' }], // outdent/indent
[{ 'direction': 'rtl' }], // text direction
[{ 'size': ['small', false, 'large', 'huge'] }], // custom dropdown
[{ 'header': [1, 2, 3, 4, 5, 6, false] }],
[{ 'color': [] }, { 'background': [] }], // dropdown with defaults from theme
[{ 'align': [] }],
['clean'], // remove formatting button
]
};
@ViewChild('closeModal') public childModal?: ElementRef;
@ViewChild('modalDetail') public modalDetail?: ElementRef;
@ViewChild("CareerClusterModel") CareerClusterModel: any;
@ViewChild('profileChangeInput') profileChangeInputRef!: ElementRef;
dialogRef: any
currentContentTab: number = 1;
currentExcerptTab: number = 1;
action = "new";
allSelected = false;
someSelected = false;
itemsList: CareerClusterModel[] = [];
filterList: CareerClusterModel[] = [];
selectModel: CareerClusterModel = new CareerClusterModel();
selectedItems = new Map<string, boolean>();
// empList: CareerClusterModel[] = [];
// descName = 'engName';
pageIndex = 0;
uploaderProfile: FileUploader | undefined;
uploadErrorMsg: string = "";
modalStatus: "add" | "edit" = "add"
get searchTerm(): string {
return this._searchTerm;
}
set searchTerm(val: string) {
this.pageIndex = 0;
this.allSelected = false;
this._searchTerm = val;
if (val != '') {
this.filterList = this.filter(val);
} else {
this.updatePagedItems();
}
}
_searchTerm = "";
constructor(
private careercluster: CareerClusterService,
public translate: TranslateService,
private tokenService: TokenService,
private router: Router,
private dialog: MatDialog,
) {
}
getPosition() {
this.careercluster.getList().subscribe({
next: (response: CareerClusterModel[]) => {
this.itemsList = response.map((x: any) => new CareerClusterModel(x, this.translate));
console.log('ข้อมูลตำแหน่ง (itemsList)', this.itemsList);
this.updatePagedItems();
},
error: (error) => {
console.error('error cant get position', error);
swal("ข้อผิดพลาด", "ไม่สามารถดึงข้อมูลตำแหน่งได้", "error");
}
});
}
ngOnInit(): void {
this.getPosition();
}
filter(v: string) {
return this.itemsList?.filter(
(x) =>
x.careerClusterId?.toLowerCase().indexOf(v.toLowerCase()) !== -1 ||
x.thName?.toLowerCase().indexOf(v.toLowerCase()) !== -1 ||
x.engName?.toLowerCase().indexOf(v.toLowerCase()) !== -1 ||
x.remark?.toLowerCase().indexOf(v.toLowerCase()) !== -1
// x.getStatus().toLowerCase().indexOf(v.toLowerCase()) !== -1
);
}
delete(item: CareerClusterModel) {
swal({
title: "คุณแน่ใจหรือไม่?",
text: "คุณจะไม่สามารถกู้คืนข้อมูลนี้ได้!",
icon: "warning",
dangerMode: true,
buttons: ["ยกเลิก", "ใช่, ลบเลย!"],
})
.then((willDelete: any) => {
if (willDelete) {
const newPosition = new CareerClusterModel(item)
this.careercluster.deleteCareerCluster(newPosition).subscribe(result => {
swal("ลบสำเร็จ!!", "ลบข้อมูลสำเร็จ", "success");
this.ngOnInit();
}, error => {
console.error("เกิดข้อผิดพลาดในการลบ:", error);
swal("ข้อผิดพลาด!!", "ไม่สามารถลบข้อมูลได้", "error");
});
}
});
}
new() {
this.action = 'add';
this.selectModel = new CareerClusterModel();
// this.selectModel.status = 1;
this.selectModel.careerClusterId = "";
this.selectModel.thName = "";
this.selectModel.engName = "";
this.selectModel.remark = "";
}
view(item: CareerClusterModel) {
this.action = 'edit';
this.selectModel = new CareerClusterModel(item);
console.log(this.selectModel);
}
save() {
console.log('Before Save, selectModel is:', this.selectModel);
swal({
title: "คุณแน่ใจหรือไม่?",
text: "คุณต้องการบันทึกหรือไม่",
icon: "warning",
dangerMode: false,
buttons: ["ยกเลิก", "ยืนยัน"],
})
.then((willSave: any) => {
if (willSave) {
this.careercluster.postCareerCluster(this.selectModel).subscribe(result => {
console.log(result);
swal("บันทึกสำเร็จ!!", "บันทึกข้อมูลสมาชิก", "success");
this.ngOnInit();
this.childModal?.nativeElement.click();
}, error => {
console.error("เกิดข้อผิดพลาดในการบันทึก/อัปเดต:", error);
swal("ข้อผิดพลาด!!", "ไม่สามารถบันทึก/อัปเดตข้อมูลได้", "error");
});
}
});
}
updatePagedItems() {
const startIndex = this.pageIndex * 10;
const endIndex = startIndex + 10;
this.filterList = this.itemsList.slice(startIndex, endIndex);
}
toggleAll(event: any) {
this.allSelected = event.target.checked;
this.selectedItems.clear();
this.itemsList.forEach(item => {
this.selectedItems.set(item.careerClusterId, this.allSelected);
});
this.someSelected = this.itemsList.some(item => this.selectedItems.get(item.careerClusterId));
}
onCheckboxChange(careerClusterId: string) {
const isSelected = this.selectedItems.get(careerClusterId) || false;
this.selectedItems.set(careerClusterId, !isSelected);
this.allSelected = this.itemsList.every(item => this.selectedItems.get(item.careerClusterId));
this.someSelected = this.itemsList.some(item => this.selectedItems.get(item.careerClusterId));
}
deleteSelect() {
let employeeInfo = '';
this.selectedItems.forEach((isSelected, careerClusterId) => {
if (isSelected) {
const user = this.itemsList.find(user => user.careerClusterId === careerClusterId);
if (user) {
employeeInfo += `${this.translate.instant('thName')}: ${user.thName}\n`;
}
}
});
swal({
title: "Are you sure?",
text: employeeInfo,
icon: "warning",
dangerMode: true,
buttons: ["Cancel", "Yes, Delete it!"],
})
.then((willDelete: any) => {
if (willDelete) {
this.selectedItems.forEach((isSelected, careerClusterId) => {
if (isSelected) {
const user = this.itemsList.find(user => user.careerClusterId === careerClusterId);
if (user) {
const newPosition = new CareerClusterModel(user)
this.careercluster.deleteCareerCluster(newPosition).subscribe(result => {
swal("Save Success!!", "บันทึกข้อมูลสำเร็จ", "success");
this.ngOnInit();
});
}
}
});
}
});
}
// openDialog() {
// this.dialogRef = this.dialog.open(this.CareerClusterModel, {
// width: '1100px',
// disableClose: false,
// });
// }
// closeDialog() {
// this.dialogRef.close()
// }
}
/* tslint:disable:no-unused-variable */
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';
import { CategoryCompanyComponent } from './category-company.component';
describe('CategoryCompanyComponent', () => {
let component: CategoryCompanyComponent;
let fixture: ComponentFixture<CategoryCompanyComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ CategoryCompanyComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(CategoryCompanyComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
import { Component, ElementRef, OnInit, TemplateRef, ViewChild } from '@angular/core';
import { TranslateModule, TranslateService } from '@ngx-translate/core';
import { MatDialog } from '@angular/material/dialog';
import swal from 'sweetalert';
import { CommonModule } from '@angular/common';
import { SharedModule } from '../../../../shared/shared.module';
import { NgSelectModule } from '@ng-select/ng-select';
import { FormsModule } from '@angular/forms';
import { MatPaginator } from '@angular/material/paginator';
import { FileUploadModule } from 'ng2-file-upload';
import { PdpaConfigComponent } from '../../pdpa-manage/pdpa-config/pdpa-config.component';
import { QuillModule } from 'ngx-quill';
import { CategoryModel } from '../../../models/category.model';
import { CategoryCompanyService } from '../../../services/category-company.service';
@Component({
standalone: true,
imports: [
CommonModule,
SharedModule,
TranslateModule,
NgSelectModule,
FormsModule,
FileUploadModule,
QuillModule
],
selector: 'app-category-company',
templateUrl: './category-company.component.html',
styleUrls: ['./category-company.component.css']
})
export class CategoryCompanyComponent implements OnInit {
@ViewChild('closeModal') public childModal?: ElementRef;
@ViewChild('modalDetail') modalDetail!: TemplateRef<any>;
currentTab = 1
allSelected = false;
someSelected = false;
itemsList: CategoryModel[] = []
filterList: CategoryModel[] = []
category: CategoryModel = new CategoryModel()
selectedItems = new Map<string, boolean>();
pageIndex = 0;
modalStatus: "add" | "edit" = "add"
isSaving = false;
get searchTerm(): string {
return this._searchTerm;
}
set searchTerm(val: string) {
this.pageIndex = 0;
this.allSelected = false
this._searchTerm = val;
if (val != '') {
this.filterList = this.filter(val);
} else {
this.updatePagedItems()
}
}
_searchTerm = "";
constructor(private categoryCompanyService: CategoryCompanyService, public translate: TranslateService, private modal: MatDialog) {
}
ngOnInit(): void {
this.categoryCompanyService.list().subscribe(res => {
this.itemsList = res.map(item => new CategoryModel(item, this.translate));
this.filterList = [...this.itemsList];
});
}
filter(v: string) {
return this.itemsList?.filter(
(x) =>
x.categoryId?.toLowerCase().indexOf(v.toLowerCase()) !== -1 ||
x.thName?.toLowerCase().indexOf(v.toLowerCase()) !== -1 ||
x.engName?.toLowerCase().indexOf(v.toLowerCase()) !== -1
);
}
new() {
this.modalStatus = 'add'
this.category = new CategoryModel();
}
view(item: CategoryModel) {
this.modalStatus = 'edit';
this.category = new CategoryModel(item, this.translate);
}
save() {
swal({
title: "Are you sure?",
text: "คุณต้องการบันทึกหรือไม่",
icon: "warning",
dangerMode: false,
buttons: ["Cancel", "Confirm"],
})
.then((willDelete: any) => {
if (willDelete) {
if (this.modalStatus == 'add') {
console.log(this.category);
this.categoryCompanyService.post(this.category).subscribe(result => {
swal("Save Success!!", "บันทึกประเภทสำเร็จ", "success");
this.ngOnInit()
this.childModal?.nativeElement.click()
})
} else if (this.modalStatus == 'edit') {
const respone = new CategoryModel(this.category);
this.categoryCompanyService.post(respone).subscribe(result => {
console.log(result)
swal("Update Success!!", "บันทึกประเภทสำเร็จ", "success");
this.ngOnInit()
this.childModal?.nativeElement.click()
})
}
}
});
}
deletecategory(item: CategoryModel) {
const versionText = `${this.translate.instant('category')}: ${item.thName}`;
swal({
title: "Are you sure?",
text: `Confirm to delete :\n${versionText}\!`,
icon: "warning",
dangerMode: true,
buttons: ["Cancel", "Yes,Delete it!"],
}).then((willDelete: any) => {
if (willDelete) {
const res = new CategoryModel(item)
this.categoryCompanyService.delete(res).subscribe(result => {
swal("Delete Success!!", "ลบข้อมูลสำเร็จ", "success");
this.ngOnInit();
});
}
});
}
deleteSelect() {
let categoryConfig = '';
this.selectedItems.forEach((isSelected, res) => {
if (isSelected) {
const category = this.itemsList.find(category => category.categoryId === res) as CategoryModel;
if (category) {
categoryConfig += `${this.translate.instant('category')}: ${category.thName}\n`;
}
}
});
swal({
title: "Are you sure?",
text: categoryConfig,
icon: "warning",
dangerMode: true,
buttons: ["Cancel", "Yes, Delete it!"],
})
.then((willDelete: any) => {
if (willDelete) {
this.selectedItems.forEach((isSelected, res) => {
if (isSelected) {
const category = this.itemsList.find(category => category.categoryId === res);
if (category) {
const newcategory = new CategoryModel(category)
this.categoryCompanyService.delete(newcategory).subscribe(result => {
swal("Delete Success!!", "ลบข้อมูลที่เลือกสำเร็จ", "success");
this.ngOnInit();
});
}
}
});
}
});
}
updatePagedItems() {
const startIndex = this.pageIndex * 10;
const endIndex = startIndex + 10;
this.filterList = this.itemsList.slice(startIndex, endIndex);
}
toggleAll(event: any) {
this.allSelected = event.target.checked;
this.selectedItems.clear();
this.itemsList.forEach(item => {
this.selectedItems.set(item.categoryId, this.allSelected);
});
this.someSelected = this.itemsList.some(item => this.selectedItems.get(item.categoryId));
}
onCheckboxChange(categoryId: string) {
const isSelected = this.selectedItems.get(categoryId) || false;
this.selectedItems.set(categoryId, !isSelected);
this.allSelected = this.itemsList.every(item => this.selectedItems.get(item.categoryId));
this.someSelected = this.itemsList.some(item => this.selectedItems.get(item.categoryId));
}
filterEmp(empId: string) {
this.category = this.itemsList.filter(e => e.categoryId == empId)[0]
}
}
import { Component, ElementRef, ViewChild } from '@angular/core';
import { Router, RouterModule } from '@angular/router';
import { SharedModule } from '../../../shared/shared.module';
import { TranslateModule, TranslateService } from '@ngx-translate/core';
import { MatPaginator } from '@angular/material/paginator';
import { FormsModule } from '@angular/forms';
import { NgSelectModule } from '@ng-select/ng-select';
import { CommonModule } from '@angular/common';
@Component({
selector: 'app-company-department',
standalone: true,
imports: [
CommonModule,
SharedModule,
TranslateModule,
NgSelectModule,
FormsModule,
MatPaginator,
RouterModule,
],
templateUrl: './company-department.component.html',
styleUrl: './company-department.component.css',
})
export class CompanyDepartmentComponent {
ngOnInit(): void {
}
}
import { Component, ElementRef, ViewChild } from '@angular/core';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
import { Router, RouterModule } from '@angular/router';
import { SharedModule } from '../../../../shared/shared.module';
import { TranslateModule, TranslateService } from '@ngx-translate/core';
import swal from 'sweetalert';
import { MatPaginator } from '@angular/material/paginator';
import { FormsModule } from '@angular/forms';
import { NgSelectModule } from '@ng-select/ng-select';
import { CommonModule } from '@angular/common';
import { FileUploadModule } from 'ng2-file-upload';
import { FileItem, FileUploader, ParsedResponseHeaders } from "ng2-file-upload";
import { environment } from '../../../../../environments/environment';
import { TokenService } from '../../../../shared/services/token.service'
import { QuillModule } from 'ngx-quill';
import { MatDialog, MatDialogModule } from '@angular/material/dialog';
import { CompanyPositionService } from '../../../services/company-position.service';
import { CompanyPositionModel } from '../../../models/company-position.model';
@Component({
selector: 'app-company-position',
standalone: true,
imports: [
CommonModule,
SharedModule,
TranslateModule,
NgSelectModule,
FormsModule,
MatPaginator,
RouterModule,
FileUploadModule,
QuillModule,
MatDialogModule
],
templateUrl: './company-position.component.html',
styleUrl: './company-position.component.css',
})
export class CompanyPositionComponent {
quillConfig = {
toolbar: [
['link'], // เพิ่มปุ่มลิงก์
['bold', 'italic', 'underline', 'strike'], // toggled buttons
['blockquote', 'code-block'],
[{ 'header': 1 }, { 'header': 2 }], // custom button values
[{ 'list': 'ordered' }, { 'list': 'bullet' }],
[{ 'script': 'sub' }, { 'script': 'super' }], // superscript/subscript
[{ 'indent': '-1' }, { 'indent': '+1' }], // outdent/indent
[{ 'direction': 'rtl' }], // text direction
[{ 'size': ['small', false, 'large', 'huge'] }], // custom dropdown
[{ 'header': [1, 2, 3, 4, 5, 6, false] }],
[{ 'color': [] }, { 'background': [] }], // dropdown with defaults from theme
[{ 'align': [] }],
['clean'], // remove formatting button
]
};
@ViewChild('closeModal') public childModal?: ElementRef;
@ViewChild('modalDetail') public modalDetail?: ElementRef;
@ViewChild("CompanyPositionModel") CompanyPositionModel: any;
@ViewChild('profileChangeInput') profileChangeInputRef!: ElementRef;
dialogRef: any
currentContentTab: number = 1;
currentExcerptTab: number = 1;
action = "new";
allSelected = false;
someSelected = false;
itemsList: CompanyPositionModel[] = [];
filterList: CompanyPositionModel[] = [];
selectModel: CompanyPositionModel = new CompanyPositionModel();
selectedItems = new Map<string, boolean>();
// empList: CompanyPositionModel[] = [];
// descName = 'engName';
pageIndex = 0;
uploaderProfile: FileUploader | undefined;
uploadErrorMsg: string = "";
modalStatus: "add" | "edit" = "add"
get searchTerm(): string {
return this._searchTerm;
}
set searchTerm(val: string) {
this.pageIndex = 0;
this.allSelected = false;
this._searchTerm = val;
if (val != '') {
this.filterList = this.filter(val);
} else {
this.updatePagedItems();
}
}
_searchTerm = "";
constructor(
private compositionservice: CompanyPositionService,
public translate: TranslateService,
private tokenService: TokenService,
private router: Router,
private dialog: MatDialog,
) {
}
getPosition() {
this.compositionservice.getList().subscribe({
next: (response: CompanyPositionModel[]) => {
this.itemsList = response.map((x: any) => new CompanyPositionModel(x, this.translate));
console.log('ข้อมูลตำแหน่ง (itemsList)', this.itemsList);
this.updatePagedItems();
},
error: (error) => {
console.error('error cant get position', error);
swal("ข้อผิดพลาด", "ไม่สามารถดึงข้อมูลตำแหน่งได้", "error");
}
});
}
ngOnInit(): void {
this.getPosition();
}
filter(v: string) {
return this.itemsList?.filter(
(x) =>
x.positionId?.toLowerCase().indexOf(v.toLowerCase()) !== -1 ||
x.thName?.toLowerCase().indexOf(v.toLowerCase()) !== -1 ||
x.engName?.toLowerCase().indexOf(v.toLowerCase()) !== -1 ||
x.remark?.toLowerCase().indexOf(v.toLowerCase()) !== -1
// x.getStatus().toLowerCase().indexOf(v.toLowerCase()) !== -1
);
}
delete(item: CompanyPositionModel) {
swal({
title: "คุณแน่ใจหรือไม่?",
text: "คุณจะไม่สามารถกู้คืนข้อมูลนี้ได้!",
icon: "warning",
dangerMode: true,
buttons: ["ยกเลิก", "ใช่, ลบเลย!"],
})
.then((willDelete: any) => {
if (willDelete) {
const newPosition = new CompanyPositionModel(item)
this.compositionservice.deletePosition(newPosition).subscribe(result => {
swal("ลบสำเร็จ!!", "ลบข้อมูลสำเร็จ", "success");
this.ngOnInit();
}, error => {
console.error("เกิดข้อผิดพลาดในการลบ:", error);
swal("ข้อผิดพลาด!!", "ไม่สามารถลบข้อมูลได้", "error");
});
}
});
}
new() {
this.action = 'add';
this.selectModel = new CompanyPositionModel();
// this.selectModel.status = 1;
this.selectModel.positionId = "";
this.selectModel.thName = "";
this.selectModel.engName = "";
this.selectModel.remark = "";
}
view(item: CompanyPositionModel) {
this.action = 'edit';
this.selectModel = new CompanyPositionModel(item);
console.log(this.selectModel);
}
save() {
console.log('Before Save, selectModel is:', this.selectModel);
swal({
title: "คุณแน่ใจหรือไม่?",
text: "คุณต้องการบันทึกหรือไม่",
icon: "warning",
dangerMode: false,
buttons: ["ยกเลิก", "ยืนยัน"],
})
.then((willSave: any) => {
if (willSave) {
this.compositionservice.postPosition(this.selectModel).subscribe(result => {
console.log(result);
swal("บันทึกสำเร็จ!!", "บันทึกข้อมูลสมาชิก", "success");
this.ngOnInit();
this.childModal?.nativeElement.click();
}, error => {
console.error("เกิดข้อผิดพลาดในการบันทึก/อัปเดต:", error);
swal("ข้อผิดพลาด!!", "ไม่สามารถบันทึก/อัปเดตข้อมูลได้", "error");
});
}
});
}
updatePagedItems() {
const startIndex = this.pageIndex * 10;
const endIndex = startIndex + 10;
this.filterList = this.itemsList.slice(startIndex, endIndex);
}
toggleAll(event: any) {
this.allSelected = event.target.checked;
this.selectedItems.clear();
this.itemsList.forEach(item => {
this.selectedItems.set(item.positionId, this.allSelected);
});
this.someSelected = this.itemsList.some(item => this.selectedItems.get(item.positionId));
}
onCheckboxChange(positionId: string) {
const isSelected = this.selectedItems.get(positionId) || false;
this.selectedItems.set(positionId, !isSelected);
this.allSelected = this.itemsList.every(item => this.selectedItems.get(item.positionId));
this.someSelected = this.itemsList.some(item => this.selectedItems.get(item.positionId));
}
deleteSelect() {
let employeeInfo = '';
this.selectedItems.forEach((isSelected, positionId) => {
if (isSelected) {
const user = this.itemsList.find(user => user.positionId === positionId);
if (user) {
employeeInfo += `${this.translate.instant('thName')}: ${user.thName}\n`;
}
}
});
swal({
title: "Are you sure?",
text: employeeInfo,
icon: "warning",
dangerMode: true,
buttons: ["Cancel", "Yes, Delete it!"],
})
.then((willDelete: any) => {
if (willDelete) {
this.selectedItems.forEach((isSelected, positionId) => {
if (isSelected) {
const user = this.itemsList.find(user => user.positionId === positionId);
if (user) {
const newPosition = new CompanyPositionModel(user)
this.compositionservice.deletePosition(newPosition).subscribe(result => {
swal("Save Success!!", "บันทึกข้อมูลสำเร็จ", "success");
this.ngOnInit();
});
}
}
});
}
});
}
// openDialog() {
// this.dialogRef = this.dialog.open(this.CompanyPositionModel, {
// width: '1100px',
// disableClose: false,
// });
// }
// closeDialog() {
// this.dialogRef.close()
// }
}
/* tslint:disable:no-unused-variable */
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';
import { CountryRegistrationComponent } from './country-registration.component';
describe('CountryRegistrationComponent', () => {
let component: CountryRegistrationComponent;
let fixture: ComponentFixture<CountryRegistrationComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ CountryRegistrationComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(CountryRegistrationComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
import { CommonModule } from "@angular/common";
import { ChangeDetectionStrategy, Component, ElementRef, TemplateRef, ViewChild } from '@angular/core';
import { NgSelectModule } from "@ng-select/ng-select";
import { TranslateModule, TranslateService } from "@ngx-translate/core";
import { FormsModule } from "@angular/forms";
import swal from 'sweetalert';
import { MatPaginator, PageEvent } from "@angular/material/paginator";
import { FileUploadModule } from 'ng2-file-upload';
import { FileItem, FileUploader, ParsedResponseHeaders } from "ng2-file-upload";
import { Router } from "@angular/router";
import { QuillModule } from "ngx-quill";
import { MatDialog } from "@angular/material/dialog";
import { SharedModule } from "../../../../shared/shared.module";
import { PdpaConfigComponent } from "../../pdpa-manage/pdpa-config/pdpa-config.component";
import { MyPdpaModel, PdpaModel } from "../../../models/pdpa.model";
import { CountryService } from "../../../services/country.service";
import { CountryModel } from "../../../models/country.model";
@Component({
selector: 'app-country-registration',
standalone: true,
imports: [
CommonModule,
SharedModule,
TranslateModule,
NgSelectModule,
FormsModule,
FileUploadModule,
QuillModule
],
templateUrl: './country-registration.component.html',
styleUrl: './country-registration.component.css'
})
export class CountryRegistrationComponent {
@ViewChild('closeModal') public childModal?: ElementRef;
@ViewChild('modalDetail') modalDetail!: TemplateRef<any>;
currentTab = 1
allSelected = false;
someSelected = false;
itemsList: CountryModel[] = []
filterList: CountryModel[] = []
country: CountryModel = new CountryModel()
selectedItems = new Map<string, boolean>();
pageIndex = 0;
modalStatus: "add" | "edit" = "add"
isSaving = false;
get searchTerm(): string {
return this._searchTerm;
}
set searchTerm(val: string) {
this.pageIndex = 0;
this.allSelected = false
this._searchTerm = val;
if (val != '') {
this.filterList = this.filter(val);
} else {
this.updatePagedItems()
}
}
_searchTerm = "";
constructor(private countryService: CountryService, public translate: TranslateService, private modal: MatDialog) {
}
ngOnInit(): void {
this.countryService.list().subscribe(res => {
this.itemsList = res.map(item => new CountryModel(item, this.translate));
this.filterList = [...this.itemsList];
});
}
filter(v: string) {
return this.itemsList?.filter(
(x) =>
x.countryId?.toLowerCase().indexOf(v.toLowerCase()) !== -1 ||
x.thName?.toLowerCase().indexOf(v.toLowerCase()) !== -1 ||
x.engName?.toLowerCase().indexOf(v.toLowerCase()) !== -1
);
}
new() {
this.modalStatus = 'add'
this.country = new CountryModel();
}
view(item: CountryModel) {
this.modalStatus = 'edit';
this.country = new CountryModel(item, this.translate);
}
save() {
swal({
title: "Are you sure?",
text: "คุณต้องการบันทึกหรือไม่",
icon: "warning",
dangerMode: false,
buttons: ["Cancel", "Confirm"],
})
.then((willDelete: any) => {
if (willDelete) {
if (this.modalStatus == 'add') {
console.log(this.country);
this.countryService.post(this.country).subscribe(result => {
swal("Save Success!!", "บันทึกประเทศสำเร็จ", "success");
this.ngOnInit()
this.childModal?.nativeElement.click()
})
} else if (this.modalStatus == 'edit') {
const respone = new CountryModel(this.country);
this.countryService.post(respone).subscribe(result => {
console.log(result)
swal("Update Success!!", "บันทึกประเทศสำเร็จ", "success");
this.ngOnInit()
this.childModal?.nativeElement.click()
})
}
}
});
}
deleteCountry(item: CountryModel) {
const versionText = `${this.translate.instant('Country')}: ${item.thName}`;
swal({
title: "Are you sure?",
text: `Confirm to delete :\n${versionText}\!`,
icon: "warning",
dangerMode: true,
buttons: ["Cancel", "Yes,Delete it!"],
}).then((willDelete: any) => {
if (willDelete) {
const res = new CountryModel(item)
console.log(res);
this.countryService.delete(res).subscribe(result => {
swal("Delete Success!!", "ลบข้อมูลสำเร็จ", "success");
this.ngOnInit();
});
}
});
}
deleteSelect() {
let countryConfig = '';
this.selectedItems.forEach((isSelected, res) => {
if (isSelected) {
const country = this.itemsList.find(country => country.countryId === res) as CountryModel;
if (country) {
countryConfig += `${this.translate.instant('Country')}: ${country.thName}\n`;
}
}
});
swal({
title: "Are you sure?",
text: countryConfig,
icon: "warning",
dangerMode: true,
buttons: ["Cancel", "Yes, Delete it!"],
})
.then((willDelete: any) => {
if (willDelete) {
this.selectedItems.forEach((isSelected, res) => {
if (isSelected) {
const country = this.itemsList.find(country => country.countryId === res);
if (country) {
const newCountry = new CountryModel(country)
console.log(newCountry);
this.countryService.delete(newCountry).subscribe(result => {
swal("Delete Success!!", "ลบข้อมูลที่เลือกสำเร็จ", "success");
this.ngOnInit();
});
}
}
});
}
});
}
updatePagedItems() {
const startIndex = this.pageIndex * 10;
const endIndex = startIndex + 10;
this.filterList = this.itemsList.slice(startIndex, endIndex);
}
toggleAll(event: any) {
this.allSelected = event.target.checked;
this.selectedItems.clear();
this.itemsList.forEach(item => {
this.selectedItems.set(item.countryId, this.allSelected);
});
this.someSelected = this.itemsList.some(item => this.selectedItems.get(item.countryId));
}
onCheckboxChange(countryId: string) {
const isSelected = this.selectedItems.get(countryId) || false;
this.selectedItems.set(countryId, !isSelected);
this.allSelected = this.itemsList.every(item => this.selectedItems.get(item.countryId));
this.someSelected = this.itemsList.some(item => this.selectedItems.get(item.countryId));
}
filterEmp(empId: string) {
this.country = this.itemsList.filter(e => e.countryId == empId)[0]
}
}
\ No newline at end of file
/* tslint:disable:no-unused-variable */
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';
import { DegreeManageComponent } from './degree-manage.component';
describe('DegreeManageComponent', () => {
let component: DegreeManageComponent;
let fixture: ComponentFixture<DegreeManageComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ DegreeManageComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(DegreeManageComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
import { CommonModule } from "@angular/common";
import { ChangeDetectionStrategy, Component, ElementRef, TemplateRef, ViewChild } from '@angular/core';
import { NgSelectModule } from "@ng-select/ng-select";
import { TranslateModule, TranslateService } from "@ngx-translate/core";
import { FormsModule } from "@angular/forms";
import swal from 'sweetalert';
import { MatPaginator, PageEvent } from "@angular/material/paginator";
import { FileUploadModule } from 'ng2-file-upload';
import { FileItem, FileUploader, ParsedResponseHeaders } from "ng2-file-upload";
import { Router } from "@angular/router";
import { QuillModule } from "ngx-quill";
import { MatDialog } from "@angular/material/dialog";
import { SharedModule } from "../../../../shared/shared.module";
import { PdpaConfigComponent } from "../../pdpa-manage/pdpa-config/pdpa-config.component";
import { MyPdpaModel, PdpaModel } from "../../../models/pdpa.model";
import { DegreeModel } from "../../../models/degree.model";
import { DegreeService } from "../../../services/degree.service";
@Component({
selector: 'app-degree-manage',
standalone: true,
imports: [
CommonModule,
SharedModule,
TranslateModule,
NgSelectModule,
FormsModule,
FileUploadModule,
QuillModule
],
templateUrl: './degree-manage.component.html',
styleUrl: './degree-manage.component.css'
})
export class DegreeManageComponent {
@ViewChild('closeModal') public childModal?: ElementRef;
@ViewChild('modalDetail') modalDetail!: TemplateRef<any>;
currentTab = 1
allSelected = false;
someSelected = false;
itemsList: DegreeModel[] = []
filterList: DegreeModel[] = []
degree: DegreeModel = new DegreeModel()
selectedItems = new Map<string, boolean>();
pageIndex = 0;
modalStatus: "add" | "edit" = "add"
isSaving = false;
get searchTerm(): string {
return this._searchTerm;
}
set searchTerm(val: string) {
this.pageIndex = 0;
this.allSelected = false
this._searchTerm = val;
if (val != '') {
this.filterList = this.filter(val);
} else {
this.updatePagedItems()
}
}
_searchTerm = "";
constructor(private degreeService: DegreeService, public translate: TranslateService, private modal: MatDialog) {
}
ngOnInit(): void {
this.degreeService.list().subscribe(res => {
this.itemsList = res.map(item => new DegreeModel(item, this.translate));
this.filterList = [...this.itemsList];
});
}
filter(v: string) {
return this.itemsList?.filter(
(x) =>
x.degreeId?.toLowerCase().indexOf(v.toLowerCase()) !== -1 ||
x.thName?.toLowerCase().indexOf(v.toLowerCase()) !== -1 ||
x.engName?.toLowerCase().indexOf(v.toLowerCase()) !== -1 ||
x.higher?.toLowerCase().indexOf(v.toLowerCase()) !== -1
);
}
new() {
this.modalStatus = 'add'
this.degree = new DegreeModel();
}
view(item: DegreeModel) {
this.modalStatus = 'edit';
this.degree = new DegreeModel(item, this.translate);
}
save() {
swal({
title: "Are you sure?",
text: "คุณต้องการบันทึกหรือไม่",
icon: "warning",
dangerMode: false,
buttons: ["Cancel", "Confirm"],
})
.then((willDelete: any) => {
if (willDelete) {
if (this.modalStatus == 'add') {
console.log(this.degree);
this.degreeService.post(this.degree).subscribe(result => {
swal("Save Success!!", "บันทึกระดับการศึกษาสำเร็จ", "success");
this.ngOnInit()
this.childModal?.nativeElement.click()
})
} else if (this.modalStatus == 'edit') {
const respone = new DegreeModel(this.degree);
this.degreeService.post(respone).subscribe(result => {
console.log(result)
swal("Update Success!!", "บันทึกระดับการศึกษาสำเร็จ", "success");
this.ngOnInit()
this.childModal?.nativeElement.click()
})
}
}
});
}
deletedegree(item: DegreeModel) {
const versionText = `${this.translate.instant('degree')}: ${item.thName}`;
swal({
title: "Are you sure?",
text: `Confirm to delete :\n${versionText}\!`,
icon: "warning",
dangerMode: true,
buttons: ["Cancel", "Yes,Delete it!"],
}).then((willDelete: any) => {
if (willDelete) {
const res = new DegreeModel(item)
console.log(res);
this.degreeService.delete(res).subscribe(result => {
swal("Delete Success!!", "ลบข้อมูลสำเร็จ", "success");
this.ngOnInit();
});
}
});
}
deleteSelect() {
let degreeConfig = '';
this.selectedItems.forEach((isSelected, res) => {
if (isSelected) {
const degree = this.itemsList.find(degree => degree.degreeId === res) as DegreeModel;
if (degree) {
degreeConfig += `${this.translate.instant('degree')}: ${degree.thName}\n`;
}
}
});
swal({
title: "Are you sure?",
text: degreeConfig,
icon: "warning",
dangerMode: true,
buttons: ["Cancel", "Yes, Delete it!"],
})
.then((willDelete: any) => {
if (willDelete) {
this.selectedItems.forEach((isSelected, res) => {
if (isSelected) {
const degree = this.itemsList.find(degree => degree.degreeId === res);
if (degree) {
const newdegree = new DegreeModel(degree)
console.log(newdegree);
this.degreeService.delete(newdegree).subscribe(result => {
swal("Delete Success!!", "ลบข้อมูลที่เลือกสำเร็จ", "success");
this.ngOnInit();
});
}
}
});
}
});
}
updatePagedItems() {
const startIndex = this.pageIndex * 10;
const endIndex = startIndex + 10;
this.filterList = this.itemsList.slice(startIndex, endIndex);
}
toggleAll(event: any) {
this.allSelected = event.target.checked;
this.selectedItems.clear();
this.itemsList.forEach(item => {
this.selectedItems.set(item.degreeId, this.allSelected);
});
this.someSelected = this.itemsList.some(item => this.selectedItems.get(item.degreeId));
}
onCheckboxChange(degreeId: string) {
const isSelected = this.selectedItems.get(degreeId) || false;
this.selectedItems.set(degreeId, !isSelected);
this.allSelected = this.itemsList.every(item => this.selectedItems.get(item.degreeId));
this.someSelected = this.itemsList.some(item => this.selectedItems.get(item.degreeId));
}
filterEmp(empId: string) {
this.degree = this.itemsList.filter(e => e.degreeId == empId)[0]
}
}
\ No newline at end of file
/* tslint:disable:no-unused-variable */
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';
import { JobTypeComponent } from './job-type.component';
describe('JobTypeComponent', () => {
let component: JobTypeComponent;
let fixture: ComponentFixture<JobTypeComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ JobTypeComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(JobTypeComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
import { Component, ElementRef, ViewChild } from '@angular/core';
import { Router, RouterModule } from '@angular/router';
import { TranslateModule, TranslateService } from '@ngx-translate/core';
import swal from 'sweetalert';
import { MatPaginator } from '@angular/material/paginator';
import { FormsModule } from '@angular/forms';
import { NgSelectModule } from '@ng-select/ng-select';
import { CommonModule } from '@angular/common';
import { SharedModule } from '../../../../shared/shared.module';
import { TokenService } from '../../../../shared/services/token.service';
import { JobTypeModel } from '../../../models/job-type.model';
import { JobTypeService } from '../../../services/job-type.service';
@Component({
selector: 'app-job-type',
standalone: true,
imports: [
CommonModule,
SharedModule,
TranslateModule,
NgSelectModule,
FormsModule,
MatPaginator,
RouterModule,
],
templateUrl: './job-type.component.html',
styleUrl: './job-type.component.css',
})
export class JobTypeComponent {
@ViewChild("JobTypeModel") JobTypeModel: any;
dialogRef: any
currentengNameTab: number = 1;
currentExcerptTab: number = 1;
action = "new";
allSelected = false;
someSelected = false;
itemsList: JobTypeModel[] = [];
filterList: JobTypeModel[] = [];
selectModel: JobTypeModel = new JobTypeModel();
selectedItems = new Map<string, boolean>();
pageIndex = 0;
get searchTerm(): string {
return this._searchTerm;
}
set searchTerm(val: string) {
this.pageIndex = 0;
this.allSelected = false;
this._searchTerm = val;
if (val != '') {
this.filterList = this.filter(val);
} else {
this.updatePagedItems();
}
}
_searchTerm = "";
constructor(private jobtypeservice: JobTypeService, public translate: TranslateService, private tokenService: TokenService, private router: Router,) {
}
getJobtype() {
this.jobtypeservice.getList().subscribe({
next: (response: JobTypeModel[]) => {
this.itemsList = response.map((x: any) => new JobTypeModel(x, this.translate));
console.log('ข้อมูลบริษัท (itemsList)', this.itemsList);
this.updatePagedItems();
},
error: (error) => {
console.error('error cant get company', error);
swal("ข้อผิดพลาด", "ไม่สามารถดึงข้อมูลบริษัทได้", "error");
}
});
}
ngOnInit(): void {
this.getJobtype();
}
filter(v: string) {
return this.itemsList?.filter(
(x) =>
x.jobTypeId?.toLowerCase().indexOf(v.toLowerCase()) !== -1 ||
x.thName?.toLowerCase().indexOf(v.toLowerCase()) !== -1 ||
x.engName?.toLowerCase().indexOf(v.toLowerCase()) !== -1
// x.getStatus().toLowerCase().indexOf(v.toLowerCase()) !== -1
);
}
delete(item: JobTypeModel) {
swal({
title: "คุณแน่ใจหรือไม่?",
text: "คุณจะไม่สามารถกู้คืนข้อมูลนี้ได้!",
icon: "warning",
dangerMode: true,
buttons: ["ยกเลิก", "ใช่, ลบเลย!"],
})
.then((willDelete: any) => {
if (willDelete) {
this.jobtypeservice.deleteById(item.jobTypeId).subscribe(result => {
swal("ลบสำเร็จ!!", "ลบข้อมูลสำเร็จ", "success");
this.ngOnInit();
}, error => {
console.error("เกิดข้อผิดพลาดในการลบ:", error);
swal("ข้อผิดพลาด!!", "ไม่สามารถลบข้อมูลได้", "error");
});
}
});
}
new() {
this.action = 'add';
this.selectModel = new JobTypeModel();
this.selectModel.jobTypeId = "";
this.selectModel.thName = "";
this.selectModel.engName = "";
}
view(item: JobTypeModel) {
this.action = 'edit';
this.selectModel = new JobTypeModel(item);
}
save() {
console.log('Before Save, selectModel is:', this.selectModel);
swal({
title: "คุณแน่ใจหรือไม่?",
text: "คุณต้องการบันทึกหรือไม่",
icon: "warning",
dangerMode: false,
buttons: ["ยกเลิก", "ยืนยัน"],
})
.then((willSave: any) => {
if (willSave) {
this.jobtypeservice.post(this.selectModel).subscribe(result => {
console.log(result);
swal("บันทึกสำเร็จ!!", "บันทึกข้อมูลสมาชิก", "success");
this.ngOnInit();
}, error => {
console.error("เกิดข้อผิดพลาดในการบันทึก/อัปเดต:", error);
swal("ข้อผิดพลาด!!", "ไม่สามารถบันทึก/อัปเดตข้อมูลได้", "error");
});
}
});
}
updatePagedItems() {
const startIndex = this.pageIndex * 10;
const endIndex = startIndex + 10;
this.filterList = this.itemsList.slice(startIndex, endIndex);
}
toggleAll(event: any) {
this.allSelected = event.target.checked;
this.selectedItems.clear();
this.itemsList.forEach(item => {
this.selectedItems.set(item.jobTypeId, this.allSelected);
});
this.someSelected = this.itemsList.some(item => this.selectedItems.get(item.jobTypeId));
}
onCheckboxChange(jobTypeId: string) {
const isSelected = this.selectedItems.get(jobTypeId) || false;
this.selectedItems.set(jobTypeId, !isSelected);
this.allSelected = this.itemsList.every(item => this.selectedItems.get(item.jobTypeId));
this.someSelected = this.itemsList.some(item => this.selectedItems.get(item.jobTypeId));
}
deleteSelect() {
let companyInfo = '';
const selectedjobTypeIdsToDelete: string[] = [];
this.selectedItems.forEach((isSelected, jobTypeId) => {
if (isSelected) {
const item = this.itemsList.find(c => c.jobTypeId === jobTypeId);
if (item) {
companyInfo += `${this.translate.instant('บริษัท')}: ${item.thName}\n`;
selectedjobTypeIdsToDelete.push(item.jobTypeId);
}
}
});
if (selectedjobTypeIdsToDelete.length === 0) {
swal("ข้อผิดพลาด", "กรุณาเลือกบริษัทที่ต้องการลบ", "warning");
return;
}
swal({
title: "คุณแน่ใจหรือไม่?",
text: companyInfo,
icon: "warning",
dangerMode: true,
buttons: ["ยกเลิก", "ใช่, ลบเลย!"],
})
.then((willDelete: any) => {
if (willDelete) {
const deletePromises = selectedjobTypeIdsToDelete.map(jobTypeId =>
this.jobtypeservice.deleteById(jobTypeId).toPromise()
.then(() => true)
.catch(error => {
console.error(`Error deleting company ${jobTypeId}:`, error);
return false;
})
);
Promise.all(deletePromises)
.then(results => {
const allSuccessful = results.every(success => success);
if (allSuccessful) {
swal("ลบสำเร็จ!!", "บันทึกข้อมูลสำเร็จ", "success");
} else {
swal("สำเร็จบางส่วน/ข้อผิดพลาด!!", "มีการลบข้อมูลบางส่วนไม่สำเร็จ หรือมีข้อผิดพลาด", "warning");
}
this.ngOnInit();
this.selectedItems.clear();
this.allSelected = false;
this.someSelected = false;
});
}
});
}
}
/* tslint:disable:no-unused-variable */
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';
import { ProvinceComponent } from './province.component';
describe('ProvinceComponent', () => {
let component: ProvinceComponent;
let fixture: ComponentFixture<ProvinceComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ ProvinceComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(ProvinceComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
:host {
display: block;
}
.small-html {
font-size: 0.85rem; /* ลดขนาดฟอนต์ */
line-height: 1.2; /* ลดระยะบรรทัด */
max-height: 150px; /* จำกัดความสูง */
overflow-y: auto; /* ถ้าเนื้อหายาวเกิน ให้เลื่อนดูได้ */
display: block;
}
<app-page-header [title]="'Department'" [activeTitle]="'จัดการบริษัท'" [title1]="'Department'"></app-page-header>
<div class="grid grid-cols-12 gap-6">
<div class="xl:col-span-12 col-span-12">
<div class="box">
<div class="box-header justify-between">
<div class="box-title">
{{ 'All List' | translate}} <span
class="badge bg-light text-default rounded-full ms-1 text-[0.75rem] align-middle">{{itemsList.length}}</span>
</div>
<div class="flex flex-wrap gap-2">
<a href="javascript:void(0);" class="hs-dropdown-toggle ti-btn ti-btn-primary-full me-2" (click)="new()"
data-hs-overlay="#modal-detail"><i class="ri-add-line font-semibold align-middle"></i>{{ 'Create' |
translate}}
</a>
<a href="javascript:void(0);" class="hs-dropdown-toggle ti-btn ti-btn-danger-full me-2" *ngIf="someSelected"
(click)="deleteSelect()"><i class="ri-delete-bin-line font-semibold align-middle"></i>{{ 'Delete' |
translate}}
</a>
<div>
<input class="form-control form-control" type="text" placeholder="{{ 'Search' | translate}}"
aria-label=".form-control-sm example" [(ngModel)]='searchTerm'>
</div>
</div>
</div>
<div class="box-body">
<div class="table-responsive">
<table class="table whitespace-nowrap min-w-full ti-custom-table-hover">
<thead>
<tr class="border-b border-defaultborder">
<th scope="col" class="!text-start">
<input class="form-check-input check-all" type="checkbox" id="all-products"
(change)="toggleAll($event)" [checked]="allSelected" aria-label="...">
</th>
<th scope="col" class="text-start">{{ 'ID' | translate}}</th>
<th scope="col" class="text-start">{{ 'ชื่อแผนก' | translate}}</th>
<th scope="col" class="text-start"></th>
</tr>
</thead>
<tbody>
@for(item of filterList;track filterList){
<tr class="border border-defaultborder dark:border-defaultborder/10">
<td class="product-checkbox"><input class="form-check-input" type="checkbox"
[checked]="selectedItems.get(item.departmentId)" (change)="onCheckboxChange(item.departmentId)"
aria-label="..." value="">
</td>
<td><span class="font-semibold text-primary">{{item.departmentId}}</span></td>
<td> {{item.thName}}</td>
<td>
<div class="flex flex-row items-center !gap-2 ">
<a aria-label="anchor" (click)="view(item)" data-hs-overlay="#modal-detail"
class="ti-btn ti-btn-wave !gap-0 !m-0 bg-info/10 text-info hover:bg-info hover:text-white hover:border-info"><i
class="ri-pencil-line"></i></a>
<a aria-label="anchor" href="javascript:void(0);" (click)="delete(item)"
class="ti-btn ti-btn-wave product-btn !gap-0 !m-0 bg-danger/10 text-danger hover:bg-danger hover:text-white hover:border-danger"><i
class="ri-delete-bin-line"></i></a>
</div>
</td>
</tr>
}
</tbody>
</table>
</div>
</div>
<div class="box-footer">
<div class="flex items-center flex-wrap overflow-auto" *ngIf="filterList.length > 0">
<div class="mb-2 sm:mb-0">
<div>
{{'Showing' | translate}} {{filterList.length}} {{'entries'
| translate}} <i class="bi bi-arrow-right ms-2 font-semibold"></i>
</div>
</div>
<div class="ms-auto">
<nav aria-label="Page navigation">
<ul class="ti-pagination mb-0">
<li *ngIf="pageIndex>0" class="page-item {{pageIndex==0 ? 'disabled' : ''}}"><a
class="page-link px-3 py-[0.375rem]"
(click)="pageIndex = pageIndex-1;updatePagedItems()">{{'Previous' | translate}}</a></li>
<li class="page-item"><a class="page-link px-3 py-[0.375rem]" href="javascript:void(0);"
*ngIf="pageIndex-1>0" (click)="pageIndex = pageIndex-2;updatePagedItems()">{{pageIndex-1}}</a></li>
<li class="page-item"><a class="page-link px-3 py-[0.375rem]" href="javascript:void(0);"
*ngIf="pageIndex>0 && ((pageIndex-1)*10 < (searchTerm == '' ? itemsList.length : filterList.length))"
(click)="pageIndex = pageIndex-1;updatePagedItems()">{{pageIndex}}</a></li>
<li class="page-item"><a class="page-link active px-3 py-[0.375rem]"
href="javascript:void(0);">{{pageIndex +1}}</a>
</li>
<li class="page-item"><a class="page-link px-3 py-[0.375rem]" href="javascript:void(0);"
*ngIf="(pageIndex+1)*10 < (searchTerm == '' ? itemsList.length : filterList.length)"
(click)="pageIndex = pageIndex+1;updatePagedItems()">{{pageIndex +2}}</a></li>
<li class="page-item"><a class="page-link px-3 py-[0.375rem]" href="javascript:void(0);"
*ngIf="(pageIndex+2)*10 < (searchTerm == '' ? itemsList.length : filterList.length)"
(click)="pageIndex = pageIndex+2;updatePagedItems()">{{pageIndex +3}}</a></li>
<li *ngIf="(pageIndex+1)*10 < (searchTerm == '' ? itemsList.length : filterList.length)"
class="page-item"><a class="page-link px-3 py-[0.375rem]"
(click)="pageIndex = pageIndex+1;updatePagedItems()">{{'Next' |
translate}}</a>
</li>
</ul>
</nav>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Start:: Create Contact -->
<div id="modal-detail" class="hs-overlay hidden ti-modal [--overlay-backdrop:static]">
<div class="hs-overlay-open:mt-7 ti-modal-box mt-0 ease-out">
<div class="ti-modal-content">
<div class="ti-modal-header">
<h6 class="modal-title text-[1rem] font-semibold text-defaulttextcolor" id="mail-ComposeLabel">{{ 'Create' |
translate }} {{ 'Department' | translate }}
</h6>
<button type="button" class="hs-dropdown-toggle !text-[1rem] !font-semibold !text-defaulttextcolor"
data-hs-overlay="#modal-detail" #closeModal>
<span class="sr-only">{{'Close' | translate}}</span>
<i class="ri-close-line"></i>
</button>
</div>
<div class="ti-modal-body px-4">
<div class="grid grid-cols-12 gap-4">
<div class="xl:col-span-6 col-span-12">
<label for="contact-lead-score" class="form-label">{{'Name (TH)' | translate}}</label>
<input type="text" class="form-control" id="contact-lead-score" placeholder=""
[(ngModel)]="selectModel.thName">
<div class="text-danger" *ngIf="!selectModel.thName">
{{'Please fill in information' | translate}}
</div>
</div>
<div class="xl:col-span-6 col-span-12">
<label for="contact-mail" class="form-label">{{'Name (EN)' | translate}}</label>
<input type="text" class="form-control" id="contact-mail" placeholder="" [(ngModel)]="selectModel.engName">
<div class="text-danger" *ngIf="!selectModel.engName">
{{'Please fill in information' | translate}}
</div>
</div>
</div>
</div>
<div class="ti-modal-footer">
<button type="button" class="hs-dropdown-toggle ti-btn ti-btn-light align-middle"
data-hs-overlay="#modal-detail">
{{'Cancel' | translate}}
</button>
<button type="button" [disabled]="!selectModel.thName || !selectModel.engName"
class="ti-btn bg-primary text-white !font-medium {{!selectModel.thName || !selectModel.engName ? 'ti-btn-disabled' : ''}}"
(click)="save()">{{'Save' |
translate}}</button>
</div>
</div>
</div>
</div>
<!-- End:: Create Contact -->
import { CommonModule } from "@angular/common";
import { ChangeDetectionStrategy, Component, ElementRef, ViewChild } from '@angular/core';
import { NgSelectModule } from "@ng-select/ng-select";
import { TranslateModule, TranslateService } from "@ngx-translate/core";
import { SharedModule } from "../../../../shared/shared.module";
import { DepartmentService } from "../../../services/department.service";
import { DepartmentModel } from "../../../models/department.model";
import { FormsModule } from "@angular/forms";
import swal from 'sweetalert';
import { MatPaginator, PageEvent } from "@angular/material/paginator";
import { ActivatedRoute } from "@angular/router";
import { TokenService } from "../../../../shared/services/token.service";
@Component({
selector: 'app-department',
standalone: true,
imports: [
CommonModule,
SharedModule,
TranslateModule,
NgSelectModule,
FormsModule,
MatPaginator
],
templateUrl: './department.component.html',
styleUrl: './department.component.css'
})
export class DepartmentComponent {
@ViewChild('closeModal') public childModal?: ElementRef;
@ViewChild('modalDetail') public modalDetail?: ElementRef;
allSelected = false;
someSelected = false;
companyId = ""
itemsList: DepartmentModel[] = []
filterList: DepartmentModel[] = [];
selectModel: DepartmentModel = new DepartmentModel()
selectedItems = new Map<string, boolean>();
pageIndex = 0;
isEdit = false;
get searchTerm(): string {
return this._searchTerm;
}
set searchTerm(val: string) {
this.pageIndex = 0;
this.allSelected = false
this._searchTerm = val;
if (val != '') {
this.filterList = this.filter(val);
} else {
this.updatePagedItems()
}
}
_searchTerm = "";
constructor(private departmentService: DepartmentService, private tokenService: TokenService, public translate: TranslateService) {
this.companyId = this.tokenService.getSelectCompany().companyId;;
this.getDepartment()
}
getDepartment() {
this.departmentService.getLists(this.companyId).subscribe(result => {
this.itemsList = result
this.updatePagedItems()
})
}
filter(v: string) {
this.pageIndex = 0;
return this.itemsList?.filter(
(x) =>
x.departmentId?.toLowerCase().indexOf(v.toLowerCase()) !== -1 ||
x.thName?.toLowerCase().indexOf(v.toLowerCase()) !== -1 ||
x.engName?.toLowerCase().indexOf(v.toLowerCase()) !== -1
);
}
delete(item: DepartmentModel) {
swal({
title: "Are you sure?",
text: "You won't be able to revert this!",
icon: "warning",
timer: 1000,
dangerMode: true,
buttons: ["Cancel", "Yes,Delete it!"],
})
.then((willDelete: any) => {
if (willDelete) {
this.departmentService.delete(item).subscribe(result => {
swal("Save Success!!", "บันทึกข้อมูลสำเร็จ", "success");
this.getDepartment()
})
}
});
}
new() {
this.isEdit = false
this.selectModel = new DepartmentModel()
}
view(item: DepartmentModel) {
this.isEdit = true;
this.selectModel = new DepartmentModel(item)
}
save() {
swal({
title: "Are you sure?",
text: "คุณต้องการบันทึกหรือไม่",
icon: "warning",
dangerMode: false,
buttons: ["Cancel", "Confirm"],
})
.then((willDelete: any) => {
if (willDelete) {
this.selectModel.companyId = this.companyId
if (!this.isEdit) {
this.departmentService.save(this.selectModel).subscribe(result => {
swal("Save Success!!", "บันทึกข้อมูลสำเร็จ", "success");
this.getDepartment()
this.childModal?.nativeElement.click()
})
} else {
this.departmentService.update(this.selectModel).subscribe(result => {
swal("Save Success!!", "บันทึกข้อมูลสำเร็จ", "success");
this.getDepartment()
this.childModal?.nativeElement.click()
})
}
}
});
}
updatePagedItems() {
const startIndex = this.pageIndex * 10;
const endIndex = startIndex + 10;
this.filterList = this.itemsList.slice(startIndex, endIndex);
}
toggleAll(event: any) {
this.allSelected = event.target.checked;
this.selectedItems.clear();
this.itemsList.forEach(item => {
this.selectedItems.set(item.departmentId, this.allSelected);
});
this.someSelected = this.itemsList.some(item => this.selectedItems.get(item.departmentId));
}
onCheckboxChange(departmentId: string) {
const isSelected = this.selectedItems.get(departmentId) || false;
this.selectedItems.set(departmentId, !isSelected);
this.allSelected = this.itemsList.every(item => this.selectedItems.get(item.departmentId));
this.someSelected = this.itemsList.some(item => this.selectedItems.get(item.departmentId));
}
deleteSelect() {
let employeeInfo = '';
this.selectedItems.forEach((isSelected, departmentId) => {
if (isSelected) {
const item = this.itemsList.find(item => item.departmentId === departmentId);
if (item) {
employeeInfo += `${this.translate.instant('ชื่อตำแหน่ง')}: ${item.getName()}\n`;
}
}
});
swal({
title: "Are you sure?",
text: employeeInfo,
icon: "warning",
dangerMode: true,
buttons: ["Cancel", "Yes, Delete it!"],
})
.then((willDelete: any) => {
if (willDelete) {
this.selectedItems.forEach((isSelected, departmentId) => {
if (isSelected) {
const item = this.itemsList.find(item => item.departmentId === departmentId);
if (item) {
this.departmentService.delete(item).subscribe(result => {
swal("Save Success!!", "บันทึกข้อมูลสำเร็จ", "success");
this.getDepartment();
});
}
}
});
}
});
}
}
<app-page-header [title]="'Position'" [activeTitle]="'จัดการบริษัท'" [title1]="'Position'"></app-page-header>
<div class="grid grid-cols-12 gap-6">
<div class="xl:col-span-12 col-span-12">
<div class="box">
<div class="box-header justify-between">
<div class="box-title">
{{ 'All List' | translate}} <span
class="badge bg-light text-default rounded-full ms-1 text-[0.75rem] align-middle">{{itemsList.length}}</span>
</div>
<div class="flex flex-wrap gap-2">
<a href="javascript:void(0);" class="hs-dropdown-toggle ti-btn ti-btn-primary-full me-2" (click)="new()"
data-hs-overlay="#modal-detail"><i class="ri-add-line font-semibold align-middle"></i>{{ 'Create' |
translate}}
</a>
<a href="javascript:void(0);" class="hs-dropdown-toggle ti-btn ti-btn-danger-full me-2" *ngIf="someSelected"
(click)="deleteSelect()"><i class="ri-delete-bin-line font-semibold align-middle"></i>{{ 'Delete' |
translate}}
</a>
<div>
<input class="form-control form-control" type="text" placeholder="{{ 'Search' | translate}}"
aria-label=".form-control-sm example" [(ngModel)]='searchTerm'>
</div>
</div>
</div>
<div class="box-body">
<div class="table-responsive">
<table class="table whitespace-nowrap min-w-full ti-custom-table-hover">
<thead>
<tr class="border-b border-defaultborder">
<th scope="col" class="!text-start">
<input class="form-check-input check-all" type="checkbox" id="all-products"
(change)="toggleAll($event)" [checked]="allSelected" aria-label="...">
</th>
<th scope="col" class="text-start">{{ 'ID' | translate}}</th>
<th scope="col" class="text-start">{{ 'ชื่อตำแหน่ง' | translate}}</th>
<!-- <th scope="col" class="text-start">{{ 'Name (EN)' | translate}}</th> -->
<th scope="col" class="text-start"></th>
</tr>
</thead>
<tbody>
@for(item of filterList;track filterList){
<tr class="border border-defaultborder dark:border-defaultborder/10">
<td class="product-checkbox"><input class="form-check-input" type="checkbox"
[checked]="selectedItems.get(item.positionId)" (change)="onCheckboxChange(item.positionId)"
aria-label="..." value="">
</td>
<td><span class="font-semibold text-primary">{{item.positionId}}</span></td>
<td> {{item.thName}}</td>
<td>
<div class="flex flex-row items-center !gap-2 ">
<a aria-label="anchor" (click)="view(item)" data-hs-overlay="#modal-detail"
class="ti-btn ti-btn-wave !gap-0 !m-0 bg-info/10 text-info hover:bg-info hover:text-white hover:border-info"><i
class="ri-pencil-line"></i></a>
<a aria-label="anchor" href="javascript:void(0);" (click)="delete(item)"
class="ti-btn ti-btn-wave product-btn !gap-0 !m-0 bg-danger/10 text-danger hover:bg-danger hover:text-white hover:border-danger"><i
class="ri-delete-bin-line"></i></a>
</div>
</td>
</tr>
}
</tbody>
</table>
</div>
</div>
<div class="box-footer">
<div class="flex items-center flex-wrap overflow-auto" *ngIf="filterList.length > 0">
<div class="mb-2 sm:mb-0">
<div>
{{'Showing' | translate}} {{filterList.length}} {{'entries'
| translate}} <i class="bi bi-arrow-right ms-2 font-semibold"></i>
</div>
</div>
<div class="ms-auto">
<nav aria-label="Page navigation">
<ul class="ti-pagination mb-0">
<li *ngIf="pageIndex>0" class="page-item {{pageIndex==0 ? 'disabled' : ''}}"><a
class="page-link px-3 py-[0.375rem]"
(click)="pageIndex = pageIndex-1;updatePagedItems()">{{'Previous' | translate}}</a></li>
<li class="page-item"><a class="page-link px-3 py-[0.375rem]" href="javascript:void(0);"
*ngIf="pageIndex-1>0" (click)="pageIndex = pageIndex-2;updatePagedItems()">{{pageIndex-1}}</a></li>
<li class="page-item"><a class="page-link px-3 py-[0.375rem]" href="javascript:void(0);"
*ngIf="pageIndex>0 && ((pageIndex-1)*10 < (searchTerm == '' ? itemsList.length : filterList.length))"
(click)="pageIndex = pageIndex-1;updatePagedItems()">{{pageIndex}}</a></li>
<li class="page-item"><a class="page-link active px-3 py-[0.375rem]"
href="javascript:void(0);">{{pageIndex +1}}</a>
</li>
<li class="page-item"><a class="page-link px-3 py-[0.375rem]" href="javascript:void(0);"
*ngIf="(pageIndex+1)*10 < (searchTerm == '' ? itemsList.length : filterList.length)"
(click)="pageIndex = pageIndex+1;updatePagedItems()">{{pageIndex +2}}</a></li>
<li class="page-item"><a class="page-link px-3 py-[0.375rem]" href="javascript:void(0);"
*ngIf="(pageIndex+2)*10 < (searchTerm == '' ? itemsList.length : filterList.length)"
(click)="pageIndex = pageIndex+2;updatePagedItems()">{{pageIndex +3}}</a></li>
<li *ngIf="(pageIndex+1)*10 < (searchTerm == '' ? itemsList.length : filterList.length)"
class="page-item"><a class="page-link px-3 py-[0.375rem]"
(click)="pageIndex = pageIndex+1;updatePagedItems()">{{'Next' |
translate}}</a>
</li>
</ul>
</nav>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Start:: Create Contact -->
<div id="modal-detail" class="hs-overlay hidden ti-modal [--overlay-backdrop:static]">
<div class="hs-overlay-open:mt-7 ti-modal-box mt-0 ease-out">
<div class="ti-modal-content">
<div class="ti-modal-header">
<h6 class="modal-title text-[1rem] font-semibold text-defaulttextcolor" id="mail-ComposeLabel">{{ 'Create' |
translate }} {{ 'Position' | translate }}
</h6>
<button type="button" class="hs-dropdown-toggle !text-[1rem] !font-semibold !text-defaulttextcolor"
data-hs-overlay="#modal-detail" #closeModal>
<span class="sr-only">{{'Close' | translate}}</span>
<i class="ri-close-line"></i>
</button>
</div>
<div class="ti-modal-body px-4">
<div class="grid grid-cols-12 gap-4">
<!-- <div class="xl:col-span-12 col-span-12">
<label for="deal-title" class="form-label">{{'ID' | translate}}</label>
<input type="text" class="form-control" id="deal-title" placeholder="" [(ngModel)]="selectModel.positionId">
<div class="text-danger" *ngIf="!selectModel.positionId">
{{'Please fill in information' | translate}}
</div>
</div> -->
<div class="xl:col-span-6 col-span-12">
<label for="contact-lead-score" class="form-label">{{'Name (TH)' | translate}}</label>
<input type="text" class="form-control" id="contact-lead-score" placeholder=""
[(ngModel)]="selectModel.thName">
<div class="text-danger" *ngIf="!selectModel.thName">
{{'Please fill in information' | translate}}
</div>
</div>
<div class="xl:col-span-6 col-span-12">
<label for="contact-mail" class="form-label">{{'Name (EN)' | translate}}</label>
<input type="text" class="form-control" id="contact-mail" placeholder="" [(ngModel)]="selectModel.engName">
<div class="text-danger" *ngIf="!selectModel.engName">
{{'Please fill in information' | translate}}
</div>
</div>
</div>
</div>
<div class="ti-modal-footer">
<button type="button" class="hs-dropdown-toggle ti-btn ti-btn-light align-middle"
data-hs-overlay="#modal-detail">
{{'Cancel' | translate}}
</button>
<button type="button" [disabled]="!selectModel.thName || !selectModel.engName"
class="ti-btn bg-primary text-white !font-medium {{!selectModel.thName || !selectModel.engName ? 'ti-btn-disabled' : ''}}"
(click)="save()">{{'Save' |
translate}}</button>
</div>
</div>
</div>
</div>
<!-- End:: Create Contact -->
import { CommonModule } from "@angular/common";
import { ChangeDetectionStrategy, Component, ElementRef, ViewChild } from '@angular/core';
import { NgSelectModule } from "@ng-select/ng-select";
import { TranslateModule, TranslateService } from "@ngx-translate/core";
import { SharedModule } from "../../../../shared/shared.module";
import { PositionService } from "../../../services/position.service";
import { PositionModel } from "../../../models/position.model";
import { FormsModule } from "@angular/forms";
import swal from 'sweetalert';
import { MatPaginator, PageEvent } from "@angular/material/paginator";
import { ActivatedRoute } from "@angular/router";
import { TokenService } from "../../../../shared/services/token.service";
@Component({
selector: 'app-position',
standalone: true,
imports: [
CommonModule,
SharedModule,
TranslateModule,
NgSelectModule,
FormsModule,
MatPaginator
],
templateUrl: './position.component.html',
styleUrl: './position.component.css'
})
export class PositionComponent {
@ViewChild('closeModal') public childModal?: ElementRef;
@ViewChild('modalDetail') public modalDetail?: ElementRef;
allSelected = false;
someSelected = false;
companyId = ""
itemsList: PositionModel[] = []
filterList: PositionModel[] = [];
selectModel: PositionModel = new PositionModel()
selectedItems = new Map<string, boolean>();
pageIndex = 0;
isEdit = false;
get searchTerm(): string {
return this._searchTerm;
}
set searchTerm(val: string) {
this.pageIndex = 0;
this.allSelected = false
this._searchTerm = val;
if (val != '') {
this.filterList = this.filter(val);
} else {
this.updatePagedItems()
}
}
_searchTerm = "";
constructor(private positionService: PositionService, private tokenService: TokenService, public translate: TranslateService) {
this.companyId = this.tokenService.getSelectCompany().companyId;;
this.getPosition()
}
ngOnInit(): void {
}
getPosition() {
this.positionService.getLists(this.companyId).subscribe(result => {
this.itemsList = result
this.updatePagedItems()
})
}
filter(v: string) {
this.pageIndex = 0;
return this.itemsList?.filter(
(x) =>
x.positionId?.toLowerCase().indexOf(v.toLowerCase()) !== -1 ||
x.thName?.toLowerCase().indexOf(v.toLowerCase()) !== -1 ||
x.engName?.toLowerCase().indexOf(v.toLowerCase()) !== -1
);
}
delete(item: PositionModel) {
swal({
title: "Are you sure?",
text: "You won't be able to revert this!",
icon: "warning",
timer: 1000,
dangerMode: true,
buttons: ["Cancel", "Yes,Delete it!"],
})
.then((willDelete: any) => {
if (willDelete) {
this.positionService.delete(item).subscribe(result => {
swal("Save Success!!", "บันทึกข้อมูลสำเร็จ", "success");
this.getPosition()
})
}
});
}
new() {
this.isEdit = false
this.selectModel = new PositionModel()
}
view(item: PositionModel) {
this.isEdit = true;
this.selectModel = new PositionModel(item)
}
save() {
swal({
title: "Are you sure?",
text: "คุณต้องการบันทึกหรือไม่",
icon: "warning",
dangerMode: false,
buttons: ["Cancel", "Confirm"],
})
.then((willDelete: any) => {
if (willDelete) {
this.selectModel.companyId = this.companyId
if (!this.isEdit) {
this.positionService.save(this.selectModel).subscribe(result => {
swal("Save Success!!", "บันทึกข้อมูลสำเร็จ", "success");
this.getPosition()
this.getPosition()
this.childModal?.nativeElement.click()
})
} else {
this.positionService.update(this.selectModel).subscribe(result => {
swal("Save Success!!", "บันทึกข้อมูลสำเร็จ", "success");
this.getPosition()
this.getPosition()
this.childModal?.nativeElement.click()
})
}
}
});
}
updatePagedItems() {
const startIndex = this.pageIndex * 10;
const endIndex = startIndex + 10;
this.filterList = this.itemsList.slice(startIndex, endIndex);
}
toggleAll(event: any) {
this.allSelected = event.target.checked;
this.selectedItems.clear();
this.itemsList.forEach(item => {
this.selectedItems.set(item.positionId, this.allSelected);
});
this.someSelected = this.itemsList.some(item => this.selectedItems.get(item.positionId));
}
onCheckboxChange(positionId: string) {
const isSelected = this.selectedItems.get(positionId) || false;
this.selectedItems.set(positionId, !isSelected);
this.allSelected = this.itemsList.every(item => this.selectedItems.get(item.positionId));
this.someSelected = this.itemsList.some(item => this.selectedItems.get(item.positionId));
}
deleteSelect() {
let employeeInfo = '';
this.selectedItems.forEach((isSelected, positionId) => {
if (isSelected) {
const item = this.itemsList.find(item => item.positionId === positionId);
if (item) {
employeeInfo += `${this.translate.instant('ชื่อตำแหน่ง')}: ${item.getName()}\n`;
}
}
});
swal({
title: "Are you sure?",
text: employeeInfo,
icon: "warning",
dangerMode: true,
buttons: ["Cancel", "Yes, Delete it!"],
})
.then((willDelete: any) => {
if (willDelete) {
this.selectedItems.forEach((isSelected, positionId) => {
if (isSelected) {
const item = this.itemsList.find(item => item.positionId === positionId);
if (item) {
this.positionService.delete(item).subscribe(result => {
swal("Save Success!!", "บันทึกข้อมูลสำเร็จ", "success");
this.getPosition();
});
}
}
});
}
});
}
}
/* tslint:disable:no-unused-variable */
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';
import { HomeCommonComponent } from './home-common.component';
describe('HomeCommonComponent', () => {
let component: HomeCommonComponent;
let fixture: ComponentFixture<HomeCommonComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ HomeCommonComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(HomeCommonComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
import { ChangeDetectorRef, Component, ElementRef, Renderer2 } from '@angular/core';
import { RouterModule } from '@angular/router';
import { SharedModule } from '../../../shared/shared.module';
import { ChartModule, CategoryService, LineSeriesService, ColumnSeriesService, TooltipService, LegendService, DataLabelService, SplineSeriesService, BarSeriesService } from '@syncfusion/ej2-angular-charts';
import { AccumulationChartModule, PieSeriesService, AccumulationDataLabelService, AccumulationTooltipService, AccumulationLegendService } from '@syncfusion/ej2-angular-charts';
@Component({
selector: 'app-home-common',
imports: [RouterModule, SharedModule, ChartModule, AccumulationChartModule],
standalone: true,
templateUrl: './home-common.component.html',
styleUrls: ['./home-common.component.css'],
providers: [CategoryService, LineSeriesService, ColumnSeriesService, TooltipService, LegendService, DataLabelService, SplineSeriesService, BarSeriesService, PieSeriesService, AccumulationDataLabelService, AccumulationTooltipService, AccumulationLegendService]
})
export class HomeCommonComponent {
// Chart 1: Total Users
public totalUsersData: Object[] = [
{ x: 1, y: 0 }, { x: 2, y: 21 }, { x: 3, y: 54 }, { x: 4, y: 38 }, { x: 5, y: 56 }, { x: 6, y: 24 }, { x: 7, y: 65 }
];
public primaryXAxis1: Object = { valueType: 'Category', majorGridLines: { width: 0 }, visible: false };
public primaryYAxis1: Object = { majorGridLines: { width: 0 }, visible: false };
public marker1: Object = { visible: false };
public tooltip1: Object = { enable: true };
public chartArea1: Object = { border: { width: 0 } };
// Chart 2: Bounce Rate
public bounceRateData: Object[] = [
{ x: 1, y: 54 }, { x: 2, y: 38 }, { x: 3, y: 56 }, { x: 4, y: 35 }, { x: 5, y: 65 }, { x: 6, y: 43 },
{ x: 7, y: 53 }, { x: 8, y: 45 }, { x: 9, y: 62 }, { x: 10, y: 80 }, { x: 11, y: 35 }, { x: 12, y: 48 }
];
public primaryXAxis2: Object = { valueType: 'Category', majorGridLines: { width: 0 }, visible: false };
public primaryYAxis2: Object = { majorGridLines: { width: 0 }, visible: false };
public chartArea2: Object = { border: { width: 0 } };
// Chart 3: Audience Report (Mixed Column/Line)
public audienceData: Object[] = [
{ x: 'Jan', y: 23, y1: 44 }, { x: 'Feb', y: 11, y1: 55 }, { x: 'Mar', y: 22, y1: 41 },
{ x: 'Apr', y: 27, y1: 67 }, { x: 'May', y: 13, y1: 22 }, { x: 'Jun', y: 22, y1: 43 },
{ x: 'Jul', y: 37, y1: 21 }, { x: 'Aug', y: 21, y1: 41 }, { x: 'Sep', y: 44, y1: 56 },
{ x: 'Oct', y: 22, y1: 27 }, { x: 'Nov', y: 45, y1: 43 }, { x: 'Dec', y: 35, y1: 27 }
];
public primaryXAxis3: Object = { valueType: 'Category', majorGridLines: { width: 0 }, lineStyle: { width: 0 } };
public primaryYAxis3: Object = { title: 'Value', lineStyle: { width: 0 }, majorTickLines: {width: 0} };
public legendSettings3: Object = { visible: true, position: 'Top' };
public tooltip3: Object = { enable: true };
// Chart 4: Top Countries (Mixed Line/Bar)
public topCountriesData: Object[] = [
{ x: 'Jan', y: 24, y1: 20 }, { x: 'Feb', y: 23, y1: 23 }, { x: 'Mar', y: 20, y1: 26 },
{ x: 'Apr', y: 25, y1: 22 }, { x: 'May', y: 27, y1: 20 }, { x: 'Jun', y: 26, y1: 26 },
{ x: 'Jul', y: 24, y1: 28 }, { x: 'Aug', y: 23, y1: 26 }, { x: 'Sep', y: 23, y1: 22 },
{ x: 'Oct', y: 25, y1: 27 }, { x: 'Nov', y: 23, y1: 25 }, { x: 'Dec', y: 23, y1: 26 }
];
public primaryXAxis4: Object = { valueType: 'Category', majorGridLines: { width: 0 }, lineStyle: { width: 0 } };
public primaryYAxis4: Object = { title: 'Value', lineStyle: { width: 0 }, majorTickLines: {width: 0} };
public legendSettings4: Object = { visible: true, position: 'Top' };
// Chart 5: Sessions by Device (Donut)
public sessionsByDeviceData: Object[] = [
{ x: 'Mobile', y: 1754, text: '68.3%' },
{ x: 'Tablet', y: 1234, text: '17.68%' },
{ x: 'Desktop', y: 878, text: '10.5%' },
{ x: 'Others', y: 270, text: '5.16%' }
];
public dataLabel5: Object = { visible: true, name: 'text', position: 'Inside' };
public legendSettings5: Object = { visible: false };
// Chart 6: Session Duration
public sessionDurationData: Object[] = [
{ x: 'Jan', y: 32, y1: 56, y2: 48 }, { x: 'Feb', y: 15, y1: 58, y2: 29 }, { x: 'Mar', y: 63, y1: 38, y2: 50 },
{ x: 'Apr', y: 51, y1: 50, y2: 69 }, { x: 'May', y: 36, y1: 64, y2: 20 }, { x: 'Jun', y: 62, y1: 45, y2: 59 },
{ x: 'Jul', y: 99, y1: 55, y2: 52 }, { x: 'Aug', y: 42, y1: 32, y2: 12 }, { x: 'Sep', y: 78, y1: 15, y2: 48 },
{ x: 'Oct', y: 76, y1: 63, y2: 28 }, { x: 'Nov', y: 32, y1: 51, y2: 17 }, { x: 'Dec', y: 120, y1: 136, y2: 98 }
];
public primaryXAxis6: Object = { valueType: 'Category', majorGridLines: { width: 0 }, visible: false };
public primaryYAxis6: Object = { visible: false };
public legendSettings6: Object = { visible: true, position: 'Top' };
constructor(private el: ElementRef, private renderer: Renderer2, private cdr: ChangeDetectorRef) {
}
}
<!-- <div class="modal-header">
<h5 class="modal-title" id="editLabel">ข้อความแจ้งเตือน</h5>
<button type="button" class="close" (click)="activeModal.dismiss('dismiss')" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<ng-container *ngIf="innerHTML!=undefined then InnerHTML else Message"></ng-container>
<ng-template #Message>
<div class="modal-body">
{{message}}
</div>
</ng-template>
<ng-template #InnerHTML>
<div class="modal-body" [innerHTML]="innerHTML">
</div>
</ng-template> -->
<div class="modal-header">
<h5 class="modal-title" id="editLabel">ข้อความแจ้งเตือน</h5>
<button type="button" class="close" (click)="close()" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<ng-container *ngIf="data.innerHTML != undefined then InnerHTML else Message"></ng-container>
<ng-template #Message>
<div class="modal-body">
{{data.message}}
</div>
</ng-template>
<ng-template #InnerHTML>
<div class="modal-body" [innerHTML]="data.innerHTML">
</div>
</ng-template>
\ No newline at end of file
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { AlertModalComponent } from './alert-modal.component';
describe('AlertModalComponent', () => {
let component: AlertModalComponent;
let fixture: ComponentFixture<AlertModalComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ AlertModalComponent ]
})
.compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(AlertModalComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
import { Component, OnInit, Inject } from '@angular/core';
import { MatDialogRef, MAT_DIALOG_DATA, MatDialogModule } from '@angular/material/dialog';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
@Component({
selector: 'app-alert-modal',
templateUrl: './alert-modal.component.html',
styleUrls: ['./alert-modal.component.scss'],
standalone: true,
imports: [
CommonModule,
FormsModule,
MatDialogModule
]
})
export class AlertModalComponent implements OnInit {
constructor(
public dialogRef: MatDialogRef<AlertModalComponent>,
@Inject(MAT_DIALOG_DATA) public data: { message: string; innerHTML?: string }
) { }
ngOnInit(): void {
}
close(): void {
this.dialogRef.close();
}
}
\ No newline at end of file
<div class="modal-header">
<h5 class="modal-title" id="editLabel">ข้อความแจ้งเตือน</h5>
<button type="button" class="close" (click)="activeModal.dismiss('dismiss')" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="modal-body">
{{message}}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-info" (click)="activeModal.close('close')">
ยืนยัน
</button>
<button type="button" class="btn btn-danger" (click)="activeModal.dismiss('dismiss')">
ยกเลิก
</button>
</div>
\ No newline at end of file
import { Component, Input, OnInit } from '@angular/core';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
@Component({
selector: 'app-confirm-modal',
templateUrl: './confirm-modal.component.html',
styleUrls: ['./confirm-modal.component.scss']
})
export class ConfirmModalComponent implements OnInit {
@Input() message: string = "";
constructor(public activeModal: NgbActiveModal) { }
ngOnInit(): void {
}
}
.secure-input {
-webkit-text-security: disc;
text-security: disc;
}
\ No newline at end of file
/* tslint:disable:no-unused-variable */
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';
import { ExcelReportComponent } from './excel-report.component';
describe('ExcelReportComponent', () => {
let component: ExcelReportComponent;
let fixture: ComponentFixture<ExcelReportComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ ExcelReportComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(ExcelReportComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
/* tslint:disable:no-unused-variable */
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';
import { HomeCommonComponent } from './home-common.component';
describe('HomeCommonComponent', () => {
let component: HomeCommonComponent;
let fixture: ComponentFixture<HomeCommonComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ HomeCommonComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(HomeCommonComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
::ng-deep ng2-dropdown-menu {
z-index: 9999 !important;
.ng2-dropdown-menu {
z-index: 9999 !important;
ng2-menu-item {
z-index: 9999 !important;
}
}
}
\ No newline at end of file
::ng-deep ng2-dropdown-menu {
z-index: 9999 !important;
.ng2-dropdown-menu {
z-index: 9999 !important;
ng2-menu-item {
z-index: 9999 !important;
}
}
}
\ No newline at end of file
::ng-deep ng2-dropdown-menu {
z-index: 9999 !important;
.ng2-dropdown-menu {
z-index: 9999 !important;
ng2-menu-item {
z-index: 9999 !important;
}
}
}
\ No newline at end of file
<app-page-header [title]="'รายการเอกสารผ่านการอนุมัติ'" [activeTitle]="'รายการเอกสารผ่านการอนุมัติ'" [title1]="'อนุมัติหลักสูตร'"></app-page-header>
<!-- <div class="row">
<div class="col-12">
<div class="card card-body">
<h4 class="card-title">รายการเอกสาร</h4>
<div class="row justify-content-center">
<div class="col-md-4 " *ngFor="let c of testdata|slice: (page-1) * pageSize : (page-1) * pageSize + pageSize">
<div class="card border border-2">
<div class="card-body text-center">
<img src="{{ c.img }}" class="rounded-circle border p-1" width="100">
<h3 class="card-title mt-3 mb-0">{{c.name}}</h3>
</div>
<div class="d-flex justify-content-between bg-light border-top p-3">
<div>
<span class="align-middle">จำนวนเอกสาร {{ c.document }} ฉบับ</span>
</div>
<div >
<button class="btn btn-info btn-sm text-nowrap" (click)="openView(c.id)">รายละเอียด</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div> -->
<div class="max-w-7xl mx-auto">
<div class="box p-4">
<h4 class="text-xl font-semibold text-gray-800 mb-6">รายการเอกสาร</h4>
<!-- Flex แทน Grid -->
<div class="flex flex-wrap justify-center gap-6">
<div
class=" bg-white rounded-xl shadow-lg overflow-hidden transform hover:scale-105 transition duration-300 ease-in-out flex flex-col" style="width: 30%;"
*ngFor="let c of testdata | slice: (page-1) * pageSize : (page-1) * pageSize + pageSize"
>
<div class="p-8 text-center">
<div class="w-24 h-24 mx-auto rounded-full bg-green-100 flex items-center justify-center shadow-inner">
<img src="{{ c.img }}" class="" alt="" />
</div>
<h3 class="text-2xl font-bold text-gray-800 mt-6 mb-2">{{ c.name }}</h3>
</div>
<!-- Footer -->
<div class="mt-auto">
<div class="flex justify-between items-center bg-gray-50 border-t border-gray-200 p-4">
<div>
<span class="text-sm text-gray-700">จำนวนเอกสาร {{ c.document }} ฉบับ</span>
</div>
<div>
<button
class="bg-primary inline-flex items-center px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white text-sm font-medium rounded-md shadow-md
active hover:bg-success hover:scale-110 transition duration-300 ease-in-out focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-opacity-50"
(click)="openView(c.id)"
>
รายละเอียด
</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
\ No newline at end of file
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { ApprovedListComponent } from './approved-list.component';
describe('ApprovedListComponent', () => {
let component: ApprovedListComponent;
let fixture: ComponentFixture<ApprovedListComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ ApprovedListComponent ]
})
.compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(ApprovedListComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
import { Component, OnInit } from '@angular/core';
import { Router, RouterModule } from '@angular/router';
import { DocumentService } from '../../../../services/document.service';
import { CourseService } from '../../../../services/course.service';
import { ExcelService } from '../../../../services/excel.service';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { TranslateModule } from '@ngx-translate/core';
import { SharedModule } from '../../../../../shared/shared.module';
@Component({
selector: 'app-approved-list',
templateUrl: './approved-list.component.html',
styleUrls: ['./approved-list.component.scss'],
standalone: true,
imports: [
CommonModule,
FormsModule,
RouterModule,
TranslateModule,
SharedModule,
],
})
export class ApprovedListComponent implements OnInit {
constructor(
private routes: Router,
private excelService:ExcelService,private documentService:DocumentService,private courseService:CourseService
) {}
page = 1;
pageSize = 10;
testdata: {
id:string;
img: String;
name: String;
details: String;
document: String;
}[] = [];
ngOnInit() {
this.testdata = [
{
id:'1',
img: "assets/images/icons/excel.png",
name: "Excel",
details: "xxxxxxxxxxxxxxxxxxxxxxxxxxx",
document: "0"
},
{
id:'2',
img: "assets/images/icons/document.png",
name: "Document",
details: "xxxxxxxxxxxxxxxxxxxxxxxxxxx",
document: "0"
},
{
id:'3',
img: "assets/images/icons/course.png",
name: "Course",
details: "xxxxxxxxxxxxxxxxxxxxxxxxxxx",
document: "0"
},
];
this.getListCount();
}
async getListCount(){
try {
const countExcel = await this.excelService.getCountContent().toPromise();
const countDoc = await this.documentService.getCountContent().toPromise();
const countCourse = await this.courseService.getCountContent().toPromise();
this.testdata.forEach((x ,i) => {
if(i == 0){
x.document = (countExcel ?? 0).toString()
}else if(i == 1){
x.document = (countDoc ?? 0).toString()
}else if(i == 2){
x.document = (countCourse ?? 0).toString()
}
})
} catch (error) {
console.error('Error loading data:', error);
}
}
openView(id:string){
if(id =='1'){
this.routes.navigate(['/admin/view-list-excel/1']);
}else if(id =='2'){
this.routes.navigate(['/admin/view-list-doc/1']);
}else if(id =='3'){
this.routes.navigate(['/admin/view-list-course/1']);
}
}
}
import { Component, OnInit } from '@angular/core';
import { NgbModal, NgbPaginationModule } from '@ng-bootstrap/ng-bootstrap';
import { ActivatedRoute } from '@angular/router';
import { OpenImageComponent } from '../../../open-image/open-image.component';
import { ConfirmModalComponent } from '../../../confirm-modal/confirm-modal.component';
import { AlertModalComponent } from '../../../alert-modal/alert-modal.component';
import { firstValueFrom } from 'rxjs';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { RouterModule } from '@angular/router';
import { NgSelectModule } from '@ng-select/ng-select';
import { SharedModule } from '../../../../../../shared/shared.module';
import { MatDialogModule } from '@angular/material/dialog';
import { TranslateModule } from '@ngx-translate/core';
import { CourseContentModel } from '../../../../../models/course-content.model';
import { CourseService } from '../../../../../services/course.service';
declare var require: any
import FileSaver from 'file-saver';
@Component({
selector: 'app-view-list-course',
templateUrl: './view-list-course.component.html',
styleUrls: ['./view-list-course.component.scss'],
standalone: true,
imports: [
CommonModule,
FormsModule,
RouterModule,
NgSelectModule,
SharedModule,
MatDialogModule,
TranslateModule,
NgbPaginationModule,
],
})
export class ViewListCourseComponent implements OnInit {
page = 0;
pageSize = 10;
listCourse: CourseContentModel[] = []
search: string = ''
checkType: string = '0'
pagedItems: CourseContentModel[];
constructor(private modalService: NgbModal, private courseService: CourseService, private activatedRoute: ActivatedRoute) {
this.activatedRoute.paramMap.subscribe(result => {
this.checkType = result.get("type")!;
});
}
get totalItems(): number {
return this.search == ''
? this.listCourse.length
: this.filterListCourse().length;
}
get totalPages(): number {
return Math.ceil(this.totalItems / this.pageSize);
}
get totalPagesArray(): number[] {
return Array(this.totalPages).fill(0);
}
goToPage(index: number): void {
if (index < 0 || index >= this.totalPages) return;
this.page = index;
this.updatePagedItems();
}
updatePagedItems() {
const data: CourseContentModel[] = this.search === '' ? this.listCourse : this.filterListCourse();
const start = this.page * this.pageSize;
const end = start + this.pageSize;
this.pagedItems = data.slice(start, end);
}
openEmployeeModal(image: string) {
const modalRef = this.modalService.open(OpenImageComponent, {
centered: true,
windowClass: 'my-dialog-img-preview'
})
modalRef.componentInstance.linkImage = image
modalRef.result.then(result => {
}, reason => {
this.modalService.dismissAll()
})
}
async downloadFile(logId: string) {
try {
const data = await this.courseService.downloadFileContent(logId).toPromise();
if (data) {
FileSaver.saveAs(new Blob([data]), "file_download.json");
}
} catch (error) {
console.error('Error loading data:', error);
}
}
filterListCourse() {
return this.listCourse.filter(x => x.thName.toLowerCase().includes(this.search.toLowerCase()) || x.engName.toLowerCase().includes(this.search.toLowerCase()))
}
async getListCourse() {
try {
const data = await firstValueFrom(this.courseService.getListCourseContent('0'));
this.listCourse = data.map(x => new CourseContentModel(x))
console.log("🚀 ~ ViewListCourseComponent ~ getListCourse ~ this.listCourse :", this.listCourse)
} catch (error) {
console.error('Error loading data:', error);
}
}
deleteFile(item: CourseContentModel) {
const modalRef = this.modalService.open(ConfirmModalComponent, {
centered: true,
backdrop: 'static',
})
modalRef.componentInstance.message = 'คุณต้องการลบข้อมูลหรือไม่'
modalRef.result.then(result => {
this.courseService.deleteCourseContent(item).subscribe(result => {
if (result) {
this.openAlertModal('ลบข้อมูลสำเร็จ')
this.getListCourse();
} else {
this.openAlertModal('ไม่สามารถลบข้อมูลได้')
}
}, error => {
this.openAlertModal(error.message)
})
}, reject => { })
}
ngOnInit() {
this.getListCourse();
}
openLink(url: string) {
window.open(url, "_blank");
}
openAlertModal(message?: string) {
const modalRef = this.modalService.open(AlertModalComponent, {
centered: true,
backdrop: 'static'
})
modalRef.componentInstance.message = message ? message : ""
modalRef.result.then(result => {
this.modalService.dismissAll()
}, reason => {
this.modalService.dismissAll()
})
}
coverDate(date: string) {
return date.split('-').reverse().join('/')
}
}
import { Component, OnInit } from '@angular/core';
import { NgbModal, NgbPaginationModule } from '@ng-bootstrap/ng-bootstrap';
import { ActivatedRoute } from '@angular/router';
import { OpenImageComponent } from '../../../open-image/open-image.component';
import { ConfirmModalComponent } from '../../../confirm-modal/confirm-modal.component';
import { AlertModalComponent } from '../../../alert-modal/alert-modal.component';
import { firstValueFrom } from 'rxjs';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { RouterModule } from '@angular/router';
import { NgSelectModule } from '@ng-select/ng-select';
import { SharedModule } from '../../../../../../shared/shared.module';
import { MatDialogModule } from '@angular/material/dialog';
import { TranslateModule } from '@ngx-translate/core';
import { DocumentContentModel } from '../../../../../models/document-content.model';
import { DocumentService } from '../../../../../services/document.service';
declare var require: any
import FileSaver from 'file-saver';
@Component({
selector: 'app-view-list-doc',
templateUrl: './view-list-doc.component.html',
styleUrls: ['./view-list-doc.component.scss'],
standalone: true,
imports: [
CommonModule,
FormsModule,
RouterModule,
NgSelectModule,
SharedModule,
MatDialogModule,
TranslateModule,
NgbPaginationModule,
],
})
export class ViewListDocComponent implements OnInit {
page = 0;
pageSize = 10;
listDoc: DocumentContentModel[] = []
search: string = ''
checkType: string = '0'
pagedItems: DocumentContentModel[] = [];
constructor(private modalService: NgbModal, private documentService: DocumentService, private activatedRoute: ActivatedRoute) {
this.activatedRoute.paramMap.subscribe(result => {
this.checkType = result.get("type")!;
});
}
get totalItems(): number {
return this.search == ''
? this.listDoc.length
: this.filterListDoc().length;
}
get totalPages(): number {
return Math.ceil(this.totalItems / this.pageSize);
}
get totalPagesArray(): number[] {
return Array(this.totalPages).fill(0);
}
goToPage(index: number): void {
if (index < 0 || index >= this.totalPages) return;
this.page = index;
this.updatePagedItems();
}
updatePagedItems() {
const data: DocumentContentModel[] = this.search === '' ? this.listDoc : this.filterListDoc();
const start = this.page * this.pageSize;
const end = start + this.pageSize;
this.pagedItems = data.slice(start, end);
}
openEmployeeModal(image: string) {
const modalRef = this.modalService.open(OpenImageComponent, {
centered: true,
windowClass: 'my-dialog-img-preview'
})
modalRef.componentInstance.linkImage = image
modalRef.result.then(result => {
}, reason => {
this.modalService.dismissAll()
})
}
deleteFile(item: DocumentContentModel) {
const modalRef = this.modalService.open(ConfirmModalComponent, {
centered: true,
backdrop: 'static',
})
modalRef.componentInstance.message = 'คุณต้องการลบข้อมูลหรือไม่'
modalRef.result.then(result => {
this.documentService.deleteExcelContent(item).subscribe(result => {
if (result) {
this.openAlertModal('ลบข้อมูลสำเร็จ')
this.getListDoc();
} else {
this.openAlertModal('ไม่สามารถลบข้อมูลได้')
}
}, error => {
this.openAlertModal(error.message)
})
}, reject => { })
}
async downloadFile(logId: string, lang: string) {
try {
const data = await this.documentService.downloadFileContent(logId, lang).toPromise();
if (data) {
FileSaver.saveAs(new Blob([data]), "file_download.doc");
}
} catch (error) {
console.error('Error loading data:', error);
}
}
filterListDoc() {
return this.listDoc.filter(x => x.thName.toLowerCase().includes(this.search.toLowerCase()) || x.engName.toLowerCase().includes(this.search.toLowerCase()))
}
async getListDoc() {
try {
const data = await firstValueFrom(this.documentService.getListExcelContent('0'));
this.listDoc = data.map(x => new DocumentContentModel(x))
} catch (error) {
console.error('Error loading data:', error);
}
}
ngOnInit() {
this.getListDoc();
}
openAlertModal(message?: string) {
const modalRef = this.modalService.open(AlertModalComponent, {
centered: true,
backdrop: 'static'
})
modalRef.componentInstance.message = message ? message : ""
modalRef.result.then(result => {
this.modalService.dismissAll()
}, reason => {
this.modalService.dismissAll()
})
}
openLink(url: string) {
window.open(url, "_blank");
}
coverDate(date: string) {
return date.split('-').reverse().join('/')
}
}
import { Component, OnInit } from '@angular/core';
import { NgbModal, NgbPaginationModule } from '@ng-bootstrap/ng-bootstrap';
import { ActivatedRoute } from '@angular/router';
import { ExcelContentModel } from '../../../../../models/excel-content.model';
import { ExcelService } from '../../../../../services/excel.service';
import { OpenImageComponent } from '../../../open-image/open-image.component';
import { ConfirmModalComponent } from '../../../confirm-modal/confirm-modal.component';
import { AlertModalComponent } from '../../../alert-modal/alert-modal.component';
import { firstValueFrom } from 'rxjs';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { RouterModule } from '@angular/router';
import { NgSelectModule } from '@ng-select/ng-select';
import { SharedModule } from '../../../../../../shared/shared.module';
import { MatDialogModule } from '@angular/material/dialog';
import { TranslateModule } from '@ngx-translate/core';
declare var require: any
import FileSaver from 'file-saver';
@Component({
selector: 'app-view-list-excel',
templateUrl: './view-list-excel.component.html',
styleUrls: ['./view-list-excel.component.scss'],
standalone: true,
imports: [
CommonModule,
FormsModule,
RouterModule,
NgSelectModule,
SharedModule,
MatDialogModule,
TranslateModule,
NgbPaginationModule,
],
})
export class ViewListExcelComponent implements OnInit {
page = 0;
pageSize = 10;
listExcel: ExcelContentModel[] = []
search: string = ''
checkType: string = '0'
pagedItems: ExcelContentModel[] = [];
constructor(private modalService: NgbModal, private excelService: ExcelService, private activatedRoute: ActivatedRoute,) {
this.activatedRoute.paramMap.subscribe(result => {
this.checkType = result.get("type")!;
});
}
get totalItems(): number {
return this.search == ''
? this.listExcel.length
: this.filterListExcel().length;
}
get totalPages(): number {
return Math.ceil(this.totalItems / this.pageSize);
}
get totalPagesArray(): number[] {
return Array(this.totalPages).fill(0);
}
goToPage(index: number): void {
if (index < 0 || index >= this.totalPages) return;
this.page = index;
this.updatePagedItems();
}
updatePagedItems() {
const data: ExcelContentModel[] = this.search === '' ? this.listExcel : this.filterListExcel();
const start = this.page * this.pageSize;
const end = start + this.pageSize;
this.pagedItems = data.slice(start, end);
}
openEmployeeModal(image: string) {
const modalRef = this.modalService.open(OpenImageComponent, {
centered: true,
windowClass: 'my-dialog-img-preview'
})
modalRef.componentInstance.linkImage = image
modalRef.result.then(result => {
}, reason => {
this.modalService.dismissAll()
})
}
deleteFile(item: ExcelContentModel) {
const modalRef = this.modalService.open(ConfirmModalComponent, {
centered: true,
backdrop: 'static',
})
modalRef.componentInstance.message = 'คุณต้องการลบข้อมูลหรือไม่'
modalRef.result.then(result => {
this.excelService.deleteExcelContent(item).subscribe(result => {
if (result) {
this.openAlertModal('ลบข้อมูลสำเร็จ')
this.getListExcel();
} else {
this.openAlertModal('ไม่สามารถลบข้อมูลได้')
}
}, error => {
this.openAlertModal(error.message)
})
}, reject => { })
}
async downloadFile(logId: string) {
try {
const data = await this.excelService.downloadFileContent(logId).toPromise();
if (data) {
FileSaver.saveAs(new Blob([data]), "file_download.xlsx");
}
} catch (error) {
console.error('Error loading data:', error);
}
}
getStatus(status: string): string {
if (status === '0') {
return 'รออนุมัติ';
} else if (status === '1') {
return 'เปิดใช้งาน';
} else if (status === '2') {
return 'ไม่อนุมัติ';
} else {
return 'ไม่ทราบสถานะ'; // สำหรับกรณีที่ไม่ตรงกับเงื่อนไขใดเลย
}
}
filterListExcel() {
return this.listExcel.filter(x => x.thName.toLowerCase().includes(this.search.toLowerCase()) || x.engName.toLowerCase().includes(this.search.toLowerCase()))
}
async getListExcel() {
try {
const data = await firstValueFrom(this.excelService.getListExcelContent('0'));
this.listExcel = data.map(x => new ExcelContentModel(x))
} catch (error) {
console.error('Error loading data:', error);
}
}
ngOnInit() {
this.getListExcel();
}
openLink(url: string) {
window.open(url, "_blank");
}
openAlertModal(message?: string) {
const modalRef = this.modalService.open(AlertModalComponent, {
centered: true,
backdrop: 'static'
})
modalRef.componentInstance.message = message ? message : ""
modalRef.result.then(result => {
this.modalService.dismissAll()
}, reason => {
this.modalService.dismissAll()
})
}
coverDate(date: string) {
return date.split('-').reverse().join('/')
}
}
/* tslint:disable:no-unused-variable */
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';
import { ManagementComponent } from './management.component';
describe('ManagementComponent', () => {
let component: ManagementComponent;
let fixture: ComponentFixture<ManagementComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ ManagementComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(ManagementComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-management',
templateUrl: './management.component.html',
styleUrls: ['./management.component.css']
})
export class ManagementComponent implements OnInit {
constructor() { }
ngOnInit() {
}
}
import { Component, OnInit } from '@angular/core';
import { NgbModal, NgbPaginationModule } from '@ng-bootstrap/ng-bootstrap';
import { CourseModel } from '../../../../../models/course.model';
import { CourseService } from '../../../../../services/course.service';
import { OpenImageComponent } from '../../../open-image/open-image.component';
import { ConfirmModalComponent } from '../../../confirm-modal/confirm-modal.component';
import { AlertModalComponent } from '../../../alert-modal/alert-modal.component';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { RouterModule } from '@angular/router';
import { NgSelectModule } from '@ng-select/ng-select';
import { SharedModule } from '../../../../../../shared/shared.module';
import { MatDialogModule } from '@angular/material/dialog';
import { TranslateModule } from '@ngx-translate/core';
import { firstValueFrom } from 'rxjs';
declare var require: any
import FileSaver from 'file-saver';
@Component({
selector: 'app-approve-course',
templateUrl: './approve-course.component.html',
styleUrls: ['./approve-course.component.scss'],
standalone: true,
imports: [
CommonModule,
FormsModule,
RouterModule,
NgSelectModule,
SharedModule,
MatDialogModule,
TranslateModule,
NgbPaginationModule,
],
})
export class ApproveCourseComponent implements OnInit {
page = 0;
pageSize = 10;
listCourse: CourseModel[] = []
search: string = ''
pagedItems: CourseModel[] = [];
constructor(private modalService: NgbModal, private courseService: CourseService) {
}
get totalItems(): number {
return this.search == ''
? this.listCourse.length
: this.filterListCourse().length;
}
get totalPages(): number {
return Math.ceil(this.totalItems / this.pageSize);
}
get totalPagesArray(): number[] {
return Array(this.totalPages).fill(0);
}
goToPage(index: number): void {
if (index < 0 || index >= this.totalPages) return;
this.page = index;
this.updatePagedItems();
}
updatePagedItems() {
const data: CourseModel[] = this.search === '' ? this.listCourse : this.filterListCourse();
const start = this.page * this.pageSize;
const end = start + this.pageSize;
this.pagedItems = data.slice(start, end);
}
openEmployeeModal(image: string) {
const modalRef = this.modalService.open(OpenImageComponent, {
centered: true,
windowClass: 'my-dialog-img-preview'
})
modalRef.componentInstance.linkImage = image
modalRef.result.then(result => {
}, reason => {
this.modalService.dismissAll()
})
}
async downloadFile(logId: string) {
try {
const data = await this.courseService.downloadFile(logId).toPromise();
if (data) {
FileSaver.saveAs(new Blob([data]), "file_download.json");
}
} catch (error) {
console.error('Error loading data:', error);
}
}
filterListCourse() {
return this.listCourse.filter(x => x.thName.toLowerCase().includes(this.search.toLowerCase()) || x.engName.toLowerCase().includes(this.search.toLowerCase()))
}
async getListCourse() {
try {
const data = await firstValueFrom(this.courseService.getListCourse('0'));
this.listCourse = data.map(x => new CourseModel(x))
} catch (error) {
console.error('Error loading data:', error);
}
}
onApprove(item: CourseModel) {
const modalRef = this.modalService.open(ConfirmModalComponent, {
centered: true,
backdrop: 'static',
})
modalRef.componentInstance.message = 'คุณต้องการอนุมัติข้อมูลหรือไม่'
modalRef.result.then(result => {
item.status = 1
this.courseService.approve(item).subscribe(result => {
if (result) {
this.modalService.dismissAll()
this.openAlertModal('บันทึกข้อมูลสำเร็จ')
this.getListCourse();
} else {
this.openAlertModal('ไม่สามารถบันทึกข้อมูลได้')
}
}, error => {
this.openAlertModal(error.message)
})
}, reject => { })
}
onCancelApprove(item: CourseModel) {
const modalRef = this.modalService.open(ConfirmModalComponent, {
centered: true,
backdrop: 'static',
})
modalRef.componentInstance.message = 'คุณต้องการไม่อนุมัติข้อมูลหรือไม่'
modalRef.result.then(result => {
item.status = 2
this.courseService.approve(item).subscribe(result => {
if (result) {
this.openAlertModal('บันทึกข้อมูลสำเร็จ')
this.getListCourse();
} else {
this.openAlertModal('ไม่สามารถบันทึกข้อมูลได้')
}
}, error => {
this.openAlertModal(error.message)
})
}, reject => { })
}
ngOnInit() {
this.getListCourse();
}
deleteFile(item: CourseModel) {
const modalRef = this.modalService.open(ConfirmModalComponent, {
centered: true,
backdrop: 'static',
})
modalRef.componentInstance.message = 'คุณต้องการลบข้อมูลหรือไม่'
modalRef.result.then(result => {
this.courseService.deleteCourse(item).subscribe(result => {
if (result) {
this.openAlertModal('ลบข้อมูลสำเร็จ')
this.getListCourse();
} else {
this.openAlertModal('ไม่สามารถลบข้อมูลได้')
}
}, error => {
this.openAlertModal(error.message)
})
}, reject => { })
}
openAlertModal(message?: string) {
const modalRef = this.modalService.open(AlertModalComponent, {
centered: true,
backdrop: 'static'
})
modalRef.componentInstance.message = message ? message : ""
modalRef.result.then(result => {
// this.modalService.dismissAll()
}, reason => {
// this.modalService.dismissAll()
})
}
openLink(url: string) {
window.open(url, "_blank");
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment