Deployment 25.4

- Fix some bug
- Config Security
This commit is contained in:
Nguyen Ha Khue
2023-04-25 18:20:58 +07:00
parent fe41791608
commit 7bf25cdd54
23 changed files with 750 additions and 187 deletions
@@ -10,6 +10,7 @@ import { resolve } from 'path';
import { forkJoin } from 'rxjs';
import { UserService } from 'src/app/shared/service/user.service';
import { FirebaseService } from 'src/app/shared/service/firebase.service';
import { UserInfo } from 'src/app/shared/tables/user';
@Component({
selector: 'app-dashboard',
@@ -18,9 +19,11 @@ import { FirebaseService } from 'src/app/shared/service/firebase.service';
})
export class DashboardComponent implements OnInit, AfterViewInit {
//Log-in
token = localStorage.getItem("jwt-token")
userInfo: UserInfo;
isShop: boolean = false;
loggedId: number = Number(localStorage.getItem('user-id'))
loggedRole = localStorage.getItem('user-role');
loggedId: number;
loggedRole: string;
shopId: number;
//Shop Properties
@@ -71,17 +74,20 @@ export class DashboardComponent implements OnInit, AfterViewInit {
ngOnInit() {
if (this.loggedRole != 'ROLE_ADMIN') {
this.isShop = true;
// this.shopId = Number(localStorage.getItem('shop-id'))
this.userService.getUserByToken(this.token).subscribe((userInfo) => {
if (userInfo.userRole != 'ROLE_ADMIN') {
this.isShop = true;
this.shopId = userInfo.shopId;
const shopIdPromise = new Promise<number>((resolve) => {
const shopId = Number(localStorage.getItem('shop-id'));
resolve(shopId);
})
// this.shopId = Number(localStorage.getItem('shop-id'))
shopIdPromise.then((shopId) => {
this.shopId = shopId;
// const shopIdPromise = new Promise<number>((resolve) => {
// const shopId = Number(localStorage.getItem('shop-id'));
// resolve(shopId);
// })
// shopIdPromise.then((shopId) => {
// this.shopId = shopId;
this.productService.getProductsByShopIdNoPageable(this.shopId).subscribe((products) => {
let i = 0;
@@ -106,44 +112,47 @@ export class DashboardComponent implements OnInit, AfterViewInit {
this.doughtnutData(data.products);
})
this.orderService.getOrdersByShopId(this.shopId, this.thePageNumber - 1, this.thePageSize, this.sortBy, this.sortDir)
this.orderService.getOrdersByShopId(userInfo.shopId, this.thePageNumber - 1, this.thePageSize, this.sortBy, this.sortDir)
.subscribe(this.processResult());
this.shopService.getShopRevenue(this.shopId, 30).subscribe((res) => {
this.shopService.getShopRevenue(userInfo.shopId, 30).subscribe((res) => {
this.totalRevenue = res;
});
this.valueOfShopDistrict();
})
}
else {
//ADMIN DO HERE
// })
this.userService.countNewUser(this.day).subscribe((res) => {
this.totalUser = res;
})
this.productService.getProductsNoPagination().subscribe((products) => {
let i = 0;
products.forEach(product => {
this.totalReviewCount = this.totalReviewCount + product.reviewCount;
this.totalProducts = this.totalProducts + product.sold;
if (product.averageRating != 0) {
this.totalAverageRating = this.totalAverageRating + product.averageRating;
i++;
}
});
this.totalAverageRating = this.totalAverageRating / i;
})
}
else {
//ADMIN DO HERE
this.productService.getProductsPaginationAndSort(0, 5, 'sold', 'desc').subscribe((data) => {
this.products = data.products;
this.doughtnutData(data.products)
})
this.userService.countNewUser(this.day).subscribe((res) => {
this.totalUser = res;
})
this.productService.getProductsNoPagination().subscribe((products) => {
let i = 0;
products.forEach(product => {
this.totalReviewCount = this.totalReviewCount + product.reviewCount;
this.totalProducts = this.totalProducts + product.sold;
if (product.averageRating != 0) {
this.totalAverageRating = this.totalAverageRating + product.averageRating;
i++;
}
});
this.totalAverageRating = this.totalAverageRating / i;
})
this.orderService
.getOrdersPagination(this.thePageNumber - 1, this.thePageSize, this.sortBy, this.sortDir)
.subscribe(this.processResult());
this.productService.getProductsPaginationAndSort(0, 5, 'sold', 'desc').subscribe((data) => {
this.products = data.products;
this.doughtnutData(data.products)
})
this.valueOfAdminDistrict();
}
this.orderService
.getOrdersPagination(this.thePageNumber - 1, this.thePageSize, this.sortBy, this.sortDir)
.subscribe(this.processResult());
this.valueOfAdminDistrict();
}
})
}
processResult() {
@@ -155,10 +164,6 @@ export class DashboardComponent implements OnInit, AfterViewInit {
};
}
// doughnut 2
public view = chartData.view;
public doughnutChartColorScheme = chartData.doughnutChartcolorScheme;
@@ -15,6 +15,8 @@ import { ProductImageService } from 'src/app/shared/service/product-image.servic
import { ProductImage } from 'src/app/shared/tables/product-image';
import { ToastrService } from 'ngx-toastr';
import { error } from 'console';
import { UserService } from 'src/app/shared/service/user.service';
import { userInfo } from 'os';
@Component({
@@ -29,9 +31,8 @@ export class AddProductComponent implements OnInit {
public Editor = ClassicEditor;
//Log-in
token: string = localStorage.getItem("jwt-token");
isShop: boolean = false;
loggedId: number = Number(localStorage.getItem('user-id'))
loggedRole = localStorage.getItem('user-role');
shopId: number;
adminImg = environment.adminImg;
@@ -54,7 +55,8 @@ export class AddProductComponent implements OnInit {
private productImageService: ProductImageService,
private modalService: BsModalService,
private storage: AngularFireStorage,
private toastService: ToastrService) {
private toastService: ToastrService,
private userService: UserService) {
this.productForm = this.fb.group({
name: new FormControl("", [Validators.required, Validators.minLength(2)]),
price: new FormControl("", [Validators.required, Validators.pattern("^[0-9]*$")]),
@@ -66,12 +68,14 @@ export class AddProductComponent implements OnInit {
}
ngOnInit() {
if (this.loggedRole != 'ROLE_ADMIN') {
this.isShop = true;
this.shopId = Number(localStorage.getItem('shop-id'))
}
this.productForm.patchValue({
shopId: this.shopId
this.userService.getUserByToken(this.token).subscribe((userInfo) => {
if (userInfo.userRole != 'ROLE_ADMIN') {
this.isShop = true;
this.shopId = userInfo.shopId;
this.productForm.patchValue({
shopId: this.shopId
})
}
})
}
@@ -138,25 +142,6 @@ export class AddProductComponent implements OnInit {
this.modalRef = this.modalService.show(this.errorShopModal, { class: 'modal-sm' });
}
})
// Promise.all(uploadPromises).then(() => {
// this.productService.addProduct(product).pipe(
// switchMap((product) => {
// this.createdId = product.id;
// return this.imageUrls;
// }),
// concatMap((url) => {
// const img = new ProductImage();
// img.id = 0;
// img.imageUrl = url;
// img.productId = this.createdId;
// return this.productImageService.addProductImage(img, img.productId);
// })
// resolve();
// })
})
}
@@ -2,6 +2,7 @@ import { Component, OnInit, TemplateRef } from '@angular/core';
import { Router } from '@angular/router';
import { BsModalRef, BsModalService } from 'ngx-bootstrap/modal';
import { ProductService } from "../../../../shared/service/product.service";
import { UserService } from 'src/app/shared/service/user.service';
@Component({
selector: 'app-product-list',
@@ -11,8 +12,8 @@ import { ProductService } from "../../../../shared/service/product.service";
export class ProductListComponent implements OnInit {
//Login Info
loggedId: number = Number(localStorage.getItem('user-id'));
loggedRole: string = localStorage.getItem('user-role');
token: string = localStorage.getItem("jwt-token");
loggedRole: string;
isShop: boolean = false;
shopId: number;
@@ -27,16 +28,20 @@ export class ProductListComponent implements OnInit {
theTotalElements = 0;
constructor(private productService: ProductService,
private userService: UserService,
private modalService: BsModalService,
private router: Router) {
}
ngOnInit() {
if (this.loggedRole != 'ROLE_ADMIN') {
this.isShop = true;
this.shopId = Number(localStorage.getItem('shop-id'))
}
this.listProduct();
this.userService.getUserByToken(this.token).subscribe((userInfo) => {
this.loggedRole = userInfo.userRole;
if (userInfo.userRole != 'ROLE_ADMIN') {
this.isShop = true;
this.shopId = userInfo.shopId;
}
this.listProduct();
})
}
listProduct() {
@@ -10,6 +10,7 @@ import { OrderService } from "src/app/shared/service/order.service";
import { BsModalRef, BsModalService } from "ngx-bootstrap/modal";
import { Shipper } from "src/app/shared/tables/shipper";
import { ShipperService } from "src/app/shared/service/shipper.service";
import { UserService } from "src/app/shared/service/user.service";
@Component({
selector: "app-orders",
@@ -19,9 +20,9 @@ import { ShipperService } from "src/app/shared/service/shipper.service";
})
export class OrdersComponent implements OnInit {
//Log-in
token: string = localStorage.getItem("jwt-token");
isShop: boolean = false;
loggedId: number = Number(localStorage.getItem('user-id'))
loggedRole = localStorage.getItem('user-role');
loggedRole: string;
shopId: number;
//Required properties
@@ -56,15 +57,19 @@ export class OrdersComponent implements OnInit {
orderStatuses = ["Chờ xác nhận", "Đã xác nhận", "Đang giao hàng", "Giao thành công", "Đã huỷ đơn", "Không nhận hàng"];
constructor(private orderService: OrderService,
private userService: UserService,
private shipperService: ShipperService,
private modalService: BsModalService) { }
ngOnInit() {
if (this.loggedRole != 'ROLE_ADMIN') {
this.isShop = true;
this.shopId = Number(localStorage.getItem('shop-id'))
}
this.listOrder();
this.userService.getUserByToken(this.token).subscribe((userInfo) => {
this.loggedRole = userInfo.userRole;
if (this.loggedRole != 'ROLE_ADMIN') {
this.isShop = true;
this.shopId = userInfo.shopId
}
this.listOrder();
})
}
listOrder() {
@@ -3,6 +3,7 @@ import { Routes, RouterModule } from "@angular/router";
import { DetailOrderComponent } from "./detail-order/detail-order.component";
import { OrdersComponent } from "./orders/orders.component";
import { TransactionsComponent } from "./transactions/transactions.component";
import { ScamOrdersComponent } from "./scam-orders/scam-orders.component";
const routes: Routes = [
{
@@ -16,6 +17,14 @@ const routes: Routes = [
breadcrumb: "Danh sách",
},
},
{
path: "scam-orders",
component: ScamOrdersComponent,
data: {
title: "Đơn hàng bị báo cáo",
breadcrumb: "Danh sách",
},
},
{
path: "detail-order/user/:userId/order/:id",
component: DetailOrderComponent,
+2 -1
View File
@@ -8,12 +8,13 @@ import { FormsModule } from '@angular/forms';
import { Ng2SearchPipeModule } from 'ng2-search-filter';
import { SharedModule } from 'src/app/shared/shared.module';
import { DetailOrderComponent } from './detail-order/detail-order.component';
import { ScamOrdersComponent } from './scam-orders/scam-orders.component';
@NgModule({
declarations: [OrdersComponent, TransactionsComponent, DetailOrderComponent],
declarations: [OrdersComponent, TransactionsComponent, DetailOrderComponent, ScamOrdersComponent],
imports: [
CommonModule,
SalesRoutingModule,
@@ -0,0 +1,200 @@
<!-- Container-fluid starts-->
<div class="container-fluid">
<div class="row">
<div class="col-sm-12">
<div class="card">
<!-- <div class="card-header">
<h5>Quản lý đơn hàng</h5>
</div> -->
<div class="card-body">
<div class="custom-datatable">
<div class="mb-3">
<input type="text" [(ngModel)]="searchName" (change)="searchOrder()"
class="filter-ngx form-control" placeholder="Tìm kiếm ..." autocomplete="off" />
</div>
<table class="table table-striped" *ngIf="orders.length > 0">
<thead>
<tr>
<th scope="col">Mã vận đơn</th>
<th scope="col">Thời gian</th>
<th scope="col">Khách hàng</th>
<th scope="col">Shipper</th>
<th scope="col">Địa chỉ</th>
<th scope="col">Phương thức</th>
<th scope="col">Trạng thái</th>
<th scope="col">Số tiền</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
<tr *ngFor="let order of orders">
<th scope="row">{{ order.orderTrackingNumber }}</th>
<td>{{ order.orderTime }}</td>
<td>{{ order.user.fullName }}</td>
<td *ngIf="order?.shipper?.user?.fullName != null">{{ order?.shipper?.user?.fullName
}}</td>
<td *ngIf="order?.shipper?.user?.fullName == null"><i style="color: #FF8084;"
class="fa fa-times"></i>
<span class="sr-only">Loading...</span>
</td>
<td>{{ order.address }}</td>
<td>
<span [ngClass]="{
badge: true,
'badge-info': order.paymentMethod === 'ZALO PAY',
'badge-success': order.paymentMethod === 'CASH'
}">
{{ order.paymentMethod === "CASH"
? "Tiền mặt"
: order.paymentMethod === "ZALO PAY"
? "Zalo Pay"
: ""
}}
</span>
</td>
<td>
<span [ngClass]="{
badge: true,
'badge-dark': order.status === 'AWAITING',
'badge-warning': order.status === 'CONFIRMED',
'badge-info': order.status === 'SHIPPING',
'badge-success': order.status === 'COMPLETED',
'badge-primary': order.status === 'CANCELED' || order.status === 'REJECT_DELIVERY'
}">
{{
order.status === "AWAITING"
? "Chờ xác nhận"
: order.status === "CONFIRMED"
? "Đã xác nhận"
: order.status === "SHIPPING"
? "Đang giao hàng"
: order.status === "COMPLETED"
? "Giao thành công"
: order.status === "CANCELED"
? "Đã huỷ đơn"
: order.status === "REJECT_DELIVERY"
? "Không nhận hàng"
: ""
}}
</span>
</td>
<td style="font-size: 16px;">{{ order.total | currency : "VND" }}</td>
<td scope="row">
<a [routerLink]="['/sales', 'detail-order', 'user', order.user.id, 'order', order.id]"
style="cursor: pointer;">
<i style="color: lightseagreen;" class="fa fa-eye f-12"></i>
</a>&nbsp;
<a *ngIf="order.status != 'COMPLETED'"
(click)="openStatusModal(change_status, order.user.id, order.id, order?.shipper)"
style="cursor: pointer;">
<i class="fa fa-edit f-12"></i>
</a>
<a *ngIf="order.status == 'COMPLETED'" style="cursor: not-allowed;">
<i style="color: lightcoral;" class="fa fa-edit f-12"></i>
</a>&nbsp;
<a (click)="openDeleteModal(delete_order, order.user.id, order.id)"
style="cursor: pointer;">
<i class="fa fa-trash-o"></i>
</a>
</td>
</tr>
</tbody>
</table>
<div class="d-flex justify-content-center p-2" *ngIf="orders.length > 0">
<!-- <select [(ngModel)]="sortBy" class="form-select" style="width: auto" name="pageSize"
(change)="ngOnInit()">
<option [value]="'orderTime'" [selected]="true" [ngValue]="'orderTime'">Thời gian</option>
<option [ngValue]="20">20 đơn hàng / trang</option>
<option [ngValue]="30">30 đơn hàng / trang</option>
</select> -->
<ngb-pagination [collectionSize]="theTotalElements" [(page)]="thePageNumber"
[pageSize]="thePageSize" [rotate]="true" [maxSize]="5" [boundaryLinks]="true"
(pageChange)="listOrder()">
</ngb-pagination>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<select [(ngModel)]="thePageSize" class="form-select" style="width: auto" name="pageSize"
(change)="ngOnInit()">
<option [value]="5" [selected]="true" [ngValue]="10">10 đơn hàng / trang</option>
<option [ngValue]="20">20 đơn hàng / trang</option>
<option [ngValue]="30">30 đơn hàng / trang</option>
</select>
</div>
<div class="d-flex justify-content-center p-2" *ngIf="orders.length == 0">
<img src="../../../../assets/images/error/no-order.png" alt="" srcset="">
</div>
<div class="d-flex justify-content-center p-2" *ngIf="orders.length == 0">
<h4 style="color: lightcoral">Không tìm thấy đơn hàng</h4>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Container-fluid Ends-->
</div>
<!-- /////////////////////////////////////////////////////////////////////////////////////////////// -->
<!-- Change status -->
<ng-template #change_status>
<div class="modal-change-status">
<h5 class="modal-confirm-text">Cập nhật đơn hàng</h5>
<div class="modal-select-option" *ngIf="!isHaveShipper">
<select [(ngModel)]="shipper">
<option [selected]="true" [ngValue]="undefined">Chọn shipper</option>
<option *ngFor="let shipper of shippers" [ngValue]="shipper">{{ shipper.user.fullName }}</option>
</select>
</div>
<div class="modal-select-option">
<select [(ngModel)]="selectedStatus">
<option value="AWAITING">Chờ xác nhận</option>
<option value="CONFIRMED">Đã xác nhận</option>
<option value="SHIPPING">Đang giao hàng</option>
<option value="COMPLETED">Giao thành công</option>
<option value="CANCELED">Đã huỷ đơn</option>
<option value="REJECT_DELIVERY">Không nhận hàng</option>
</select>
</div>
<div class="modal-btn-option">
<button type="button" class="btn btn-default width-btn"
(click)="confirmBoxChangeStatus(change_status_success)">Đổi</button>
<button type="button" class="btn btn-primary width-btn" (click)="decline()">Huỷ</button>
</div>
</div>
</ng-template>
<!--Change status success -->
<ng-template #change_status_success>
<div class="modal-body text-center">
<h5 class="modal-confirm-text">Chỉnh sửa đơn hàng thành công</h5>
<button type="button" class="btn btn-primary" (click)="successChangeStatus()">Tiếp tục</button>
</div>
</ng-template>
<!-- /////////////////////////////////////////////////////////////////////////////////////////////// -->
<!-- Confirm delete -->
<ng-template #delete_order>
<div class=" modal-confirm-delete">
<h5 class="modal-confirm-text">Bạn chắc chắc xoá đơn hàng này chứ ?</h5>
<div class="modal-btn-option">
<button type="button" class="btn btn-default width-btn"
(click)="confirmBoxDelete(userId, orderId, delete_order_success)">Xoá</button>
<button type="button" class="btn btn-primary width-btn" (click)="decline()">Huỷ</button>
</div>
</div>
</ng-template>
<!--Delete success -->
<ng-template #delete_order_success>
<div class="modal-body text-center">
<h5 class="modal-confirm-text">Xoá đơn hàng thành công</h5>
<button type="button" class="btn btn-primary" (click)="successDelete()">Tiếp tục</button>
</div>
</ng-template>
@@ -0,0 +1,23 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { ScamOrdersComponent } from './scam-orders.component';
describe('ScamOrdersComponent', () => {
let component: ScamOrdersComponent;
let fixture: ComponentFixture<ScamOrdersComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ ScamOrdersComponent ]
})
.compileComponents();
fixture = TestBed.createComponent(ScamOrdersComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
@@ -0,0 +1,237 @@
import { Component, TemplateRef } from '@angular/core';
import { BsModalRef, BsModalService } from 'ngx-bootstrap/modal';
import { OrderService } from 'src/app/shared/service/order.service';
import { ShipperService } from 'src/app/shared/service/shipper.service';
import { UserService } from 'src/app/shared/service/user.service';
import { Order } from 'src/app/shared/tables/order-list';
import { Shipper } from 'src/app/shared/tables/shipper';
@Component({
selector: 'app-scam-orders',
templateUrl: './scam-orders.component.html',
styleUrls: ['./scam-orders.component.scss']
})
export class ScamOrdersComponent {
//Log-in
token: string = localStorage.getItem("jwt-token");
isShop: boolean = false;
loggedRole: string;
shopId: number;
//Required properties
oldid: number = 1;
userId: number;
orderId: number;
orders: Order[] = [];
//Pagination Properties
thePageNumber = 1;
thePageSize = 10;
sortBy = "orderTime";
sortDir = "desc";
theTotalElements = 0;
order: Order;
layer1: BsModalRef;
layer2: BsModalRef;
selectedStatus: string;
isHaveShipper: boolean = false;
shipper: Shipper = undefined;
shippers: Shipper[] = [];
searchName: string = '';
//Event
refreshInterval = 5000;
refreshTimeout;
totalOrders = 0;
orderStatuses = ["Chờ xác nhận", "Đã xác nhận", "Đang giao hàng", "Giao thành công", "Đã huỷ đơn", "Không nhận hàng"];
constructor(private orderService: OrderService,
private userService: UserService,
private shipperService: ShipperService,
private modalService: BsModalService) { }
ngOnInit() {
this.userService.getUserByToken(this.token).subscribe((userInfo) => {
this.loggedRole = userInfo.userRole;
if (this.loggedRole != 'ROLE_ADMIN') {
this.isShop = true;
this.shopId = userInfo.shopId
}
this.listOrder();
})
}
listOrder() {
if (this.isShop) {
this.orderService.getOrdersByShopId(this.shopId, this.thePageNumber - 1, this.thePageSize, this.sortBy, this.sortDir)
.subscribe(this.processResult());
this.shipperService.findFreeShopShipper(this.shopId).subscribe((shippers) => {
this.shippers = shippers;
})
}
else {
this.orderService
.getOrdersPagination(this.thePageNumber - 1, this.thePageSize, this.sortBy, this.sortDir)
.subscribe(this.processResult());
}
this.refreshTimeout = setTimeout(() => {
this.refreshOrder();
}, this.refreshInterval);
}
refreshOrder() {
if (this.isShop) {
this.orderService.getOrdersByShopId(this.shopId, this.thePageNumber - 1, this.thePageSize, this.sortBy, this.sortDir)
.subscribe(this.refreshResult());
this.shipperService.findFreeShopShipper(this.shopId).subscribe((shippers) => {
this.shippers = shippers;
})
}
else {
this.orderService
.getOrdersPagination(this.thePageNumber - 1, this.thePageSize, this.sortBy, this.sortDir)
.subscribe(this.refreshResult());
}
this.refreshTimeout = setTimeout(() => {
this.refreshOrder();
}, this.refreshInterval);
}
searchOrder() {
if (this.searchName.trim() !== '') {
this.orderService.findOrdersByTrackingNumber(this.searchName, this.thePageNumber - 1, this.thePageSize, this.sortBy, this.sortDir)
.subscribe(this.processResult());
}
else {
this.listOrder()
}
}
processResult() {
return (data: any) => {
this.orders = data.orders;
this.thePageNumber = data.page.pageNo + 1;
this.thePageSize = data.page.pageSize;
this.theTotalElements = data.page.totalElements;
this.totalOrders = data.page.totalElements;
};
}
refreshResult() {
return (data: any) => {
this.orders = data.orders;
this.thePageNumber = data.page.pageNo + 1;
this.thePageSize = data.page.pageSize;
this.theTotalElements = data.page.totalElements;
if (this.totalOrders != this.theTotalElements) {
this.totalOrders = this.theTotalElements;
}
};
}
// Change status order modal
openStatusModal(confirmBoxChangeStatus: TemplateRef<any>, userId: number, orderId: number, shipper: Shipper) {
this.isHaveShipper = false;
if (shipper != undefined) {
this.isHaveShipper = true
}
this.orderService.getOrderById(userId, orderId).subscribe(
(order: Order) => {
this.userId = userId;
this.orderId = orderId;
this.selectedStatus = order.status;
this.layer1 = this.modalService.show(confirmBoxChangeStatus, { class: "modal-sm" });
},
(error) => {
console.error(error); // handle error
}
);
}
confirmBoxChangeStatus(successChangeStatus: TemplateRef<any>) {
if (this.shipper) {
this.isHaveShipper = true;
}
// console.log(this.isHaveShipper)
if (this.isHaveShipper) {
this.orderService.updateOrderShipper(this.userId, this.orderId, this.shipper.id).subscribe(() => {
this.orderService.updateOrderStatus(this.userId, this.orderId, this.selectedStatus).subscribe((res) => { });
this.layer1.hide();
this.layer1 = this.modalService.show(successChangeStatus, { class: "modal-sm" });
})
}
else {
this.orderService.updateOrderStatus(this.userId, this.orderId, this.selectedStatus).subscribe((res) => { });
this.layer1.hide();
this.layer1 = this.modalService.show(successChangeStatus, { class: "modal-sm" });
}
// if (!this.isHaveShipper) {
// if (this.shipper != undefined) {
// this.orderService.updateOrderStatus(this.userId, this.orderId, this.selectedStatus).subscribe((res) => { });
// this.layer1.hide();
// this.layer1 = this.modalService.show(successChangeStatus, { class: "modal-sm" });
// }
// else {
// this.orderService.updateOrderShipper(this.userId, this.orderId, this.shipper.id).subscribe(() => {
// this.orderService.updateOrderStatus(this.userId, this.orderId, this.selectedStatus).subscribe((res) => { });
// this.layer1.hide();
// this.layer1 = this.modalService.show(successChangeStatus, { class: "modal-sm" });
// });
// }
// }
// else {
// this.orderService.updateOrderStatus(this.userId, this.orderId, this.selectedStatus).subscribe((res) => { });
// this.layer1.hide();
// this.layer1 = this.modalService.show(successChangeStatus, { class: "modal-sm" });
// }
}
decline() {
this.shipper = undefined;
this.layer1.hide();
}
successChangeStatus() {
this.listOrder();
this.layer1.hide();
}
// Delete order modal
openDeleteModal(confirmBoxDelete: TemplateRef<any>, userId: number, orderId: number) {
this.userId = userId
this.orderId = orderId
this.layer1 = this.modalService.show(confirmBoxDelete, { class: "modal-sm" });
}
confirmBoxDelete(userId: number, orderId: number, successDelete: TemplateRef<any>) {
this.orderService.deleteOrderById(this.userId, this.orderId).subscribe(() => {
this.listOrder()
})
this.layer1.hide()
this.layer1 = this.modalService.show(successDelete, { class: "modal-sm" });
}
successDelete() {
this.listOrder();
this.layer1.hide();
}
ngOnDestroy() {
// Xóa timeout khi component bị destroy
clearTimeout(this.refreshTimeout);
}
}
@@ -1,4 +1,5 @@
import { Component, OnInit } from '@angular/core';
import { userInfo } from 'os';
import { UserService } from 'src/app/shared/service/user.service';
import { User } from 'src/app/shared/tables/user';
@@ -9,7 +10,7 @@ import { User } from 'src/app/shared/tables/user';
})
export class ProfileComponent implements OnInit {
public active = 1;
loggedId: number = Number(localStorage.getItem('user-id'))
token: string = localStorage.getItem("jwt-token");
user: User;
constructor(
@@ -17,8 +18,10 @@ export class ProfileComponent implements OnInit {
) { }
ngOnInit() {
this.userService.getUserById(this.loggedId).subscribe((user) => {
this.user = user;
this.userService.getUserByToken(this.token).subscribe(userInfo => {
this.userService.getUserById(userInfo.userId).subscribe((user) => {
this.user = user;
})
})
}
@@ -5,6 +5,7 @@ import { Router } from '@angular/router';
import { rejects } from 'assert';
import { url } from 'inspector';
import { BsModalRef, BsModalService } from 'ngx-bootstrap/modal';
import { userInfo } from 'os';
import { resolve } from 'path';
import { finalize, mergeMap, Observable, of } from 'rxjs';
import { switchMap } from 'rxjs-compat/operator/switchMap';
@@ -28,9 +29,8 @@ export class CreateShipperComponent implements OnInit {
public active = 1;
//Log-in
token: string = localStorage.getItem("jwt-token");
isShop: boolean = false;
loggedId: number = Number(localStorage.getItem('user-id'))
loggedRole = localStorage.getItem('user-role');
shopId: number;
imageFile: File;
@@ -57,8 +57,6 @@ export class CreateShipperComponent implements OnInit {
this.createPermissionForm();
}
createPermissionForm() {
this.permissionForm = this.formBuilder.group({});
}
@@ -84,13 +82,15 @@ export class CreateShipperComponent implements OnInit {
}
);
if (this.loggedRole != 'ROLE_ADMIN') {
this.isShop = true;
this.shopId = Number(localStorage.getItem('shop-id'))
this.accountForm.patchValue({
shopId: this.shopId
})
}
this.userService.getUserByToken(this.token).subscribe((userInfo) => {
if (userInfo.userRole != 'ROLE_ADMIN') {
this.isShop = true;
this.shopId = userInfo.shopId;
this.accountForm.patchValue({
shopId: this.shopId
})
}
})
}
// Validation for password and confirm password
@@ -1,8 +1,10 @@
import { Component, OnInit, TemplateRef } from '@angular/core';
import { Router } from '@angular/router';
import { BsModalRef, BsModalService } from 'ngx-bootstrap/modal';
import { userInfo } from 'os';
import { FirebaseService } from 'src/app/shared/service/firebase.service';
import { ShipperService } from 'src/app/shared/service/shipper.service';
import { UserService } from 'src/app/shared/service/user.service';
import { Shipper } from 'src/app/shared/tables/shipper';
@Component({
@@ -12,9 +14,9 @@ import { Shipper } from 'src/app/shared/tables/shipper';
})
export class ListShipperComponent {
//Log-in properties
token: string = localStorage.getItem("jwt-token");
isShop: boolean = false;
loggedId: number = Number(localStorage.getItem('user-id'))
loggedRole = localStorage.getItem('user-role');
loggedRole: string;
shopId: number;
searchName: string = '';
@@ -33,17 +35,21 @@ export class ListShipperComponent {
email: string;
constructor(private shipperService: ShipperService,
private userService: UserService,
private modalService: BsModalService,
private router: Router,
private firebaseService: FirebaseService) {
}
ngOnInit() {
if (this.loggedRole != 'ROLE_ADMIN') {
this.isShop = true;
this.shopId = Number(localStorage.getItem('shop-id'))
}
this.listAllShipper();
this.userService.getUserByToken(this.token).subscribe((userInfo) => {
this.loggedRole = userInfo.userRole;
if (this.loggedRole != 'ROLE_ADMIN') {
this.isShop = true;
this.shopId = userInfo.shopId;
}
this.listAllShipper();
})
}
listAllShipper() {
+13 -8
View File
@@ -61,8 +61,10 @@
<label for="validationCustom2"><span>*</span> Email</label>
</div>
<div class="col-xl-8 col-md-7">
<input formControlName="email" class="form-control" type="email"
placeholder="Email" />
<input *ngIf="!isShop" formControlName="email" class="form-control"
type="email" placeholder="Email" />
<input readonly *ngIf="isShop" formControlName="email" class="form-control"
type="email" placeholder="Email" />
<div *ngIf="userEmail?.invalid && (userEmail?.dirty || userEmail?.touched)"
class="alert alert-danger mt-1">
<div *ngIf="userEmail?.errors?.['required']">Vui lòng không được bỏ
@@ -85,8 +87,7 @@
<div *ngIf="userDateOfBirth?.invalid && (userDateOfBirth?.dirty || userDateOfBirth?.touched)"
class="alert alert-danger mt-1">
<div *ngIf="userDateOfBirth?.errors?.['required']">Vui lòng không được
bỏ
trống ngày sinh.</div>
bỏ trống ngày sinh.</div>
</div>
</div>
</div>
@@ -97,8 +98,10 @@
<label for="validationCustom2"><span>*</span> Số Điện Thoại</label>
</div>
<div class="col-xl-8 col-md-7">
<input formControlName="phoneNumber" class="form-control" type="tel"
placeholder="Số điện thoại" />
<input *ngIf="!isShop" formControlName="phoneNumber" class="form-control"
type="tel" placeholder="Số điện thoại" />
<input readonly *ngIf="isShop" formControlName="phoneNumber"
class="form-control" type="tel" placeholder="Số điện thoại" />
<div *ngIf="userPhoneNumber?.invalid && (userPhoneNumber?.dirty || userPhoneNumber?.touched)"
class="alert alert-danger mt-1">
<div *ngIf="userPhoneNumber?.errors?.['required']">Vui lòng không được
@@ -117,8 +120,10 @@
<label for="validationCustom2"><span>*</span> CMND/CCCD</label>
</div>
<div class="col-xl-8 col-md-7">
<input formControlName="identifiedCode" class="form-control" type="number"
placeholder="Số CMND/CCCD" />
<input *ngIf="!isShop" formControlName="identifiedCode" class="form-control"
type="number" placeholder="Số CMND/CCCD" />
<input readonly *ngIf="isShop" formControlName="identifiedCode"
class="form-control" type="number" placeholder="Số CMND/CCCD" />
<div *ngIf="userIdentifiedCode?.invalid && (userIdentifiedCode?.dirty || userIdentifiedCode?.touched)"
class="alert alert-danger mt-1">
<div *ngIf="userIdentifiedCode?.errors?.['required']">Vui lòng không
+9 -2
View File
@@ -21,7 +21,8 @@ import { Ward } from 'src/app/shared/tables/ward';
styleUrls: ['./edit-vendor.component.scss']
})
export class EditVendorComponent implements OnInit {
roleName = localStorage.getItem('user-role');
token: string = localStorage.getItem("jwt-token");
roleName: string;
//ids
userId: number;
@@ -55,6 +56,7 @@ export class EditVendorComponent implements OnInit {
wards: Ward[] = [];
//Shop
isShop: boolean = false;
isStudent: boolean = true;
isEnabled: boolean = true;
userImg: string;
@@ -86,8 +88,13 @@ export class EditVendorComponent implements OnInit {
}
ngOnInit() {
this.userService.getUserByToken(this.token).subscribe(userInfo => {
this.roleName = userInfo.userRole;
if (userInfo.userRole != "ROLE_ADMIN") {
this.isShop = true;
}
})
const shopId = +this.route.snapshot.paramMap.get("id")!;
console.log(shopId);
this.getAllDistrict().then(() => {
this.shopService.getShopById(shopId).subscribe((data => this.fillFormToUpdate(data)))
}).catch(error => { });
@@ -2,6 +2,7 @@ import { Component, OnInit, TemplateRef, ViewChild } from '@angular/core';
import { OrderService } from '../../service/order.service';
import { BsModalRef, BsModalService } from 'ngx-bootstrap/modal';
import { Router } from '@angular/router';
import { UserService } from '../../service/user.service';
@Component({
selector: 'app-footer',
@@ -10,8 +11,8 @@ import { Router } from '@angular/router';
})
export class FooterComponent implements OnInit {
//Log-in
loggedId: number = Number(localStorage.getItem('user-id'))
loggedRole = localStorage.getItem('user-role');
token = localStorage.getItem('jwt-token')
loggedRole: string;
shopId: number;
//Pagination Properties
@@ -31,15 +32,18 @@ export class FooterComponent implements OnInit {
@ViewChild('new_order') newOrderTemplate: TemplateRef<any>;
constructor(
private userService: UserService,
private orderService: OrderService,
private modalService: BsModalService,
private router: Router) { }
ngOnInit() {
if (this.loggedRole == 'ROLE_SHOP') {
this.shopId = Number(localStorage.getItem('shop-id'))
this.countShopOrder();
}
this.userService.getUserByToken(this.token).subscribe((userInfo) => {
if (userInfo.userRole == 'ROLE_SHOP') {
this.shopId = userInfo.shopId;
this.countShopOrder();
}
})
}
countShopOrder() {
@@ -18,9 +18,10 @@ export class HeaderComponent implements OnInit {
public user: User;
//Log-in
token: string = localStorage.getItem("jwt-token");
isShop: boolean = false;
loggedId: number = Number(localStorage.getItem('user-id'))
loggedRole = localStorage.getItem('user-role');
loggedId: number;
loggedRole: string;
shopId: number;
@Output() rightSidebarEvent = new EventEmitter<boolean>();
@@ -29,9 +30,7 @@ export class HeaderComponent implements OnInit {
public navServices: NavService,
private userService: UserService,
private firebaseService: FirebaseService) {
this.userService.getUserById(Number(localStorage.getItem('user-id'))).subscribe((user) => {
this.user = user;
})
}
collapseSidebar() {
@@ -49,10 +48,18 @@ export class HeaderComponent implements OnInit {
ngOnInit() {
if (this.loggedRole != 'ROLE_ADMIN') {
this.isShop = true;
this.shopId = Number(localStorage.getItem('shop-id'))
}
this.userService.getUserByToken(this.token).subscribe((userInfo) => {
this.loggedId = userInfo.userId;
this.loggedRole = userInfo.userRole;
if (this.loggedRole != 'ROLE_ADMIN') {
this.isShop = true;
this.shopId = userInfo.shopId;
}
this.userService.getUserById(userInfo.userId).subscribe((user) => {
this.user = user;
})
})
}
logOut() {
@@ -15,34 +15,65 @@ export class SidebarComponent {
public menuItems: Menu[];
public url: any;
public fileurl: any;
token = localStorage.getItem('jwt-token')
user: User;
constructor(private router: Router, public navServices: NavService, private userService: UserService) {
this.userService.getUserById(Number(localStorage.getItem('user-id'))).subscribe((user) => {
this.user = user;
this.userService.getUserByToken(this.token).subscribe((userInfo) => {
this.userService.getUserById(userInfo.userId).subscribe((user) => {
this.user = user;
})
if (userInfo.userRole == 'ROLE_ADMIN') {
this.navServices.adminItems.subscribe(menuItems => {
this.menuItems = menuItems
this.router.events.subscribe((event) => {
if (event instanceof NavigationEnd) {
menuItems.filter(items => {
if (items.path === event.url)
this.setNavActive(items)
if (!items.children) return false
items.children.filter(subItems => {
if (subItems.path === event.url)
this.setNavActive(subItems)
if (!subItems.children) return false
subItems.children.filter(subSubItems => {
if (subSubItems.path === event.url)
this.setNavActive(subSubItems)
})
})
})
}
})
})
}
else {
this.navServices.shopItems.subscribe(menuItems => {
this.menuItems = menuItems
this.router.events.subscribe((event) => {
if (event instanceof NavigationEnd) {
menuItems.filter(items => {
if (items.path === event.url)
this.setNavActive(items)
if (!items.children) return false
items.children.filter(subItems => {
if (subItems.path === event.url)
this.setNavActive(subItems)
if (!subItems.children) return false
subItems.children.filter(subSubItems => {
if (subSubItems.path === event.url)
this.setNavActive(subSubItems)
})
})
})
}
})
})
}
})
this.navServices.items.subscribe(menuItems => {
this.menuItems = menuItems
this.router.events.subscribe((event) => {
if (event instanceof NavigationEnd) {
menuItems.filter(items => {
if (items.path === event.url)
this.setNavActive(items)
if (!items.children) return false
items.children.filter(subItems => {
if (subItems.path === event.url)
this.setNavActive(subItems)
if (!subItems.children) return false
subItems.children.filter(subSubItems => {
if (subSubItems.path === event.url)
this.setNavActive(subSubItems)
})
})
})
}
})
})
}
// Active Nave state
+10 -2
View File
@@ -1,19 +1,27 @@
import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { FirebaseService } from '../service/firebase.service';
import { UserService } from '../service/user.service';
@Injectable({
providedIn: 'root'
})
export class AdminGuard implements CanActivate {
token: string = localStorage.getItem('jwt-token');
role: string;
constructor(
private firebaseService: FirebaseService,
private userService: UserService,
private router: Router
) { }
) {
this.userService.getUserByToken(this.token).subscribe((userInfo) => {
this.role = userInfo.userRole;
})
}
canActivate(): boolean {
if (this.firebaseService.isAdmin()) {
if (this.role == 'ROLE_ADMIN') {
return true;
}
else {
+9 -12
View File
@@ -10,6 +10,7 @@ import { environment } from 'src/environments/environment';
import { StringBoolObject } from '../tables/string-bool-object';
import { Observable } from 'rxjs';
import { BsModalRef, BsModalService } from 'ngx-bootstrap/modal';
import { UserInfo } from '../tables/user';
@Injectable({
providedIn: 'root'
@@ -58,21 +59,14 @@ export class FirebaseService {
this.userService.getUserByEmailOrPhoneNumber(email).subscribe((user) => {
if (user.role.roleName == 'ROLE_ADMIN') {
this.loggedIn = true;
localStorage.setItem('user-role', user.role.roleName);
localStorage.setItem('email', user.email);
localStorage.setItem('user-id', user.id.toString());
localStorage.setItem('is-logged', JSON.stringify(this.loggedIn));
this.router.navigate(['/dashboard/default']);
resolve(true); // trả về true nếu đăng nhập thành công
} else if (user.role.roleName == 'ROLE_SHOP') {
localStorage.setItem('user-role', user.role.roleName);
localStorage.setItem('user-email', user.email);
localStorage.setItem('user-id', user.id.toString());
this.shopService.getShopByUserId(user.id).subscribe((shop) => {
if (shop.isEnabled) {
this.loggedIn = true;
localStorage.setItem('is-logged', JSON.stringify(this.loggedIn))
localStorage.setItem('shop-id', shop.id.toString());
this.router.navigate(['/dashboard/default']);
resolve(true); // trả về true nếu đăng nhập thành công
} else {
@@ -125,11 +119,14 @@ export class FirebaseService {
}
}
isAdmin() {
const role = localStorage.getItem('user-role');
if (role == 'ROLE_ADMIN') {
return true;
}
isAdmin(): boolean {
this.userService.getUserByToken(localStorage.getItem("jwt-token")).subscribe((userInfo) => {
const role = userInfo.userRole;
if (role == 'ROLE_ADMIN') {
return true;
}
return false;
})
return false;
}
+18 -15
View File
@@ -1,6 +1,7 @@
import { HostListener, Inject, Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
import { WINDOW } from "./windows.service";
import { UserService } from './user.service';
// Menu
export interface Menu {
@@ -23,10 +24,13 @@ export class NavService {
public screenWidth: any
public collapseSidebar: boolean = false
public roleName: string = localStorage.getItem('user-role');
public items: BehaviorSubject<Menu[]>;
public token = localStorage.getItem('jwt-token');
public roleName: string;
public adminItems: BehaviorSubject<Menu[]>;
public shopItems: BehaviorSubject<Menu[]>;
constructor(@Inject(WINDOW) private window) {
constructor(@Inject(WINDOW) private window,
private userService: UserService) {
this.onResize();
if (this.screenWidth < 991) {
this.collapseSidebar = true
@@ -35,12 +39,8 @@ export class NavService {
}
private updateMenuItems() {
if (this.roleName == 'ROLE_ADMIN') {
this.items = new BehaviorSubject<Menu[]>(this.MENUITEMS);
}
else {
this.items = new BehaviorSubject<Menu[]>(this.SHOP_ITEMS);
}
this.adminItems = new BehaviorSubject<Menu[]>(this.MENUITEMS);
this.shopItems = new BehaviorSubject<Menu[]>(this.SHOP_ITEMS);
}
// Windows width
@@ -88,6 +88,7 @@ export class NavService {
{
title: 'Đơn hàng', icon: 'dollar-sign', type: 'sub', active: false, children: [
{ path: '/sales/orders', title: 'Danh sách', type: 'link' },
{ path: '/sales/scam-orders', title: 'Bị báo cáo', type: 'link' }
// { path: '/sales/transactions', title: 'Giao dịch', type: 'link' },
]
},
@@ -168,6 +169,13 @@ export class NavService {
badgeType: 'primary',
active: false
},
{
title: 'Đơn hàng', path: '/sales/orders', icon: 'dollar-sign', type: 'link', active: false,
// children: [
// // { path: '/sales/orders', title: 'Danh sách', type: 'link' },
// // { path: '/sales/transactions', title: 'Giao dịch', type: 'link' },
// ]
},
{
title: 'Sản phẩm', icon: 'box', type: 'sub', active: false, children: [
{ path: '/products/add-product', title: 'Thêm sản phẩm', type: 'link' },
@@ -194,12 +202,7 @@ export class NavService {
// {path: '/products/digital/digital-add-product', title: 'Add Product', type: 'link'},
// ]
// },
{
title: 'Đơn hàng', icon: 'dollar-sign', type: 'sub', active: false, children: [
{ path: '/sales/orders', title: 'Danh sách', type: 'link' },
{ path: '/sales/transactions', title: 'Giao dịch', type: 'link' },
]
},
// {
// title: 'Coupons', icon: 'tag', type: 'sub', active: false, children: [
// {path: '/coupons/list-coupons', title: 'List Coupons', type: 'link'},
+16 -1
View File
@@ -4,7 +4,8 @@ import { Observable } from 'rxjs-compat';
import { environment } from 'src/environments/environment';
import { Address } from '../tables/address';
import { StringBoolObject } from '../tables/string-bool-object';
import { User } from '../tables/user';
import { User, UserInfo } from '../tables/user';
import { userInfo } from 'os';
@Injectable({
providedIn: 'root'
@@ -84,4 +85,18 @@ export class UserService {
return this.httpClient.get<number>(this.baseUrl + `/count?day=${day}`);
}
//Get User By Token
getUserByToken(token: string) {
return this.httpClient.get<UserInfo>(this.baseUrl + `/info?token=${token}`);
}
//User Info
getUserInfo(): UserInfo {
const token = localStorage.getItem("jwt-token");
this.httpClient.get<UserInfo>(this.baseUrl + `/info?token=${token}`).subscribe((userInfo) => {
console.log(userInfo)
return userInfo;
})
return null;
}
}
+7
View File
@@ -16,4 +16,11 @@ export class User {
//Response
addresses: Address[]
role: Role;
}
export class UserInfo {
userId: number;
shopId: number;
userRole: string;
userEmail: string;
}