import { Component, Injector, ViewChild, ViewEncapsulation, LOCALE_ID, Inject, ɵDEFAULT_LOCALE_ID, ViewChildren, QueryList, Output, EventEmitter, Input } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { appModuleAnimation } from '@shared/animations/routerTransition'; import { AppComponentBase } from '@shared/common/app-component-base'; import { OrderServiceProxy, OrderListDto,GetLabelInput,GetLabels,LocationServiceProxy,CancelOrderInputDto, LocationListDto, OrderTypesServiceProxy, RoleListDto, GetOrderListDtoNew, NameValueDto, GetCreatorUsers, GetOrderInput, RecurringOrderSchedulesServiceProxy, UpdateRecurringScheduleIdInput, DriversServiceProxy, GetDriverList } from '@shared/service-proxies/service-proxies'; import { LazyLoadEvent } from 'primeng/components/common/lazyloadevent'; import { Paginator } from 'primeng/components/paginator/paginator'; import { Table } from 'primeng/components/table/table'; import { finalize } from 'rxjs/operators'; import * as moment from 'moment'; import { CreateOrderModalComponent } from './create-order-modal.component'; import { PrimengTableHelper } from '@shared/helpers/PrimengTableHelper'; import { FileDownloadService } from '@shared/utils/file-download.service'; import { HttpClient } from '@angular/common/http'; import { AppConsts } from '@shared/AppConsts'; import { FileUpload } from 'primeng/fileupload'; import * as signalR from '@aspnet/signalr'; import { ImportOrderTrackingComponent } from './import-order-tracking.component'; import { LocalizationService } from 'abp-ng2-module/dist/src/localization/localization.service'; import { EntityTypeHistoryModalComponent } from '@app/shared/common/entityHistory/entity-type-history-modal.component'; import * as _ from 'lodash'; import { MovePendingOrder } from '@app/sprintship/controller/route-detail/move-order-modal.component'; import { HeaderNotificationsComponent } from '@app/shared/layout/notifications/header-notifications.component'; import { ProgressBarService } from '@app/shared/layout/progressbar/progressbar.service'; import { interval } from 'rxjs'; import { CreateNewRouteModalComponent } from '@app/sprintship/controller/routes/create-route-modal.component'; import { CommonLookupModalComponent } from '@app/shared/common/lookup/common-lookup-modal.component'; @Component({ templateUrl: './order.component.html', encapsulation: ViewEncapsulation.None, animations: [appModuleAnimation()], styleUrls: ['./order.component.less'], selector: 'order-component', }) export class OrderComponent extends AppComponentBase { @Input() IsIntegration: boolean; @ViewChild("recurringList", { static: true }) recurringList: CommonLookupModalComponent; @ViewChild('movePendingOrder', { static: false }) movePendingOrder: MovePendingOrder; @ViewChild('dataTable', {static: true}) dataTable: Table; @ViewChild('paginator', {static: true}) paginator: Paginator; @ViewChild('createOrderModal', {static: false}) createOrderModal: CreateOrderModalComponent; @ViewChild('ExcelFileUpload', { static: true }) excelFileUpload: FileUpload; @ViewChild('importOrderTracking', {static: false}) importOrderTracking: ImportOrderTrackingComponent; @ViewChild('entityTypeHistoryModal', { static: true }) entityTypeHistoryModal: EntityTypeHistoryModalComponent; @ViewChild('routeList', { static: true }) routeList: CreateNewRouteModalComponent; @Output() passOrderIds: EventEmitter = new EventEmitter(); @Output() passOrderIdsForRoute: EventEmitter = new EventEmitter(); _entityTypeFullName = 'SprintTek.Shipping.Orders.Order'; entityHistoryEnabled = false; //Filters filterText = undefined; locationFilter: LocationListDto = new LocationListDto(); filterDate: moment.Moment; filterRouteDate: any; filterDateString: any; maxResultCount = 1000; filteredOrder: any; filteredLocation: any; filteredOrderTypes: any; advancedFiltersAreShown: false; TimeCreated: any; RouteDate: any; deliveryEta: any; orderId: string; locationId: number; orderTypeId: number; isActiveFilter = -1; uploadUrl: string; orderNumberFilter: string; trackingIdFilter: string; fullNameFilter: string; firstNameFilter: string lastNameFilter: string addressLine1Filter: string; cityFilter: string; stateFilter: string; postalCodeFilter: string; ZoneFilter: string; orderImporting: boolean = false; featurefbx: boolean = false; _ukLocale: boolean; _isLab: boolean; private hubConnection: signalR.HubConnection; unassigned: boolean; // sprintIds: Array<{}> = new Array(); sprintIds: any[]; sprintIdsList: any[]; trackingIds: Array<{}> = new Array(); getLabels: GetLabels = new GetLabels(); trackingIdsList: any[]; checkAll: boolean; records: any; creatorId: number = null; creatorUserIds: any; excludUserIds: any; orderusers: GetCreatorUsers[]; recurringId : any recurringName: string recurringOrderId: any allRecurringOrderSchedules: any allZones : any users: GetDriverList[] = [] constructor( injector: Injector, private router: Router, private _orderAppService: OrderServiceProxy, private _locationAppService: LocationServiceProxy, private _fileDownloadService: FileDownloadService, private _orderTypeService: OrderTypesServiceProxy, private _httpClient: HttpClient, private _localization: LocalizationService, private _progressBar: ProgressBarService, private _driverService: DriversServiceProxy, private _recurringOrderAppService : RecurringOrderSchedulesServiceProxy ) { super(injector); this.uploadUrl = AppConsts.remoteServiceBaseUrl + '/Import/ImportFromExcel'; this.orderImporting = abp.features.isEnabled('App.OrderImporting'); this.featurefbx = abp.features.isEnabled('App.FBXFeature'); } ngOnInit(){ let that= this this.setIsEntityHistoryEnabled(); $('.kt-select2').select2({ }); this._isLab = abp.features.isEnabled('App.RouteDetails'); this._ukLocale = abp.features.isEnabled('App.DateFormatFeature.UKLocale'); this.filterLocation(); // this.filterOrder(); this.backgroundProcessListener(); this.getOrderUsers(); setTimeout(function(){ $('.kt-select2').select2(); }, 100); this.getAllRecurringOrderSchedules(); if(!this._isLab){ this.getAllDrivers(); } this.recurringList.configure({ title: this.l("Set Recurring"), dataSource: ( skipCount: number, maxResultCount: number, filter: string ) => { return this._recurringOrderAppService.getAllForModal(undefined,undefined,filter,undefined,undefined,undefined,undefined,undefined,undefined,undefined,skipCount,maxResultCount); }, }); $('#locationSelectInput').on('change', function () { that.allZones = [] that.spinnerService.show() let locationIdFilter : any if($('#locationSelectInput :selected').val() != 0 ){ locationIdFilter = $('#locationSelectInput :selected').val() that._orderAppService.getLocationsZones(locationIdFilter) .subscribe(result=>{ that.allZones = result that.spinnerService.hide() }), (error=> that.spinnerService.hide() ) }else{ that.spinnerService.hide() } }); } getAllDrivers(){ this._driverService.getDriverList().subscribe((result) => { this.users = result; }); } selectRecurring(item: NameValueDto): void { this.recurringId = parseInt(item.value); this.recurringName = item.name; this.spinnerService.show() let input = new UpdateRecurringScheduleIdInput(); let numberList : any[] = [this.recurringOrderId] if(this.sprintIds.length == 0){ input.orderIds= numberList input.recurringOrderScheduleId = this.recurringId } else{ input.orderIds = this.sprintIds input.recurringOrderScheduleId = this.recurringId } this._recurringOrderAppService.updateRecurringId(input).subscribe(() => { this.spinnerService.hide() this.reloadPage(); this.notify.success(this.l('SavedSuccessfully')); }); } showRecurring(orderId? : number){ if(orderId != undefined){ this.recurringOrderId = orderId } this.recurringList.show() } removeRecurring(orderId? : number){ this.message.confirm( this.l(''), '', (isConfirmed) => { if (isConfirmed) { let numberList : any[] = [orderId] if(this.sprintIds.length == 0){ numberList = [orderId] } else{ numberList = this.sprintIds // input.recurringOrderScheduleId = this.recurringId } this._recurringOrderAppService.removeRecurringId(numberList) .subscribe(() => { this.reloadPage(); this.notify.success(this.l('SavedSuccessfully')); }); } } ); } getAllRecurringOrderSchedules(){ this._recurringOrderAppService.getAllForModal(undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, 1000) .subscribe(result => { this.allRecurringOrderSchedules = result.items }); } private setIsEntityHistoryEnabled(): void { let customSettings = (abp as any).custom; this.entityHistoryEnabled = customSettings.EntityHistory && customSettings.EntityHistory.isEnabled && _.filter(customSettings.EntityHistory.enabledEntities, entityType => entityType === this._entityTypeFullName).length === 1; } showHistory(role: GetOrderListDtoNew): void { this.entityTypeHistoryModal.show({ entityId: role.id.toString(), entityTypeFullName: this._entityTypeFullName, entityTypeDescription: "Order - " +role.id.toString() }); } getOrders(event?: LazyLoadEvent) { $('#checkAll').prop('checked',false); this.sprintIds = []; // this.orderId = Number((document.getElementById('OrderId')).value) ? Number((document.getElementById('OrderId')).value) : undefined; this.locationId = Number((document.getElementById('locationSelectInput')).value) ? Number((document.getElementById('locationSelectInput')).value) : undefined; this.orderTypeId = Number((document.getElementById('orderType')).value) ? Number((document.getElementById('orderType')).value) : undefined; // this.creatorId = !this._isLab? undefined // : Number((document.getElementById('CreatedInput')).value) // ? Number((document.getElementById('CreatedInput')).value) // : undefined; if (this.primengTableHelper.shouldResetPaging(event)) { this.paginator.changePage(0); return; } this.spinnerService.show(); if (this.TimeCreated!=undefined){ this.filterDate = moment(this.TimeCreated); } if (this.TimeCreated!=undefined){ this.filterDateString = new Date(this.TimeCreated).toLocaleDateString('en-US'); } if (this.RouteDate!=undefined){ this.filterRouteDate = new Date(this.RouteDate).toLocaleDateString('en-US'); } this.creatorUserIds = $("#createdSelect").val()=='null'? [] : $("#createdSelect").val(); this.excludUserIds = $("#ExcludeInput").val()=='null'? [] : $("#ExcludeInput").val(); let x = new GetOrderInput(); x.id = undefined; x.filter = this.filterText; x.pickupDetailsId = undefined; x.deliveryDetailsId = undefined; x.locationId = this.locationId; x.noteId = undefined; x.creationTime = this.filterDate; x.sortOrder = undefined; x.orderTypeId = this.orderTypeId; x.orderId = this.orderId; x.customerOrderNumberFilter = this.orderNumberFilter; x.trackingIdFilter = this.trackingIdFilter; x.unassigned = this.unassigned; x.routeDate = this.filterRouteDate; x.creationTimeString = this.filterDateString; x.creator = this.creatorId; x.fullNameFilter = this.fullNameFilter; x.addressLine1Filter = this.addressLine1Filter; x.cityFilter = this.cityFilter; x.stateFilter = this.stateFilter; x.postalCodeFilter = this.postalCodeFilter; x.firstNameFilter = this.firstNameFilter; x.lastNameFilter = this.lastNameFilter; x.isIntegration = this.IsIntegration; x.creatorUserIds = this.creatorUserIds == undefined ? [] : this.creatorUserIds; x.excludedUserIds = this.excludUserIds == undefined ? [] : this.excludUserIds; x.sorting = this.primengTableHelper.getSorting(this.dataTable); x.maxResultCount = this.primengTableHelper.getMaxResultCount(this.paginator, event); x.skipCount = this.primengTableHelper.getSkipCount(this.paginator, event); x.zoneFilter = this.ZoneFilter; if((document.getElementById('RecurringOrderScheduleFilter')) != null){ x.recurringOrderScheduleIdFilter = Number((document.getElementById('RecurringOrderScheduleFilter')).value) ? Number((document.getElementById('RecurringOrderScheduleFilter')).value) : undefined; } if(!this._isLab){ x.multipleZoneFilter = $("#ZonesFilter").val() == 0 ? undefined : $("#ZonesFilter").val().toString().split(',').map(Number); x.multipleDriverFilter = $("#DriverFilter").val() == 0 ? undefined : $("#DriverFilter").val().toString().split(',').map(Number); } this._orderAppService.getOrders(x).subscribe(result => { //console.log(result) this.primengTableHelper.totalRecordsCount = result.totalCount; // result.items.forEach(item => { // let total = 0; // item.orderPackages.forEach(orderPackage => { // total = total + orderPackage.quantity; // }); // item.totalPackages = total; // }); for (let index = 0; index < result.items.length; index++) { if(this._ukLocale){ result.items[index].createdString = result.items[index].createDate.utcOffset(moment.parseZone(result.items[index].createDate).utcOffset()).format('D/M/YYYY h:mm a'); // result.items[index].lastModifiedString = result.items[index].lastModifiedTime.utcOffset(moment.parseZone(result.items[index].lastModifiedTime).utcOffset()).format('D/M/YYYY h:mm a'); } else{ result.items[index].createdString = result.items[index].createDate.utcOffset(moment.parseZone(result.items[index].createDate).utcOffset()).format('M/D/YYYY h:mm a'); // result.items[index].lastModifiedString = result.items[index].lastModifiedTime.utcOffset(moment.parseZone(result.items[index].lastModifiedTime).utcOffset()).format('M/D/YYYY h:mm a'); } } this.primengTableHelper.records = result.items; this.spinnerService.hide(); }); this.filterOrderTypes(); } selectOrders(event){ console.log(event) if (this.sprintIds.indexOf(event.data.id) == -1) { this.sprintIds.push(event.data.id); } else { this.sprintIds.splice(this.sprintIds.indexOf(event.data.id), 1); } // this.sprintIdsList = this.sprintIds; this.passOrderIds.emit(this.sprintIds) this.passOrderIdsForRoute.emit(this.sprintIds); if(this.trackingIds.indexOf(event.data.trackingId) == -1) { this.trackingIds.push(event.data.trackingId); $('#'+event.data.id).prop('checked',true); } else { this.trackingIds.splice(this.trackingIds.indexOf(event.data.trackingId), 1); $('#'+event.data.id).prop('checked',false); } } createOrder(): void { this.createOrderModal.show(); } reloadPage(): void { this.paginator.changePage(this.paginator.getPage()); this.sprintIds=[] } filterLocation(): void { this._locationAppService.getLocationNames( undefined, undefined, undefined, undefined, undefined, undefined ).subscribe(result => { this.filteredLocation = result; }); } filterOrderTypes(): void { if(this.IsIntegration){ this._orderTypeService.getXceleratorOrderTypes().subscribe(result => { this.filteredOrderTypes = result; }); }else{ this._orderTypeService.getOrderTypes().subscribe(result => { this.filteredOrderTypes = result; }); } } deleteOrder(order: OrderListDto): void { this.message.confirm( this.l(''), '', (isConfirmed) => { if (isConfirmed) { let input = new CancelOrderInputDto({ confirmationNumber: [order.id.toString()], specialInstructions:'Cancelled' }); this._orderAppService.cancelOrder(input) .subscribe(() => { this.reloadPage(); this.notify.success(this.l('SavedSuccessfully')); }); } } ); } createOrUpdate(url: any, id?: number){ if(id != null){ var myurl = `${url}/${id}`; }else{ var myurl = `${url}`; } this.router.navigateByUrl(myurl); } exportToExcel(event?: LazyLoadEvent): void { this.locationId = Number((document.getElementById('locationSelectInput')).value) ? Number((document.getElementById('locationSelectInput')).value) : undefined; this.orderTypeId = Number((document.getElementById('orderType')).value) ? Number((document.getElementById('orderType')).value) : undefined; // this.creatorId = !this._isLab? undefined // : Number((document.getElementById('CreatedInput')).value) // ? Number((document.getElementById('CreatedInput')).value) // : undefined; if (this.primengTableHelper.shouldResetPaging(event)) { this.paginator.changePage(0); return; } if (this.TimeCreated!=undefined){ this.filterDate = moment(this.TimeCreated); } if (this.TimeCreated!=undefined){ this.filterDateString = new Date(this.TimeCreated).toLocaleDateString('en-US'); } if (this.RouteDate!=undefined){ this.filterRouteDate = moment(this.RouteDate).format('MM-DD-YYYY'); } this.creatorUserIds = $("#createdSelect").val()=='null'? [] : $("#createdSelect").val(); this.excludUserIds = $("#ExcludeInput").val()=='null'? [] : $("#ExcludeInput").val(); this.spinnerService.show(); let x = new GetOrderInput(); x.id = undefined; x.filter = this.filterText; x.pickupDetailsId = undefined; x.deliveryDetailsId = undefined; x.locationId = this.locationId; x.noteId = undefined; x.creationTime = this.filterDate; x.sortOrder = undefined; x.orderTypeId = this.orderTypeId; x.orderId = this.orderId; x.customerOrderNumberFilter = this.orderNumberFilter; x.trackingIdFilter = this.trackingIdFilter; x.unassigned = this.unassigned; x.routeDate = this.filterRouteDate; x.creationTimeString = this.filterDateString; x.creator = this.creatorId; x.fullNameFilter = this.fullNameFilter; x.addressLine1Filter = this.addressLine1Filter; x.cityFilter = this.cityFilter; x.stateFilter = this.stateFilter; x.postalCodeFilter = this.postalCodeFilter; x.firstNameFilter = this.firstNameFilter; x.lastNameFilter = this.lastNameFilter; x.isIntegration = this.IsIntegration; x.creatorUserIds = this.creatorUserIds == undefined ? [] : this.creatorUserIds; x.excludedUserIds = this.excludUserIds == undefined ? [] : this.excludUserIds; x.sorting = this.primengTableHelper.getSorting(this.dataTable); x.maxResultCount = this.primengTableHelper.getMaxResultCount(this.paginator, event); x.skipCount = this.primengTableHelper.getSkipCount(this.paginator, event); x.zoneFilter = this.ZoneFilter; if(!this._isLab){ x.multipleZoneFilter = $("#ZonesFilter").val() == 0 ? undefined : $("#ZonesFilter").val().toString().split(',').map(Number); x.multipleDriverFilter = $("#DriverFilter").val() == 0 ? undefined : $("#DriverFilter").val().toString().split(',').map(Number); } this._orderAppService.getOrdersForExcels(x) .subscribe(result => { if(result!=undefined){ if(result.fileUrl!=undefined){ this.router.navigate([]).then(result1 => { window.open(result.fileUrl, '_blank'); }); this.spinnerService.hide(); }else{ this.spinnerService.hide(); } }else{ this.message.warn('', "No data to export"); this.spinnerService.hide(); } }); } uploadExcel(data: { files: File }): void { //this.importOrderTracking.clearMessages(); //this.importOrderTracking.modal.show(); const formData: FormData = new FormData(); const file = data.files[0]; formData.append('file', file, file.name); formData.append('key','orders'); formData.append('locale', abp.localization.currentLanguage.name); // formData.append('entity','addresses','addresses'); // console.log(abp.localization.currentLanguage.name); this._httpClient .post(this.uploadUrl, formData) .subscribe(response => { if (response.success) { this.notify.info('Import process is queued. Please wait'); //this.l('ImportOrderStart') this.toggle(true); } else if (response.error != null) { this.toggle(false); this.notify.error(this.l('ImportOrderFailed')); } }); } onUploadExcelError(): void { this.notify.error(this.l('ImportOrderFailed')); } backgroundProcessListener() { this.hubConnection = new signalR.HubConnectionBuilder() .withUrl(AppConsts.remoteServiceBaseUrl + '/import') .build(); this.hubConnection .start() .then(() => console.log('Connection started')) .catch(err => { console.log('Error while starting connection: ' + err); this.toggle(false); }); this.hubConnection.on('BackgroundMessage', (message) => { // if(message.match(/Route created/) || message.match(/Order created/)) { // this.importOrderTracking.logMessage(message, true); // } // else { if (message.match(/End Importing/)) { this.importOrderTracking.importing = false; this.toggle(false); this.notify.success('Import process is complete'); this.getOrders(); } else { this.importOrderTracking.logMessage(message); } this.sendMessage(message); // } }); } createIncidents(url: any, id?: number){ if(id != null){ var myurl = `${url}/${id}`; }else{ var myurl = `${url}`; } //window.open(myurl, "_blank") this.router.navigateByUrl(myurl); } toggle (toggle: boolean){ this._progressBar.toggleProgressBar(toggle); } sendMessage(message: string) { this._progressBar.sendMessage(message); } selectAllOrders() { this.sprintIdsList = null; this.trackingIds.splice(0, this.trackingIds.length); this.records = this.primengTableHelper.records for (var i = 0; i < this.records.length; i++) { if (this.checkAll == true) { this.sprintIds.push(this.records[i].id); this.trackingIds.push(this.records[i].trackingId) this.records[i].selected = this.checkAll; } else { this.sprintIds.splice(this.sprintIds.indexOf(this.records[i].id), 1); this.trackingIds.splice(this.trackingIds.indexOf(this.records[i].trackingId), 1) this.records[i].selected = this.checkAll; } } // console.log(this.sprintIds) } moveOrders(id: number, trackingId: string) { if (this.sprintIds.indexOf(id) == -1) { this.sprintIds.push(id); } else { this.sprintIds.splice(this.sprintIds.indexOf(id), 1); } // this.sprintIdsList = this.sprintIds; this.passOrderIds.emit(this.sprintIds) this.passOrderIdsForRoute.emit(this.sprintIds); if(this.trackingIds.indexOf(trackingId) == -1) { this.trackingIds.push(trackingId); } else { this.trackingIds.splice(this.trackingIds.indexOf(trackingId), 1); } } printLabels() { this.message.confirm( '', 'Are you sure you want to print labels?', (isConfirmed) => { if (isConfirmed) { if(this.trackingIds.length != 0) { this.spinnerService.show(); var data = new GetLabels(); //data.labels = this.trackingIds; var dataInput = []; this.trackingIds.forEach(function (value) { let a = String(value); dataInput.push(a); }); data.labels = dataInput; this._orderAppService.printlabels(data).subscribe(result => { if(result!=undefined){ if(result.fileUrl!=undefined){ this.router.navigate([]).then(result1 => { window.open(result.fileUrl, '_blank'); }); this.spinnerService.hide(); }else{ this.spinnerService.hide(); } }else{ this.message.warn('', "No data to export"); this.spinnerService.hide(); } }, error => { this.spinnerService.hide(); }); } else { this.message.warn('', "Please select order to generate label"); } } } ); } movePendingOrders(){ this.movePendingOrder.orderIds = this.sprintIds; console.log('OrdersPage'+this.sprintIds) if(this.sprintIds.length > 0 || this.sprintIds != undefined){ this.movePendingOrder.show(null, undefined, 0); } else{ this.message.error('No orders selected'); } } refresh(){ this.sprintIdsList = []; this.sprintIds = []; this.getOrders(); } getOrderUsers(){ this._orderAppService.getOrderUsers().subscribe(result => { this.orderusers = result; }); } generateLabel(trackingId){ this.message.confirm( '', 'Are you sure you want to print label?', (isConfirmed) => { if (isConfirmed) { this.spinnerService.show(); var label = new GetLabelInput(); label.trackingIdentifier = trackingId; this._orderAppService.printlabel(label).subscribe(result => { if(result!=undefined){ if(result.fileUrl!=undefined){ this.router.navigate([]).then(result1 => { window.open(result.fileUrl, '_blank'); }); this.spinnerService.hide(); }else{ this.spinnerService.hide(); } }else{ this.message.warn('', "No data to export"); this.spinnerService.hide(); } }); } } ); } }