import { Component, Injector, OnInit, ViewChild, ViewEncapsulation, Input, OnDestroy, ElementRef, Renderer, QueryList, ViewChildren, ViewContainerRef, Output, EventEmitter, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { AppConsts } from '@shared/AppConsts'; import { appModuleAnimation } from '@shared/animations/routerTransition'; import { AppComponentBase } from '@shared/common/app-component-base'; import { RouteListDto, RouteServiceProxy, ControllerRouteServiceProxy, ControllerKpiCountServiceProxy, UpdateRouteInput, UpdateCompleteRouteInput, VehicleLogServiceProxy, ShippingPackageServiceProxy, RealTimeEtaServiceProxy, GetControllerRouteStatusInputDto, UpdateLockedRouteInput, ShowBlindCountCodeInput, UpdateDepartureRouteInput, NameValueDto, VehicleInput, DriverListInput, ControllerRouteDetailServiceProxy, UpdateRouteByStopInput, ControllerRouteListDto, ControllerKpiCountListDto, GetTargetTime, UpdateRouteId, LoginUnlockByIdInputDto, DriverClientServiceProxy, LocationServiceProxy } from '@shared/service-proxies/service-proxies'; import * as moment from 'moment-timezone'; import { LazyLoadEvent } from 'primeng/components/common/lazyloadevent'; import { Paginator } from 'primeng/components/paginator/paginator'; import { Table } from 'primeng/components/table/table'; import { HttpClient } from '@angular/common/http'; import { finalize } from 'rxjs/operators'; import { Subscription } from 'rxjs'; import { ControllerRoutesService } from '@app/sprintship/controller/routes/croutes.service'; import * as _ from 'lodash'; import * as status_icon from '@app/sprintship/controller/status/status_icon.json'; import { KPIBoxComponent } from '@app/sprintship/controller/kpi-box/kpi-box.component'; import { TimerService } from '@app/sprintship/core-components/timer/timer.service'; import { RouteDetailModal } from '@app/sprintship/controller/route-detail/route-detail-modal.component'; import { MarkAsCompleteModalComponent } from '../routes/mark-as-complete-modal.component'; import { analyzeAndValidateNgModules } from '@angular/compiler'; import { CommonLookupModalComponent } from '@app/shared/common/lookup/common-lookup-modal.component'; import { DeleteRoutesComponent } from './delete-routes.component'; import { AssignTenantComponent } from '@app/sprintship/supportTicket/assign-tenant.component'; import { AssignStopModalComponent } from '@app/shared/common/lookup/assignStop-modal.component'; import { EntityTypeHistoryModalComponent } from '@app/shared/common/entityHistory/entity-type-history-modal.component'; import { RouteDetailComponent } from '../route-detail/route-detail.component'; import { FreezeModalComponent } from '@app/sprintship/controller/modals/freeze-modal.component'; import { UnfreezeModalComponent } from '@app/sprintship/controller/modals/unfreeze-modal.component'; import { result } from 'lodash'; import { date } from 'devexpress-dashboard/model/index.metadata'; import { StatusComponent } from '../status/status.component'; import { CheckBoxComponent } from '@app/sprintship/core-components/checkbox/checkbox.component'; import { TabsetComponent } from 'ngx-bootstrap'; declare var $: any; declare var jquery: any; @Component({ selector: 'dispatch-details', templateUrl: 'dispatch-details.component.html', encapsulation: ViewEncapsulation.None, styleUrls: ['./dispatch-details.component.less', './dispatch-details.general.component.less'], animations: [appModuleAnimation()], providers: [VehicleLogServiceProxy, RealTimeEtaServiceProxy], changeDetection: ChangeDetectionStrategy.OnPush, }) export class DispatchDetailsComponents extends AppComponentBase implements OnInit { @ViewChild('stopList', { static: true }) stopList: AssignStopModalComponent; @ViewChild('driversList', { static: true }) driversList: CommonLookupModalComponent; @ViewChild('dataTable', { static: true }) dataTable: Table; @ViewChild('paginator', { static: true }) paginator: Paginator; @ViewChildren('CheckBoxComponent') chkBoxList: QueryList; @ViewChildren(KPIBoxComponent) tKpiBoxComponents: KPIBoxComponent; @ViewChild(StatusComponent, { static: false }) statusDiv: StatusComponent; @ViewChild('routeDetailModal', { static: true }) routeDetailModal: RouteDetailModal; @ViewChild('markAsCompleteModalComponent', { static: true }) markAsCompleteModalComponent: MarkAsCompleteModalComponent; @ViewChild('deleteRoutes', { static: false }) deleteRoutes: DeleteRoutesComponent; @ViewChild('assignTenant', { static: false }) assignTenant: AssignTenantComponent; /**** ELEMENTS ****/ @ViewChild('dataTable', { read: ElementRef, static: true }) dTable: ElementRef; @ViewChild('entityTypeHistoryModal', { static: true }) entityTypeHistoryModal: EntityTypeHistoryModalComponent; _entityTypeFullName = 'SprintTek.Shipping.Routes.Route'; entityHistoryEnabled = false; @ViewChild('freezeModal', { static: true }) freezeModal: FreezeModalComponent; @ViewChild('unfreezeModal', { static: true }) unfreezeModal: UnfreezeModalComponent; @ViewChild('locationTab', { static: true }) staticTabs: TabsetComponent; @Input() filters: { locationFilter: number; locationIds: number[]; statusFilter: number; typeFilter: number; startDate: Date; endDate: Date; datePicked: string; filterTxt: string, routeId: string, routeName: string, vehicleName: string, driverName: string, completed: boolean, orderType: Array, osName: string, routeIds: Array, managerIds: Array, routeTypeIds: Array, isLineHaul: boolean, locationName: string } = {}; device_type: string; routeIds: any; routeIdsStops: GetControllerRouteStatusInputDto = new GetControllerRouteStatusInputDto(); attr: any; respkey: any; saving = false; completion: any; route: UpdateRouteInput = new UpdateRouteInput(); updateCompletedInput = new UpdateCompleteRouteInput(); updateDepartureRouteInput = new UpdateDepartureRouteInput(); updateLockedInput = new UpdateLockedRouteInput(); showBlindCountCodes = new ShowBlindCountCodeInput() totalMileage: number; given: number; convert: any; hours: number; etaHours: any; minutes: number; routeIdStatus: any; etaMinutes: any; routeIdsForEta: any; routeIdsToLab: any; routeIdsToClinics: any; totalGroup: number; key2: any; driverStatusDisplay: boolean; packages: Array<{ id: number, name: string, color: string }> = new Array(); containers: Array<{ id: number, name: string color: string }> = new Array(); filterFlyout: {}; filterFlyoutHolder = []; finalFilterResult = []; routeGroupDetails = []; sprintIds: Array = new Array(); sprintIdsList = []; selectAll: boolean = false; checkboxes_: boolean = false; @Input('search_string') search: string; @Input('edition') edition: string; @Input('firstload') firstload: boolean; subscription: Subscription; kpiClick: boolean; routeTypeIds: any; managerIds: any; groupGridBy: any; totalNoStatus: number; noResultFound: boolean = false; selectedRouteId: any; localRouteIds = []; routeId: number = null; routeBuilder: boolean = false; kpiRes = new ControllerKpiCountListDto(); private cBox: CheckBoxComponent; lateRouteIds: any; routeEtaList: any; etaTime: any; zoneList: any; showEmptyRoute: boolean; showCompletedRoute: boolean; lineHaulIds = []; hasChildRoutes: boolean = false; driverThreshold: any; completedRoutes: number = 0; locationTabs: any; isMultipleLocation: boolean = false; isLineHaul: boolean = false; boxLimit: number; constructor( injector: Injector, private _routeService: RouteServiceProxy, private _controllerRouteService: ControllerRouteServiceProxy, private _cRoutesService: ControllerRoutesService, private _cKpiService: ControllerKpiCountServiceProxy, private _vehicleLogsService: VehicleLogServiceProxy, private _controllerRoutePackages: ShippingPackageServiceProxy, private _timerService: TimerService, private router: Router, private renderer: Renderer, private elem: ElementRef, private _realTimeEtaService: RealTimeEtaServiceProxy, private viewContainerRef: ViewContainerRef, private _controllerRouteDetails: ControllerRouteDetailServiceProxy, private ref: ChangeDetectorRef, private _driverClientService: DriverClientServiceProxy, private _locationServiceProxy: LocationServiceProxy, private _activatedroute:ActivatedRoute ) { super(injector); setInterval(() => { this.ref.markForCheck(); }, 1000); this.kpiClick = false; } ngOnInit(): void { this.setIsEntityHistoryEnabled(); this.routeBuilder = abp.features.isEnabled('App.RouteBuilder'); this.sprintIdsList = []; localStorage.setItem('routeIds', JSON.stringify(this.sprintIdsList)); this.groupGridBy = localStorage.getItem('groupGridBy'); this.driverStatusDisplay = false; //assign driver this.driversList.configure({ title: this.l('Assign Driver'), type: 'assignDriver', dataSource: (skipCount: number, maxResultCount: number, filter: string, tenantId?: number, locationId?: number) => { let input = new DriverListInput(); input.filter = filter; input.maxResultCount = maxResultCount; input.skipCount = skipCount; input.tenantId = tenantId; input.locationId = parseInt(localStorage.getItem('operatingLocationId')); return this._controllerRouteDetails.assignDriversList(input); } }); // assign stop this.stopList.configure({ title: this.l('Select Delivery Address'), dataSource: (skipCount: number, maxResultCount: number, filter: string, tenantId?: number, locationId?: number) => { return this._controllerRouteDetails.getAllStopsList(tenantId, parseInt(localStorage.getItem('operatingLocationId')), maxResultCount, skipCount, filter); } }); this.packages = this.getParentComponent().packages; this.containers = this.getParentComponent().containers; this.showEmptyRoute = localStorage.getItem("showEmptyRoute") == null ? false : JSON.parse(localStorage.getItem("showEmptyRoute")); this.showCompletedRoute = localStorage.getItem("showCompleted") == null ? false : JSON.parse(localStorage.getItem("showCompleted")); } setFilter(value: string) { this.search = value; } isNumeric = (val: string): boolean => { return !isNaN(Number(val)); } populateTable(event?: LazyLoadEvent): void { this.spinnerService.show(); let timeId = localStorage.getItem('timeZoneId'); this.routeTypeIds = JSON.parse(localStorage.getItem('selectedRouteTypeIds')) == null ? undefined : JSON.parse(localStorage.getItem('selectedRouteTypeIds')); this.managerIds = JSON.parse(localStorage.getItem('selectedManagerIds')) == null ? undefined : JSON.parse(localStorage.getItem('selectedManagerIds')); this.showEmptyRoute = localStorage.getItem("showEmptyRoute") == null ? false : JSON.parse(localStorage.getItem("showEmptyRoute")); this.showCompletedRoute = localStorage.getItem("showCompleted") == null ? false : JSON.parse(localStorage.getItem("showCompleted")); this.driverThreshold = localStorage.getItem('THRESHOLD') == null ? undefined : this.isNumeric(localStorage.getItem('THRESHOLD')) ? parseInt(localStorage.getItem('THRESHOLD')) : undefined; var that = this; that.routeIds = []; that.lineHaulIds = []; this.filterFlyoutHolder = []; this.finalFilterResult = []; this.hasChildRoutes = false; this.completedRoutes = 0; // if(this.locationTabs!=undefined){ // this.filters.locationFilter = this.locationTabs[0].id; // } if (this.filters.locationFilter !== undefined) { if (this.primengTableHelper.shouldResetPaging(event)) { if(this.paginator!=undefined){ this.paginator.changePage(0); return; } } if (this.kpiClick == false && this.edition === 'LABORATORY') { this._cKpiService.getKPICountLab(undefined, this.filters.locationFilter, undefined, this.filters.routeId, this.filters.vehicleName, this.filters.routeName, this.filters.driverName, moment.tz(localStorage.getItem('loadDate'), timeId), moment.tz(localStorage.getItem('loadDate'), timeId).endOf('day'), this.filters.filterTxt, undefined, this.showCompletedRoute, undefined, this.filters.orderType, this.edition, this.routeTypeIds, this.managerIds, undefined, undefined, this.showEmptyRoute, undefined, localStorage.getItem('loadDate'), this.filters.isLineHaul, undefined, this.paginator==undefined ? 1000 : this.primengTableHelper.getMaxResultCount(this.paginator, event), this.paginator==undefined ? 0 : this.primengTableHelper.getSkipCount(this.paginator, event)) .subscribe(resultCount => { that._cRoutesService.setStatistics({ 'total_stops': resultCount.totalStops, 'total_callins': resultCount.totalWillCalls, 'total_routes': resultCount.totalRoutes, 'completed_stops': resultCount.totalCompletedStops, 'completed_callins': resultCount.totalCompletedWillCalls, 'total_completed_routes': resultCount.totalCompletedRoutes, 'total_unassigned_routes': resultCount.totalUnassignedRoutes, 'total_unassigned_stops': resultCount.totalUnassignedStops, 'total_not_checkin': resultCount.totalNotCheckedIn, 'total_twenty_minutes': resultCount.kpiCountLates[0].total20Minutes, 'total_thirty_minutes': resultCount.kpiCountLates[0].total30Minutes, 'unassigned_routes_ids': resultCount.unassignedRoutesIds, 'not_check_in_routes_ids': resultCount.notCheckedInRouteIds, 'completed_route_ids': resultCount.completedRouteIds, 'late20_route_ids': resultCount.kpiCountLates[0].total20MinutesList, 'late30_route_ids': resultCount.kpiCountLates[0].total30MinutesList, 'unassigned_willcall_ids': resultCount.unassignedWillCallIds, 'completed_stop_ids': resultCount.completedStopsIds, 'completed_willcalls_ids': resultCount.completedWillCallIds, 'incident': resultCount.incidentIds, 'total_unassigned_willcalls': resultCount.totalUnassignedWillCalls }); if (resultCount != null) { this.etaTime = resultCount.routeDestination; } }); } else { this._cKpiService.getKPICount(undefined, this.filters.locationFilter, moment.tz(localStorage.getItem('loadDate'), timeId), moment.tz(localStorage.getItem('loadDate'), timeId).endOf('day'), undefined, undefined, undefined, undefined).subscribe(resultCount => { that._cRoutesService.setStatistics( { 'total_vehicle': resultCount.totalVehicle, 'total_vehicle_ids': resultCount.totalVehicleIds, 'total_stops': resultCount.totalStops, 'total_stops_ids': resultCount.totalStopsIds, 'total_unassignedstops': resultCount.unassignedStops, 'total_unassignedstops_ids': resultCount.unassignedStopsIds, 'total_lateRoutes': resultCount.lateRoutes, 'total_lateRoutes_ids': resultCount.lateRouteIds, 'total_remaningPickup': resultCount.remainingPickup, 'total_remaningPickup_ids': resultCount.remainingPickupIds, 'total_remaningDeliveries': resultCount.remainingDeliveries, 'total_remaningDeliveries_ids': resultCount.remainingDeliveriesIds, 'total_incidents': resultCount.orderIncidents, 'total_incidents_ids': resultCount.orderIncidentsIds, 'total_pickedUp': resultCount.pickedUp, 'total_pickedUp_ids': resultCount.pickedUpIds, 'total_delivered': resultCount.delivered, 'total_delivered_ids': resultCount.deliveredIds, 'total_completionRate': resultCount.competionRate, }); if (resultCount != null) { this.lateRouteIds = resultCount.lateRouteIds; this.etaTime = resultCount.routeDestination; this.zoneList = resultCount.zoneList; } }); } if (!isNaN(Date.parse(localStorage.getItem('loadDate')))) { if (localStorage.getItem('loadDate').search('-') > 0) { var str = localStorage.getItem('loadDate').split('-'); var str1 = str[1] + '/' + str[2] + '/' + str[0]; localStorage.setItem('loadDate', str1); } } this._controllerRouteService.getDispatchList(undefined, this.filters.locationFilter, undefined, this.filters.routeId, this.filters.vehicleName, this.filters.routeName, this.filters.driverName, moment.tz(localStorage.getItem('loadDate'), timeId), moment.tz(localStorage.getItem('loadDate'), timeId).endOf('day'), this.filters.filterTxt, (this.filters.osName == "null") ? undefined : this.filters.osName, this.showCompletedRoute, this.filters.routeIds, this.filters.orderType, this.edition, this.routeTypeIds, this.managerIds, undefined, undefined, this.showEmptyRoute, this.driverThreshold, localStorage.getItem('loadDate'), this.filters.isLineHaul, undefined, this.paginator==undefined ? 1000 : this.primengTableHelper.getMaxResultCount(this.paginator, event), this.paginator==undefined ? 0 : this.primengTableHelper.getSkipCount(this.paginator, event)) .subscribe(result => { var noresult = result == null || result.length == 0 ? false : result[0].routeNull; if (noresult) { var result2 = []; this.primengTableHelper.totalRecordsCount = result2.length; this.primengTableHelper.records = result2; this.noResultFound = true; this.getParentComponent().firstload = false; this.spinnerService.hide(); } else { if (result == null) { this.noResultFound = false; this.getParentComponent().lastRefresh = sessionStorage.getItem('last-refresh'); var result2 = []; this.primengTableHelper.totalRecordsCount = result2.length; this.primengTableHelper.records = result2; this.getParentComponent().firstload = false; that.getParentComponent().disableAll(); this.spinnerService.hide(); } else if (result.length > 0) { this.noResultFound = false; that.getParentComponent().enableAll(); sessionStorage.setItem('last-refresh', result[0].currentDateTime); this.getParentComponent().lastRefresh = sessionStorage.getItem('last-refresh'); var increment = 1; var temp = ""; for (var key in result) { that.routeIds.push(result[key].routeId); if (this.filters.isLineHaul ) { this.lineHaulIds.push(result[key].routeId); } else { if (result[key].parentRoute != null) { this.lineHaulIds.push(result[key].routeId); } } if (result[key].completion != null) { this.completedRoutes += 1; } let fullName = result[key].fullName ? "/" + result[key].fullName : ""; this.filterFlyout = { 'routeId': result[key].routeId, 'searchTerm': result[key].routeTemplateName + fullName, } this.filterFlyoutHolder.push(this.filterFlyout); } this.primengTableHelper.records = result; this.primengTableHelper.totalRecordsCount = result.length; this.highlightLateRoutes(this.lateRouteIds); this.getParentComponent().getRouteAndDriver(this.filterFlyoutHolder); this.routeIdsStops.routeIds = that.routeIds; this.routeIdsStops.editions = that.edition; this.boxLimit = localStorage.getItem("BOXLIMIT") == null ? 15 : parseInt(localStorage.getItem("BOXLIMIT")); that._controllerRouteService.stopsStats(that.routeIdsStops) .subscribe(resultStatus => { var totalStandardPackages = 0, totalStandardDeliveredPackages = 0; for (var data in this.primengTableHelper.records) { for (var data1 in resultStatus) if (this.primengTableHelper.records[data].routeId == resultStatus[data1].routeId) { this.primengTableHelper.records[data].statusDescription = resultStatus[data1].statusDescription; this.primengTableHelper.records[data].statusIcon = resultStatus[data1].icon; this.primengTableHelper.records[data].statusColor = resultStatus[data1].color; this.primengTableHelper.records[data].totalStops = resultStatus[data1].totalPackages; this.primengTableHelper.records[data].totalPickedUp = resultStatus[data1].totalPickedUp; this.primengTableHelper.records[data].totalPending = resultStatus[data1].totalPending; this.primengTableHelper.records[data].totalDelivered = resultStatus[data1].totalDelivered; this.primengTableHelper.records[data].totalCallIn = resultStatus[data1].totalCallIn; this.primengTableHelper.records[data].totalCallInPickedUp = resultStatus[data1].totalCallInPickedUp; this.primengTableHelper.records[data].completePercentage = resultStatus[data1].completeRate; this.primengTableHelper.records[data].isBoxLimit = resultStatus[data1].totalPackages <= this.boxLimit ? true : false; // this.primengTableHelper.records[data].eta = resultStatus[data1].eta; break; } totalStandardPackages = totalStandardPackages + resultStatus[data1].totalPackages + resultStatus[data1].totalLineHaul; totalStandardDeliveredPackages = totalStandardPackages + resultStatus[data1].totalPickedUp; } // if (this.edition === 'STANDARD') { // that._cRoutesService.setStatistics({ // 'total_stops': totalStandardPackages, // 'total_delivered': totalStandardDeliveredPackages // }); // } this.highlightLateRoutes(this.lateRouteIds); }); that._controllerRouteService.getProximityCodes(that.routeIds, that.edition, undefined) .subscribe(resultProximity => { for (var data in this.primengTableHelper.records) { for (var data1 in resultProximity) { if (this.primengTableHelper.records[data].routeId == resultProximity[data1].routeId) { this.primengTableHelper.records[data].proximity = resultProximity[data1].proximityCode; break; } } } }); // that._vehicleLogsService.getTotalMileage(that.routeIds).subscribe(result => { // for (var data in this.primengTableHelper.records) { // for (var data1 in result) { // if (this.primengTableHelper.records[data].routeId == result[data1].routeId) { // this.primengTableHelper.records[data].totalMileage = result[data1].totalMileage; // break; // } // } // } // }); if (this.edition === 'LABORATORY') { that.getParentComponent().enableAll(); that._controllerRouteService.getCountRouteDetails(that.routeIds, that.edition, undefined) .subscribe(resultCount => { this.primengTableHelper.records.forEach(val => { val.countPerPackage = [] }); for (var data in this.primengTableHelper.records) { var sum = 0, arrayHolder = []; for (var data2 in resultCount) { if (this.primengTableHelper.records[data].routeId == resultCount[data2].routeId) { this.primengTableHelper.records[data].countPerPackage.push(resultCount[data2]); arrayHolder.push(resultCount[data2].totalPackages) } } sum = arrayHolder.reduce((acc, cur) => acc + cur, 0); this.primengTableHelper.records[data].totalCountPackages = sum; } }); if (this.lineHaulIds.length > 0) { that.getParentComponent().enableAll(); that._controllerRouteService.getCountLineHaulRouteDetails(this.lineHaulIds, that.edition, undefined) .subscribe(resultCount => { this.primengTableHelper.records.forEach(val => { val.countLineHaulPerPackage = [] }); for (var data in this.primengTableHelper.records) { var sum = 0, arrayHolder = []; for (var data2 in resultCount) { if (this.primengTableHelper.records[data].routeId == resultCount[data2].routeId) { this.primengTableHelper.records[data].countLineHaulPerPackage.push(resultCount[data2]); arrayHolder.push(resultCount[data2].quantity); } } sum = arrayHolder.reduce((acc, cur) => acc + cur, 0); this.primengTableHelper.records[data].totalLineHaulPickedupContainers = sum; } }); } } if (this.edition == 'LABORATORY') { this.primengTableHelper.totalRecordsCount = result.length - (that.routeIds.length == this.completedRoutes ? 0 : this.completedRoutes); } } this.spinnerService.hide(); } } ); // END FULL LIST } } tickBox() { this.cBox.tickBox(); } filterArray(array: any, key: any, value: any) { var i, arrList = []; for (i in array) { if (array[i][key] == value) { arrList.push(array[i]); } } return arrList; } filterArrayKeys(array: any, key: any, value: any) { var i, keys = 0; for (i in array) { if (array[i][key] == value) { keys = i; } } return keys; } createOrder(routeId: number) { this.router.navigate([]).then(result => { window.open('/app/sprintship/order-create/' + routeId); }); } openMap(userId, routeId) { this.router.navigate([]).then(result => { window.open('/app/sprintship/locator/' + userId + '/' + routeId, '_blank'); }); } navigateDetail(id, routeName, parentRoute) { localStorage.setItem('isHandOffRoute', parentRoute != null ? 'true' : 'false'); localStorage.setItem('RouteName', routeName) this.router.navigate(['/app/sprintship/controller-routes-details/', id]); } updateRoute() { this._routeService.updateRoute(this.route) .pipe(finalize(() => this.saving = false)) .subscribe(() => { this.notify.info(this.l('SavedSuccessfully')); }); } freezeRoute(routeId, routeCode): void { this.freezeModal.show(routeId, routeCode); } unfreezeRoute(routeId, routeCode): void { this.unfreezeModal.show(routeId, routeCode); } setDepature(record) { this.saving = true; if (!record.locked) { this.updateDepartureRouteInput.id = record.routeId; if (record.departure) { this.updateDepartureRouteInput.departure = false; this._controllerRouteService.updateDepartureRoute(this.updateDepartureRouteInput) .pipe(finalize(() => { this.saving = false; })) .subscribe(() => { this.populateTable(); this.notify.info(this.l('Saved Successfully')); record.departure = false; }); } else { this.updateDepartureRouteInput.departure = true; this._controllerRouteService.updateDepartureRoute(this.updateDepartureRouteInput) .pipe(finalize(() => { this.saving = false; })) .subscribe(() => { this.populateTable(); this.notify.info(this.l('Saved Successfully')); record.departure = true; }); } } else { this.notify.info(this.l('Unlocked Loadlist First')); } } setCompleted(record) { this.saving = true; if (!record.locked) { this.updateCompletedInput.id = record.routeId; if (record.completion) { this.updateCompletedInput.completion = false; this._controllerRouteService.updateCompletedRoute(this.updateCompletedInput) .pipe(finalize(() => { this.saving = false; })) .subscribe(() => { // this.populateTable(); this.getParentComponent().filterRoutes(); this.notify.info(this.l('Saved Successfully')); record.completion = false; }); } else { this.updateCompletedInput.completion = true; this._controllerRouteService.updateCompletedRoute(this.updateCompletedInput) .pipe(finalize(() => { this.saving = false; })) .subscribe(() => { // this.populateTable(); this.getParentComponent().filterRoutes(); this.notify.info(this.l('Saved Successfully')); record.completion = true; }); } } else { this.notify.info(this.l('Unlocked Loadlist First')); } } setLocked(record) { this.updateLockedInput.routeId = record.routeId; if (record.locked == true) { this.updateLockedInput.locked = false; this._controllerRouteService.updateLockedRoute(this.updateLockedInput) .pipe(finalize(() => { this.saving = false; })) .subscribe(() => { this.notify.info(this.l('Route Unlocked Successfully')); }); record.locked = false; } else { this.updateLockedInput.locked = true; this._controllerRouteService.updateLockedRoute(this.updateLockedInput) .pipe(finalize(() => { this.saving = false; })) .subscribe(() => { this.notify.info(this.l('Route Locked Successfully')); }); record.locked = true; } } getParentComponent() { return this.viewContainerRef['_data'].componentView.component.viewContainerRef['_view'].component } selectRoute(id: number) { if (this.sprintIdsList.indexOf(id) == -1) { this.sprintIdsList.push(id); } else { this.sprintIdsList.splice(this.sprintIdsList.indexOf(id), 1); } localStorage.setItem('routeIds', JSON.stringify(this.sprintIdsList)); if (this.sprintIdsList.length == this.routeIds.length) { this.selectAll = true; } else { this.selectAll = false; } } CheckAllOptions() { if (!this.selectAll) { this.primengTableHelper.records.forEach(val => { val.selectedRoute = false }); this.sprintIdsList = []; localStorage.setItem('routeIds', JSON.stringify(this.sprintIdsList)); } else this.primengTableHelper.records.forEach(val => { val.selectedRoute = true; this.sprintIdsList.push(val.routeId) }); localStorage.setItem('routeIds', JSON.stringify(this.sprintIdsList)); } showBlindCountCode(routeId) { this.showBlindCountCodes.routeId = routeId; this._controllerRouteService.showBlindcode(this.showBlindCountCodes).subscribe(result => { $("#showBlindCount" + routeId).show(); $("#hideCount" + routeId).hide(); }); } disableAll() { this.getParentComponent().disableAll(); } generateRoutes() { this.getParentComponent().generateRoute(); } //asign driver assignDriverModal(record: any): void { this.driversList.tenantId = record.id; this.driversList.show(); this.selectedRouteId = record.routeId; } updateRouteByVehicle(item: NameValueDto): void { this.spinnerService.show(); let input = new VehicleInput(); input.driverId = parseInt(item.value); input.routeId = this.selectedRouteId; this._controllerRouteDetails.updateRouteByVehicleId(input).subscribe(result => { $('.dispatch-refresh').trigger('click'); }); } printRouteSheet(id: number) { this.routeId = id; if (localStorage.getItem('routeIds') == null) { this.localRouteIds = []; this.localRouteIds.push(this.routeId) localStorage.setItem('routeIds', JSON.stringify(this.localRouteIds)); } else { localStorage.removeItem('routeIds'); this.localRouteIds = []; this.localRouteIds.push(this.routeId) localStorage.setItem('routeIds', JSON.stringify(this.localRouteIds)); } if (this.edition === 'LABORATORY') { window.open('/app/sprintship/print-route-sheet', '_blank'); } else { window.open('/app/sprintship/route-print', '_blank'); } } removeRoutes(id: number, routeCode: string) { this.message.confirm( this.l('Are you sure you want to delete ' + routeCode + '?'), '', isConfirmed => { if (isConfirmed) { let input: any; input = { 'RouteId': id }; this._controllerRouteService.closedRoutes(input).pipe().subscribe(result => { this.notify.info(this.l('Deleted Successfully')); this.populateTable(null); }); } } ); } markAsDeliveredModal(record: any): void { if(!record.completion){ this.stopList.tenantId = record.id; this.selectedRouteId = record.routeId; this.stopList.show(); } else { let input = new UpdateRouteByStopInput() input.contactId = undefined, input.routeId = record.routeId, input.routeComplete = true, input.loadDate = undefined this._controllerRouteDetails.updateRouteByStop(input).subscribe(result => { this.notify.info(this.l('UnmarkDelivered')); $('.dispatch-refresh').trigger('click'); }); } } updateRouteByStop(item: NameValueDto): void { let timeId = localStorage.getItem('timeZoneId'); let input = new UpdateRouteByStopInput(); input.contactId = parseInt(item.value); input.routeId = this.selectedRouteId; input.loadDate = moment.utc(this.stopList.completionDate); this._controllerRouteDetails.updateRouteByStop(input).subscribe(result => { $('.dispatch-refresh').trigger('click'); }); } 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(controller: ControllerRouteListDto): void { this.entityTypeHistoryModal.show({ entityId: controller.routeId.toString(), entityTypeFullName: this._entityTypeFullName, entityTypeDescription: controller.routeTemplateName }); } openBuilder(id) { this.router.navigate([]).then(result => { window.open('/app/sprintship/route-builder/' + id, '_blank'); }); } expandDetails(obj: string, hoIds: Array, isParent: boolean, parentRoute: any, color: string) { if (hoIds.length > 0) { if ($('.tr-' + hoIds[0]).css('display') == 'none') { $('.fa-' + obj).html(''); let level = 0 if (parentRoute != null) { level = this.primengTableHelper.records.find(o => o.routeId == obj).layer; } let childRoutes = []; hoIds.forEach(r => { var child = this.primengTableHelper.records.find(o => o.routeId == r); var childIndex = this.primengTableHelper.records.findIndex(o => o.routeId == r); this.primengTableHelper.records.splice(childIndex, 1); childRoutes.push(child); $('.tr-' + r).removeClass('handoff-parent'); $('.tr-' + r).css('display', 'table-row'); $('.tr-' + r).css('background', color); child.layer = level + 1; }); var newParentIndex = this.primengTableHelper.records.findIndex(o => o.routeId == obj); Array.prototype.splice.apply(this.primengTableHelper.records, [newParentIndex + 1, 0].concat(childRoutes)); } else { let childIndices = []; var parentIndex = this.primengTableHelper.records.findIndex(o => o.routeId == obj); var getRouteLayer = this.primengTableHelper.records.find(o => o.routeId == obj).layer; for (var i = parentIndex + 1; i <= this.primengTableHelper.records.length - 1; i++) { var element = this.primengTableHelper.records[i]; if (element.layer <= getRouteLayer) { break; } else { childIndices.push(this.primengTableHelper.records.findIndex(o => o.routeId == element.routeId)); } } var getChildRoutes = this.primengTableHelper.records.slice(parentIndex + 1, Math.max(...childIndices) + 1); getChildRoutes.forEach(r => { if (r.isParentHandOff) { $('.fa-' + r.routeId).html(''); } $('.tr-' + r.routeId).css('display', 'none'); }); $('.fa-' + obj).html(''); } } } isEmpty(element: HTMLElement): boolean { const nodes = element.childNodes; for (let i = 0; i < nodes.length; i++) { const node = nodes.item(i); if (node.nodeType !== 8 && nodes.item(i).textContent.trim().length !== 0) { return false; } } return true; } highlightLateRoutes(lateRoutes: any) { if (this.primengTableHelper.records != undefined) { for (var lateRoute in lateRoutes) { for (var route in this.primengTableHelper.records) { if (this.primengTableHelper.records[route].routeId == lateRoutes[lateRoute]) { this.primengTableHelper.records[route].islateRoute = true; } } } } if (this.etaTime != undefined) { for (var lateRoute in this.etaTime) { for (var route in this.primengTableHelper.records) { if (this.primengTableHelper.records[route].routeId == this.etaTime[lateRoute].routeId) { this.primengTableHelper.records[route].targetTimeString = this.etaTime[lateRoute].eta; this.primengTableHelper.records[route].targetTimezoneString = this.etaTime[lateRoute].timezone; } } } if (this.edition == 'LABORATORY') { var sort = _.orderBy(this.primengTableHelper.records, [function (obj) { if (obj.targetTimeString != null) { const date = new Date(); const time = obj.targetTimeString; const yy = new Date(date).getFullYear(); const mm = new Date(date).getMonth() + 1; const dd = new Date(date).getDate(); var newDate = new Date(mm + '-' + dd + '-' + yy); newDate.setHours(time.split(' ')[1] == 'PM' && (time.split(' ')[0]).split(':')[0] < 12 ? (time.split(' ')[0]).split(':')[0] + 12 : (time.split(' ')[0]).split(':')[0]); newDate.setMinutes((time.split(' ')[0]).split(':')[1]); return newDate.getTime(); } }], ['asc']); this.primengTableHelper.records = sort; } } if (this.zoneList != undefined) { for (var zoneData in this.zoneList) { for (var route in this.primengTableHelper.records) { if (this.primengTableHelper.records[route].routeId == this.zoneList[zoneData].routeId) { this.primengTableHelper.records[route].zoneList = this.zoneList[zoneData].zone; } } } } this.primengTableHelper.records[0].isLimit = true; } getDefaultColor() { var color = "hsla(" + ~~(360 * Math.random()) + "," + "70%," + "80%, 1)"; return color; } setCompletion(data: any) { this.spinnerService.show(); if (!data.locked) { if (data.completion == null) { let input = new UpdateRouteByStopInput() input.contactId = undefined; input.routeId = data.routeId; input.loadDate = moment.utc(new Date()); this._controllerRouteDetails.updateRouteByStop(input).subscribe(result => { this.notify.info(this.l('SavedSuccessfully')); this.spinnerService.hide() $('.dispatch-refresh').trigger('click'); }); } else { let input = new UpdateRouteByStopInput() input.contactId = undefined; input.routeId = data.routeId; input.routeComplete = true; input.loadDate = moment.utc(new Date()); this._controllerRouteDetails.updateRouteByStop(input).subscribe(result => { this.notify.info(this.l('SavedSuccessfully')); this.spinnerService.hide(); $('.dispatch-refresh').trigger('click'); }); } } else { this.notify.info(this.l('Unlocked Loadlist First')); this.spinnerService.hide(); } } forceLogOff(driverId: number, routeId: number, routeName: any,) { routeName = routeName == undefined ? "" : this.edition === 'LABORATORY' ? routeName : routeId this.message.confirm( this.l('Are you sure to force log off driver of route ' + routeName + '?'), this.l('AreYouSure'), (isConfirmed) => { if (isConfirmed) { if (driverId != null) { this.spinnerService.show() let dto: LoginUnlockByIdInputDto = new LoginUnlockByIdInputDto(); dto.userId = driverId this._driverClientService.forceLogOffById(dto) .subscribe(result => { this.notify.info('Force Log Off Success'); this.spinnerService.hide(); }) } else { this.notify.warn("Force Log Off Fail"); } } } ); } getContainersCount(childHandOffIds: any) { let child: Array = childHandOffIds; let total = 0; child.forEach(ro => { var route = this.primengTableHelper.records.find(r => r.routeId == ro); if (route.countLineHaulPerPackage != undefined) { if (route.countLineHaulPerPackage.length > 0) { total += parseInt(route.countLineHaulPerPackage[0].totalPickedupContainers > 0 ? route.countLineHaulPerPackage[0].totalPickedupContainers : route.countLineHaulPerPackage[0].totalWaitingPickupContainers); } } }); return total == 0 ? '-' : total; } selectedTab(locationTab: any){ if(this.filters.locationFilter != locationTab.id){ this.filters.locationFilter = locationTab.id; let timeId = localStorage.getItem('timeZoneId'); this._locationServiceProxy.getLocationForLock(this.filters.locationFilter, moment.tz(localStorage.getItem('loadDate'), timeId)).subscribe(result => { this.getParentComponent().lockOrUnlockLocation = result.lock; this.getParentComponent().lockOrUnlockLocationDetails = result; }); localStorage.setItem('selectedTabLocation', locationTab.id); this.populateTable(); } } }