added new components

This commit is contained in:
Pranav 2023-01-07 17:04:55 +00:00
parent 481ac18192
commit 902e04c7e6
12 changed files with 2218 additions and 0 deletions

View file

@ -0,0 +1,153 @@
<div style="top: 0;position: absolute;">
<app-all-menus></app-all-menus>
</div>
<div class="loading" *ngIf="Load">Loading&#8230;</div>
<div class="main">
<!-- <div class="card"> -->
<div class="topnav">
<a class="active">Device Transfer</a>
<div class="search-container">
<form [formGroup]="searchForm" (ngSubmit)="submit()">
<input type="text" placeholder="Search.." formControlName="imei" [ngClass]="{ 'is-invalid': submitted && f.imei.errors }" name="imei">
<button type="submit"><i class="fa fa-search"></i></button>
<div *ngIf="submitted && f.imei.errors" class="invalid-feedback">
<div *ngIf="f.imei.errors.required">Please Enter IMEI Number</div>
</div>
</form>
</div>
</div>
<div style="padding-left:16px;height: 100vh;">
<form [formGroup]="deviceForm" class="row g-3 mt-3">
<div class="col-md-4">
<label class="form-label">IMEI Number</label>
<input type="text" readonly formControlName="imei" class="form-control">
</div>
<div class="col-md-4">
<label class="form-label">Registration Number</label>
<input type="text" readonly formControlName="registrationNumber" class="form-control">
</div>
<div class="col-md-4">
<label class="form-label">Status</label>
<input type="text" readonly formControlName="status" class="form-control">
</div>
<!-- formControlName="superAdmin" (change)="selectSupAdmin($event)" -->
<div class="col-md-4">
<div>
<label class="form-label">Super Admin</label>
</div>
<select id="distributer" multiple="multiple">
<option *ngFor="let item of ditributers" [value]="item._id" [selected] = "item._id === selectedSupAdmin" >{{item.first_name?item.first_name:""}} {{item.last_name?item.last_name:""}}</option>
</select>
<!-- <input type="text" formControlName="superAdmin" class="form-control"> -->
</div>
<div class="col-md-4">
<div>
<label class="form-label">Dealer</label>
</div>
<select id="dealer" multiple="multiple">
<option *ngFor="let item of dealers" [value]="item._id" [selected] = "item._id === selectedDealer">{{item.first_name?item.first_name:""}} {{item.last_name?item.last_name:""}}</option>
</select>
<!-- <input type="text" readonly formControlName="dealaer" class="form-control"> -->
</div>
<div class="col-md-4">
<div>
<label class="form-label">User</label>
</div>
<select id="user" multiple="multiple">
<option *ngFor="let item of users" [value]="item._id" [selected] = "item._id === selectedUser">{{item.first_name?item.first_name:""}} {{item.last_name?item.last_name:""}}</option>
</select>
<!-- <input type="text" readonly formControlName="user" class="form-control"> -->
</div>
<!-- <div class="col-md-4">
<label class="form-label">Sim 2</label>
<input type="text" readonly formControlName="sim2" class="form-control">
</div>
<div class="col-md-4">
<label class="form-label">Vehicle Type</label>
<input type="text" readonly formControlName="vehicleType" class="form-control">
</div>
<div class="col-md-4">
<label class="form-label">Device Model</label>
<input type="text" readonly formControlName="deviceModel" class="form-control">
</div>
<div class="col-md-4">
<label class="form-label">Sim 1</label>
<input type="text" readonly formControlName="sim1" class="form-control">
</div>
<div class="col-md-4">
<label class="form-label">Creation date</label>
<input type="text" readonly formControlName="creationDate" class="form-control">
</div>
<div class="col-md-4">
<label class="form-label">Expiration date</label>
<input type="text" readonly formControlName="expirationDate" class="form-control">
</div>
<div class="col-md-4">
<label class="form-label">Last Renewal Date</label>
<input type="text" readonly formControlName="lastRenewal" class="form-control">
</div>
<div class="col-md-4">
<label class="form-label">Deleted</label>
<input type="text" readonly formControlName="deleted" class="form-control">
</div>
<div *ngIf="!deleteShow" class="col-md-4">
<label class="form-label">Deleted By</label>
<input type="text" readonly formControlName="deletedBy" class="form-control">
</div>
<div *ngIf="!deleteShow" class="col-md-4">
<label class="form-label">Deleted At</label>
<input type="text" readonly formControlName="deletedAt" class="form-control">
</div>
<div *ngIf="!deleteShow" class="col-md-4">
<label class="form-label">Deleted From</label>
<input type="text" readonly formControlName="deletedFrom" class="form-control">
</div> -->
<!-- <div *ngIf="deleteShow" class="col-md-12 text-center mt-4">
<button class="btn btn-danger" (click)="deleteDevice()">Delete <i class="fa fa-trash"></i></button>
</div>
<div *ngIf="deleted" class="col-md-12 text-center mt-4">
<button class="btn btn-danger" (click)="deleteDevicePermenatly()">Delete Permanatly <i class="fa fa-trash"></i></button>
</div> -->
<div *ngIf="deleteShow" class="col-md-12 text-center mt-4">
<button class="btn btn-primary" (click)="deleteDevice()">Save <i class="fa fa-save"></i></button>
</div>
</form>
</div>
</div>
<!-- </div> -->

View file

@ -0,0 +1,94 @@
.main {
padding: 20px;
margin-top: 55px;
}
.topnav {
overflow: hidden;
background-color: #e9e9e9;
}
.topnav a {
float: left;
display: block;
color: black;
text-align: center;
padding: 14px 16px;
text-decoration: none;
font-size: 17px;
}
.topnav a:hover {
background-color: #ddd;
color: black;
}
.topnav a.active {
background-color: #2196f3;
/* color: blueviolet; */
width: 290px;
font-size: larger;
font-weight: 600;
}
.topnav .search-container {
float: right;
}
.topnav input[type="text"] {
padding: 6px;
margin-top: 8px;
font-size: 17px;
border: black;
}
.topnav .search-container button {
float: right;
padding: 6px 10px;
margin-top: 8px;
margin-right: 16px;
background: #ddd;
font-size: 17px;
border: none;
cursor: pointer;
}
.topnav .search-container button:hover {
background: blue;
}
@media screen and (max-width: 600px) {
.topnav .search-container {
float: none;
}
.topnav a,
.topnav input[type="text"],
.topnav .search-container button {
float: none;
display: block;
text-align: left;
width: 100%;
margin: 0;
padding: 14px;
}
.topnav input[type="text"] {
border: 1px solid #ccc;
}
}
.col-md-6 {
margin-top: 15px;
}
.ms-choice>div {
position: inherit !important;
}
.ms-choice>span {
position: inherit !important;
}
.ms-parent {
display: contents;
}

View file

@ -0,0 +1,25 @@
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { DeviceSettingComponent } from './device-setting.component';
describe('DeviceSettingComponent', () => {
let component: DeviceSettingComponent;
let fixture: ComponentFixture<DeviceSettingComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ DeviceSettingComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(DeviceSettingComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should be created', () => {
expect(component).toBeTruthy();
});
});

View file

@ -0,0 +1,336 @@
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { MdSnackBar } from '@angular/material';
import { ContactService } from '../contact.service';
declare var $: any;
declare var google: any, swal: any;
@Component({
selector: 'app-device-setting',
templateUrl: './device-setting.component.html',
styleUrls: ['./device-setting.component.scss']
})
export class DeviceSettingComponent implements OnInit {
emailId: any;
Load: Boolean=false;
searchForm: FormGroup;
deleteShow: boolean = false;
submitted = false;
userId: any;
deviceForm: FormGroup
data: any;
deleted: boolean = false;
ditributers
dealers
users: any;
selectedSupAdmin
selectedDealer
selectedUser
// @ViewChild(BaseChartDirective) public chart: BaseChartDirective;
constructor(private contactService: ContactService, private fb: FormBuilder, public snackBar: MdSnackBar) {
}
ngOnInit(): void {
this.searchForm = this.fb.group({
imei: ['', Validators.required]
})
this.deviceForm = this.fb.group({
imei: [''],
registrationNumber: [''],
sim1: [''],
sim2: [''],
dealaer: [''],
user: [''],
deviceModel: [''],
vehicleType: [''],
expirationDate: [''],
creationDate: [''],
superAdmin: [''],
lastRenewal: [''],
status: [''],
deleted: [''],
deletedBy: [''],
deletedAt: [''],
deletedFrom: ['']
// 352887076587769
})
this.emailId = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).email;
this.userId = JSON.parse(window.atob(window.localStorage.token.split('.')[1]))._id;
this.loadDropdown()
this.getDistributers();
var that=this
$("#distributer").change(function () {
// alert($(this).val());
console.log($(this).val());
var value = $(this).val();
that.selectedSupAdmin = value[0];
that.getDealers(that.selectedSupAdmin)
console.log(that.selectedSupAdmin);
// var prevSelect = $("#MultiSelect_Preview").select2();
// prevSelect.val($(this).val()).trigger('change');
});
$("#dealer").change(function () {
// var that = this
// alert($(this).val());
console.log($(this).val());
var value = $(this).val();
that.selectedDealer = value[0];
that.getUsers(that.selectedDealer)
// that.getUser(that.selectedDealer)
console.log(that.selectedDealer);
// var prevSelect = $("#MultiSelect_Preview").select2();
// prevSelect.val($(this).val()).trigger('change');
});
$("#dealer").change(function () {
// var that = this
// alert($(this).val());
console.log($(this).val());
var value = $(this).val();
that.selectedUser = value[0];
// that.getUser(that.selectedUser)
console.log(that.selectedUser);
// var prevSelect = $("#MultiSelect_Preview").select2();
// prevSelect.val($(this).val()).trigger('change');
});
}
loadDropdown(){
var script = document.createElement("script");
script.setAttribute("type", "text/javascript");
script.setAttribute("src", "https://unpkg.com/multiple-select@1.3.1/dist/multiple-select.min.js");
document.getElementsByTagName("head")[0].appendChild(script);
setTimeout(() => {
$('#distributer').multipleSelect({
width: 470,
placeholder: "Select Distributer",
filter: true,
single: true,
selectAll: false
})
}, 100);
setTimeout(() => {
$('#dealer').multipleSelect({
width: 470,
placeholder: "Select Dealer",
filter: true,
single: true,
selectAll: false
})
}, 100);
setTimeout(() => {
$('#user').multipleSelect({
width: 470,
placeholder: "Select User",
filter: true,
single: true,
selectAll: false
})
}, 100);
}
get f() { return this.searchForm.controls; }
getDistributers(){
this.Load=true;
this.contactService.getSuperAdminList().subscribe(res => {
this.ditributers=res;
this.loadDropdown()
this.Load = false;
},err=>{
this.Load = false;
})
}
getDealers(id) {
this.Load = true;
this.dealers=[]
this.contactService.getDealersDetails(id).subscribe(res => {
this.dealers = res;
this.dealers = this.dealers.concat(this.ditributers);
this.loadDropdown()
this.Load = false;
}, err => {
this.Load = false;
})
}
getUsers(id) {
this.Load = true;
this.users = []
this.contactService.getContactsbyDealer(id).subscribe(res => {
this.users = res;
this.users = this.users.concat(this.ditributers);
this.users = this.users.concat(this.dealers);
this.users = this.users.filter((el, i, a) => i === a.indexOf(el))
this.loadDropdown()
this.Load = false;
}, err => {
this.Load = false;
})
}
selectSupAdmin(event){
// console.log(event.target.value);
this.getDealers(event)
}
selectDealer(event) {
console.log(event.target.value);
this.getUsers(event.target.value)
}
submit() {
this.Load = true;
console.log(this.searchForm.value);
this.submitted = true;
// stop here if form is invalid
if (this.searchForm.invalid) {
return;
}
this.contactService.searchByImei(this.searchForm.value).subscribe((res: any) => {
console.log(res);
this.data = res[0];
this.Load = false;
if (res.length != 0) {
this.deleteShow = true
if (res[0].deletedDevice) {
this.deleteShow = false;
this.deleted = true;
} else {
this.deleted = false;
}
this.selectedSupAdmin = this.data.supAdmin ? this.data.supAdmin._id : ''
this.selectedUser = this.data.user ? this.data.user._id : '';
this.selectedDealer = this.data.Dealer ? this.data.Dealer._id : '',
console.log(this.selectedSupAdmin);
this.deviceForm.patchValue({
imei: this.data.Device_ID,
registrationNumber: this.data.Device_Name,
sim1: this.data.sim_number ? this.data.sim_number : '',
sim2: this.data.sim_number2 ? this.data.sim_number2 : '',
dealaer: this.data.Dealer ? this.data.Dealer._id: '',
user: this.data.user ? this.data.user._id : '',
deviceModel: this.data.device_model ? this.data.device_model.device_type : '',
vehicleType: this.data.vehicleType ? (this.data.vehicleType.brand ? this.data.vehicleType.brand : '') + ' ' + (this.data.vehicleType.model ? this.data.vehicleType.model : '') : '',
expirationDate: this.data.expiration_date ? this.data.expiration_date : '',
superAdmin: this.data.supAdmin ? this.data.supAdmin._id : '',
lastRenewal: this.data.renew_at ? this.data.renew_at : '',
creationDate: this.data.created_on ? this.data.created_on : '',
status: this.data.status,
deleted: this.data.deletedDevice ? 'Yes' : 'No',
deletedBy: this.data.device_deleted_by ? this.data.device_deleted_by.first_name + " " + this.data.device_deleted_by.last_name : ' ',
deletedAt: this.data.device_delete_on,
deletedFrom: this.data.login_type,
})
if (this.data.supAdmin)
this.getDealers(this.data.supAdmin._id);
if (this.data.Dealer)
this.getUsers(this.data.Dealer._id)
} else {
this.deleteShow = false;
this.deviceForm.reset();
this.snackBar.open("No Data Found", '', {
duration: 4000,
});
}
},err=>{
this.Load = false;
})
}
deleteDevice() {
swal({
title: '<strong>Are you sure?</strong>',
icon: 'warning',
html: "You won't be able to revert this!",
showCloseButton: true,
focusConfirm: false,
// confirmButtonText: 'Reset today ODO',
confirmButtonText: 'Yes, Save it!',
// cancelButtonText: 'Reset total ODO',
// cancelButtonAriaLabel: 'Thumbs down'
cancelButtonText: 'No, cancel!',
}).then((result: { value: boolean; }) => {
if (result) {
var req = {
_id: this.data._id,
Dealer: this.selectedDealer ? this.selectedDealer : this.data.Dealer ? this.data.Dealer._id:undefined,
user: this.selectedUser ? this.selectedUser : this.data.user ? this.data.user._id : undefined,
supAdmin: this.selectedSupAdmin ? this.selectedSupAdmin : this.data.supAdmin ? this.data.supAdmin._id : undefined
}
this.contactService.post("/devices/updateDeviceByAdmin",req).subscribe(res => {
swal({
title: 'Saved!',
html: 'Your file has been saved.',
icon: 'success'
})
})
this.deviceForm.reset();
this.deleteShow = false;
}
}
)
}
deleteDevicePermenatly() {
swal({
title: '<strong>Are you sure?</strong>',
icon: 'warning',
html: "Device will be deleted permanantly",
showCloseButton: true,
focusConfirm: false,
// confirmButtonText: 'Reset today ODO',
confirmButtonText: 'Yes, delete it!',
// cancelButtonText: 'Reset total ODO',
// cancelButtonAriaLabel: 'Thumbs down'
cancelButtonText: 'No, cancel!',
}).then((result: { value: boolean; }) => {
if (result) {
var req = {
device: this.data.Device_ID,
userId: this.userId,
permenant: true
}
this.contactService.deldev(req).subscribe(res => {
swal({
title: 'Deleted!',
html: 'Your file has been deleted.',
icon: 'success'
})
})
this.deviceForm.reset();
}
}
)
}
}

View file

@ -0,0 +1,77 @@
<!-- <app-all-menus></app-all-menus> -->
<div class="topDiv">
<div id="toast">
<div id="desc">{{data_descip}}</div>
</div>
<div class="row"
style="text-align: center; background: #426E86; padding-top: 10px; padding-bottom: 10px; color: white;box-shadow:3px 1px 5px 0px rgb(178, 176, 174)">
<div class="col-sm-12 col-md-12 col-lg-12">
<h4>{{'Current Position Report' | translate}}</h4>
</div>
</div>
<div class="row rowStyle">
<div class="col-sm-12 col-md-12 col-lg-12" style="padding-left: 5px; padding-right: 20px; padding-top: 5px;">
<div class="row"
style="margin:0px;height: 84vh;padding-top:10px;padding-bottom:5px;background: white;box-shadow: 3px 1px 5px 0px #b2b0ae;">
<div class="col-sm-12 col-md-12 col-lg-12">
<div class="row">
<div class="col-sm-12 col-md-12 col-lg-12">
<button class="btn btn-default" [disabled]="firstcall" (click)="next()"
style="margin-right: 1px;width: 89px;float: right;color:white;line-height: 1.6;background: #426E86;height: auto;font-size: 12px;border-radius: 0px;border: none;margin-bottom: 10px;">{{'Next'
| translate}} >></button>
<button class="btn btn-default" [disabled]="lastcall" (click)="pre()"
style="width: 90px;float: right;color:white;margin-right: 0;line-height: 1.6;background: #426E86;height: auto;font-size: 12px;border-radius: 0px;border: none;margin-bottom: 10px;">
<< {{'Previous' | translate}}</button>
</div>
</div>
<div class="row">
<div class="col-sm-12 col-md-12 col-lg-12">
<div class="loading" *ngIf="Load">Loading&#8230;</div>
<div style="width: 100%;height:84vh;">
<table id="deviceTable" cellspacing="0" style="width: 100%;font-size: 14px;">
<thead style="background-color:#e0e0e0;color: #444444;">
<!-- <tr>
<th style="text-align: left;">{{'Device Name' | translate}}</th>
<th style="text-align: left;">{{'From Date' | translate}}</th>
<th style="text-align: left;">{{'To Date' | translate}}</th>
<th style="text-align: left;">{{'Start Location' | translate}}</th>
<th style="text-align: left;">{{'End Location' | translate}}</th>
<th style="text-align: left;">{{'Total K.M.' | translate}}</th>
<th style="text-align: left;">{{'Details' | translate}}</th>
</tr> -->
<tr>
<th style="text-align:left;" title="Object">{{'Object'| translate}}</th>
<th style="text-align:left;" title="Time">{{'Time' | translate}}</th>
<th style="text-align:left;" title="Position">{{'Position' | translate}}</th>
<th style="text-align:left;" title="Speed">{{'Speed' | translate}}</th>
<th style="text-align:left;" title="Status">{{'Status' | translate}}</th>
<!-- <th style="text-align: left;">{{'Total K.M.' | translate}}</th>
<th style="text-align: left;">{{'Details' | translate}}</th> -->
</tr>
</thead>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<table id="headerTable" style="border: 1px solid black;width: 100%;
border-collapse: collapse;position: absolute;top: -62px;">
<tr style="height:30px;border-top:1px solid black;">
<!-- <td>
<span style="font-weight: 700;">Report Interval from</span> {{Fromdate | date:"medium"}} to {{todate | date:"medium"}}
</td> -->
<!-- <td>
<span style="font-weight: 700;">To</span>: {{todate | date:"medium"}}
</td> -->
</tr>
</table>

View file

@ -0,0 +1,52 @@
col-sm-9 col-md-9 col-lg-9 .ms-parent {
width: 100% !important;
}
#toast {
visibility: hidden;
max-width: 250px;
height: 50px;
/*margin-left: -125px;*/
margin: auto;
background-color: #333;
color: #fff;
text-align: center;
border-radius: 2px;
position: fixed;
z-index: 1;
left: 60%;
right: 0;
bottom: 80%;
font-size: 13px;
white-space: nowrap;
}
#toast #img {
width: 250px;
height: 50px;
float: left;
padding-top: 16px;
padding-bottom: 16px;
box-sizing: border-box;
background-color: #111;
color: #fff;
}
#toast #desc {
color: #fff;
padding: 16px;
overflow: hidden;
white-space: nowrap;
}
#toast.show {
visibility: visible;
-webkit-animation: fadein 0.5s, expand 0.5s 0.5s, stay 3s 1s, shrink 0.5s 2s,
fadeout 0.5s 2.5s;
animation: fadein 0.5s, expand 0.5s 0.5s, stay 3s 1s, shrink 0.5s 4s,
fadeout 0.5s 4.5s;
}

View file

@ -0,0 +1,25 @@
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { CurrentPositionReportComponent } from './current-position.component';
describe('CurrentPositionReportComponent', () => {
let component: CurrentPositionReportComponent;
let fixture: ComponentFixture<CurrentPositionReportComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ CurrentPositionReportComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(CurrentPositionReportComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should be created', () => {
expect(component).toBeTruthy();
});
});

View file

@ -0,0 +1,913 @@
import { Component, OnInit } from '@angular/core';
import { ContactService } from '../../../contact.service';
import { MdDialog, MdDialogRef, MD_DIALOG_DATA } from '@angular/material';
import { MyaccountComponent } from '../../../myaccount/myaccount.component';
import { Params, Router, ActivatedRoute, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { FlashMessagesService } from 'angular2-flash-messages';
//import { DetailComponent } from './details/details.component';
import { ReportService } from '../../report.service';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
// declare function show
declare var google: any;
declare var jsPDF: any;
declare var $: any;
const PDF_EXTENSION = ".pdf";
declare var moment: any;
@Component({
selector: 'app-current-position',
templateUrl: './current-position.component.html',
styleUrls: ['./current-position.component.scss']
})
export class CurrentPositionReportComponent implements OnInit {
finalArr = []
dataSelect: any[];
closeProcess: number;
deviceArr: any = [];
reportArr: any = [];
firstcall: boolean = true;
lastcall: boolean = true;
skip: number = 0;
tabelObj: any;
devices: any;
value
distanceVariation
private finalise = new Subject<void>();
constructor(private contactService: ContactService, private _service: ReportService, private router: Router, public dialog: MdDialog, private _flashMessagesService: FlashMessagesService) {
this._service.invokeEventForCurrentPosition.pipe(
takeUntil(this.finalise)
).subscribe(value => {
if (value) {
this.value = value
this.getReport(value);
}
console.log(value);
this.devices = JSON.parse(localStorage.getItem('vehicaleData'))
console.log(this.devices);
})
}
fs: any;
ls: any;
emailid: any;
or: any;
useridd: any;
time: any;
device_data: any;
devicess: any;
final: any;
custtype: any;
cust: boolean = false;
Load: Boolean = false;
date: any;
devicesss: any;
mb: any;
logoutbut: boolean;
dealer: boolean;
text: any;
option: any;
finall: any;
Fromdate: any;
todate: any;
options = [];
logo: any;
before: any;
date1: any;
daily_report_data: any;
superAdmin: Boolean = false;
ngOnInit() {
// var fTime = new Date().setHours(0,0,0);
// this.Fromdate = new Date(fTime);
// show()
this.superAdmin = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).isSuperAdmin;
this.fs = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).fn;
this.ls = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).ln;
this.emailid = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).email;
this.or = JSON.parse(window.atob(window.localStorage.token.split(".")[1]))._orgName;
this.useridd = JSON.parse(window.atob(window.localStorage.token.split('.')[1]))._id;
this.mb = JSON.parse(window.atob(window.localStorage.token.split('.')[1])).phn;
this.custtype = JSON.parse(window.atob(window.localStorage.token.split('.')[1])).isDealer;
if (this.custtype == true) {
this.cust = true;
}
if (this.mb.charAt(0) == "n") {
this.mb = ' '
}
if (window.localStorage['Custumer'] == 'ON') {
this.logoutbut = false
this.dealer = true
}
else {
this.logoutbut = true
}
this.logo = window.localStorage['logo'];
this.text = window.localStorage['text'];
this.testTable();
}
uId: any;
d_name: any;
d_report: any;
total_dist: any;
total_km: any;
start_add_lat: any;
start_add_long: any;
end_add_lat: any;
end_add_long: any;
device_summary = [];
address_show: any;
end_add_show: any;
identifier: any = 'distance_report';
data_descip: any;
TODATE
FROMDATE
tpdata
getReport(event) {
if (event == 'getExcel') {
this.exportExcel();
} else if (event == 'getPdf') {
this.expotToPdf();
} else {
var deviceId: any;
this.tpdata = event;
var that = this;
// var fd = new Date(this.tpdata.fromDate);
// var td = new Date(this.tpdata.toDate);
// var toDATE = new Date(this.tpdata.fromDate);
// this.TODATE = moment(this.tpdata.toDate).format('LL')
// this.FROMDATE = moment(this.tpdata.fromDate).format('LL')
// var date: any = toDATE.setDate(toDATE.getDate() + 1)
// this.FROMDATE=new Date(date).toISOString().replace(/T.*/,'').split('-').reverse().join('-')
// this.TODATE=td.toISOString().replace(/T.*/,'').split('-').reverse().join('-')
//console.log("FROM", this.FROMDATE, "==", this.TODATE);
// if (event.deviceArr.length == 0) {
// deviceId = [];
// } else {
// deviceId = event.deviceArr;
// }
// this.deviceArr = deviceId;
// console.log('this.deviceArr', this.deviceArr);
// this.Fromdate = fd.toISOString();
// this.todate = td.toISOString();
// var diff = moment(this.todate).diff(this.Fromdate, 'days')
// if (diff >= 31) {
// this.data_descip = 'Report is unavailable for more than a month';
// launch_toast();
// } else if (diff >= 15 && this.deviceArr.length >= 10) {
// // if(this.deviceArr.length>=10){
// this.data_descip = 'Please select less than 10 vehicals';
// launch_toast();
// // }
// } else {
this.skip = 0;
this.firstcall = false;
this.lastcall = true;
this.tabelObj.ajax.reload();
//}
}
function launch_toast() {
// console.log(divid);
var x = document.getElementById("toast")
//console.log(x);
x.className = "show";
setTimeout(function () { x.className = x.className.replace("show", ""); }, 4500);
}
}
testTable() {
const that = this;
console.log("inside function");
$(document).ready(function () {
that.tabelObj = $('#deviceTable').DataTable({
// dom: 'Bfrtip',
// buttons: [
// 'copy',
// 'print',
// 'excel'
// ],
"processing": false,
"searching": true,
pagingType: 'full_numbers',
pageLength: 25,
serverSide: false,
responsive: true,
"scrollY": '60vh',
"scrollCollapse": true,
// "deferLoading": 25 ,
lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
"rowCallback": function (row: Node, data: any | Object, index: number) {
$('#edit', row).bind('click', () => {
var internalThat = that;
// console.log('rowrowrowrow=>',row);
// console.log('datadatadatadata',data);
// var fromDate=new Date(that.Fromdate)
// var date=new Date(fromDate.setDate(fromDate.getDate()+1)).toISOString()
// let dialogRef = that.dialog.open(DetailComponent, {
// // width: '950px',
// // height: '1160px',
// data: data.details
// });
});
$('#refresh', row).bind('click', () => {
var internalThat = that;
console.log('rowrowrowrow=>', row);
console.log('datadatadatadata', data);
let geocoder = new google.maps.Geocoder();
let t_latlng
var d_lat;
var d_lng;
if (data.last_location) {
t_latlng = new google.maps.LatLng(data.last_location.lat, data.last_location.long);
d_lat = data.last_location.lat;
d_lng = data.last_location.long
let request = {
latLng: t_latlng
};
geocoder.geocode(request, function (data, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (data[0] != null) {
var liveAdd = data[0].formatted_address;
// //console.log(outerThis.liveAdd);
that.saveAddress(d_lat, d_lng, liveAdd)
}
}
else {
// that.liveAdd = 'NA';
}
})
}
})
// else{
// outerThis.liveAdd = res.address;
// }
// console.log("ADDRESS---->",outerThis.liveAdd);
// })
// });
},
ajax: (dataTablesParameters, callback) => {
console.log(that.Fromdate);
var date
var deviceID;
// if(that.Fromdate){
// var fromDate=new Date(that.Fromdate)
// date=new Date(fromDate.setDate(fromDate.getDate()+1)).toISOString()
// }
console.log(date);
that.Load = true;
var from_date = that.Fromdate;
var to_date = that.todate;
var user = that.useridd;
var temp = {
from_date: from_date,
to_date: to_date,
user: user
}
var suburl = "";
// var limit = 26;
// suburl += "/summary/getDistanceNew?from=" + temp.from_date + '&to=' + temp.to_date + '&user=' + temp.user + '&skip=' + that.skip;
// if (that.deviceArr.length != 0) {
// suburl += '&device=' + that.deviceArr;
// }
suburl += "/devices/getDeviceByUser?email=" + that.emailid + '&id=' + that.useridd
if (true) {
that.contactService.get(suburl).subscribe((resp: any) => {
that.Load = false;
that.reportArr = [];
that.reportArr = resp.devices && resp.devices.length ? resp.devices :[] ;
if (that.reportArr.length != 0) {
var j = 0;
that.finalArr = [];
for (var i = 0; i < that.reportArr.length; i++) {
if (that.reportArr[i]) {
if (that.reportArr[i].status_updated_at == undefined) {
let dev_status_1 = that.reportArr[i].status ? that.reportArr[i].status : "Not available";
that.reportArr[i].status = dev_status_1;
// console.log("Not Available !!!");
} else {
// this.arrival_time = new Date(that.reportArr[i].status_updated_at)
let dev_status = that.reportArr[i] ? that.reportArr[i].status : "NA";
var curr_time: any = new Date();
this.arrival_time = new Date(that.reportArr[i].status_updated_at);
var fd: any = new Date(this.arrival_time);
// console.log('curr_time',curr_time,this.arrival_time);
var diffInMilliSeconds = Math.abs(curr_time - fd) / 1000;
// calculate days
const days = Math.floor(diffInMilliSeconds / 86400);
diffInMilliSeconds -= days * 86400;
// console.log('calculated days', days);
// calculate hours
const hours = Math.floor(diffInMilliSeconds / 3600) % 24;
diffInMilliSeconds -= hours * 3600;
// console.log('calculated hours', hours);
// calculate minutes
const minutes = Math.floor(diffInMilliSeconds / 60) % 60;
diffInMilliSeconds -= minutes * 60;
// console.log('minutes', minutes);
let difference = '';
if (days > 0) {
difference += (days === 1) ? `${days} day, ` : `${days} days, `;
}
difference += (hours === 0 || hours === 1) ? `${hours} hour, ` : `${hours} hours, `;
difference += (minutes === 0 || hours === 1) ? `${minutes} minutes` : `${minutes} minutes`;
// new conversion logic
this.Durations = difference;
if (dev_status == undefined) {
this.status_toShow = "NA";
} else {
this.status_toShow = dev_status + " " + "Since" + " " + this.Durations;
}
that.reportArr[i].status = this.status_toShow;
}
that.clocation_1(that.reportArr[i], function (err, succ) {
if (err) {
console.log(err);
j++;
} else {
console.log(succ);
that.finalArr.push(succ);
console.log(that.finalArr);
j++;
if (j === that.reportArr.length) {
that.Load = false;
callback({ data: that.finalArr });
}
}
})
} else {
that.Load = false;
callback({ data: [] });
}
}
} else {
that.Load = false;
that.firstcall = true;
that.lastcall = (that.skip > 0) ? false : true;
callback({ data: [] });
}
}, err => {
that.Load = false;
callback({ data: [] });
console.log("error", err);
});
} else {
}
},
"columns": [
{
"data": "Device_Name",
"render": function (data, type, row) {
return data ? data : '';
}
},
{
"data": "last_ping_on",
"render": function (data, type, row) {
var expDate = new Date(data);
return data ? (moment(expDate).format('lll')) : "";
}
},
{
"data": "position",
"render": function (data, type, row) {
// let date=new Date(that.todate).getDate()+"/"+new Date(that.todate).getMonth()+"/"+new Date(that.todate).getFullYear()
var address
var biden = typeof data;
if (biden === 'object') {
// var addressLink = '<a href="https://maps.google.com/?q='+ data.latlng.lat +','+data.latlng.long +' " target="_blank" title="Click to get vehicle last location"> <img height="20px" width="20px" src="../../../assets/image/addressICON.png"> </a>';
return `<button class="btn btn=info btn-sm"><i id="refresh" title="Refresh Address" style="font-size:20px;color: green" class="fas fa-redo"></i></button>`;
} else {
return data ? data : '--';
}
}
},
{
"data": "last_speed",
"defaultContent": "",
render: function (data, type, row) {
return (data ? data : '') + ' kph';
}
},
{
"data": "status",
render: function (data, type, row) {
return data ? data : '';
}
}
// <i class="fas fa-info-circle"></i>
],
"columnDefs": [
{ className: "dt-body-left", "targets": [0, 1, 2, 3, 4] },
// {
// "targets": '_all',
// "createdCell": function (td, cellData, rowData, row, col) {
// $(td).css('padding', '18px')
// }
// } ,
// { "width": "10px", "targets": 0 },
// { "width": "40px", "targets": 1 },
// { "width": "100px", "targets": 2 },
// { "width": "70px", "targets": 3 },
// { "width": "10px", "targets": 3 },
// {
// targets: -1, //-1 es la ultima columna y 0 la primera
// data: null,
// defaultContent: '<div class="btn-group"> <button (click)="show()">view</button></div>'
// },
]
});
});
}
saveAddress(lat, lng, address) {
var addressObj = {
"lat": lat,
"long": lng,
"address": address
}
this.contactService.saveAdd(addressObj).subscribe(res => {
console.log(res);
this.getReport(this.value);
}, err => {
//console.log("couldn't save address");
})
}
tab: any;
exportExcel() {
var tab_text = "<table border='2px'><tr bgcolor='#87AFC6'>";
var textRange; var j = 0;
var table = $('#deviceTable').clone();
table[0].querySelector("thead").remove();
table[0].prepend($(".dataTable thead").clone()[0]);
this.tab = table[0];
for (j = 0; j < this.tab.rows.length; j++) {
tab_text = tab_text + this.tab.rows[j].innerHTML + "</tr>";
}
tab_text = tab_text + "</table>";
tab_text = tab_text.replace(/<input[^>]*>|<\/input>/gi, "");
var ua = window.navigator.userAgent;
var msie = ua.indexOf("MSIE ");
var sa = window.open('data:application/vnd.ms-excel,' + encodeURIComponent(tab_text));
return (sa);
}
filterStates(val) {
// console.log(val)
// console.log(this.options)
if (val == "") {
this.dataSelect = [];
// console.log("deviceValue",this.dataSelect);
} else {
const filterValue: any = val;
this.dataSelect = this.options.filter(function (d) {
var t = d.value.toLocaleLowerCase().indexOf(filterValue.toLocaleLowerCase());
// this.option = this.options[i];
return t > -1;
});
return this.dataSelect;
}
}
ngOnDestroy() {
this.closeProcess = 0;
this.finalise.next(void 0);
}
clocation_1(latlngObj, cb) {
var outerThis = this;
var la = '';
let latLng = {
lat: "0",
long: "0"
};
latLng = {
long: latlngObj.last_loc && latlngObj.last_loc.coordinates && latlngObj.last_loc.coordinates.length && latlngObj.last_loc.coordinates[0] ? latlngObj.last_loc.coordinates[0] : 0,
lat: latlngObj.last_loc && latlngObj.last_loc.coordinates && latlngObj.last_loc.coordinates.length && latlngObj.last_loc.coordinates[1] ? latlngObj.last_loc.coordinates[1]: 0
}
outerThis.contactService.getAddressByApi(latLng).subscribe(res => {
if (res.message == "Address not found in databse") {
var adata = {
iden: 'noaddress',
latlng: latLng
}
latlngObj['position'] = adata;
} else {
latlngObj['position'] = res.address;
}
cb(null,latlngObj);
}, err => {
latlngObj['position'] = 'N/A';
cb(null, latlngObj);
})
}
next() {
// this.reportArr =[];
this.lastcall = false;
this.skip += 1;
// this.sidebarData();
// this.ngOnInit();
this.tabelObj.ajax.reload();
}
pre() {
// this.reportArr=[]
// console.log(this.skip)
if (this.skip > 0) {
this.skip -= 1;
this.lastcall = false;
// this.sidebarData();
// this.ngOnInit();
this.tabelObj.ajax.reload();
} else {
this.lastcall = true;
this.firstcall = false;
}
}
// --------------------New Method for excel export-------------------
exportExcels() {
for (var i = 0; i < this.reportArr.length; i++) {
//this.reportArr[i].status = this.reportArr[i].device.Device_Name;
}
this.downloadFile(this.reportArr);
}
downloadFile(data, filename = 'Distance Report') {
let arrHeader = ["Object", "Time", "Position", "Speed", "Status"];
let csvData = this.ConvertToCSV(data, arrHeader);
let blob = new Blob(['\ufeff' + csvData], { type: 'text/csv;charset=utf-8;' });
let dwldLink = document.createElement("a");
let url = URL.createObjectURL(blob);
let isSafariBrowser = navigator.userAgent.indexOf('Safari') != -1 && navigator.userAgent.indexOf('Chrome') == -1;
if (isSafariBrowser) { //if Safari open in new window to save file with random filename.
dwldLink.setAttribute("target", "_blank");
}
dwldLink.setAttribute("href", url);
dwldLink.setAttribute("download", "Distance Report.csv");
dwldLink.style.visibility = "hidden";
document.body.appendChild(dwldLink);
dwldLink.click();
document.body.removeChild(dwldLink);
}
ConvertToCSV(objArray, headerList) {
let array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
// console.log(array,"<===");Distance 126.94
// Running 2:1
// Idle 1:56
// Stop
let str = 'Current Position Report \r\n';
let row = 'S.No,';
let newHeaders = ["Object", "Time", "Position", "Speed", "Status"];
for (let index in newHeaders) {
row += newHeaders[index] + ',';
}
row = row.slice(0, -1);
str += row + '\r\n';
for (let i = 0; i < array.length; i++) {
let line = (i + 1) + '';
if (i < array.length) { }
for (let index in headerList) {
let head = headerList[index];
line += ',' + this.strRep(array[i][head]);
}
str += line + '\r\n';
}
return str;
}
strRep(data) {
if (typeof data == "string") {
let newData = data.replace(/,/g, " ");
return newData;
}
else if (typeof data == "undefined") {
return "-";
}
else if (typeof data == "number") {
return data.toString();
}
else {
return data;
}
}
expotToPdf() {
console.log(this.finalArr);
this.downloadPdf()
}
// downloadPdf() {
// let fileName =
// "Distance Report" +
// new Date().getTime() +
// PDF_EXTENSION;
// var pdfsize = "a2";
// var doc = new jsPDF("p", "pt", pdfsize);
// var f_date = moment(this.Fromdate).format('lll');
// var t_date =moment(this.todate).format('lll');
// var date_combine = f_date + ' to ' + t_date;
// // doc.setFontSize(30);
// doc.setFontSize(15);
// doc.text('Distance Report ', 20, 30);
// // doc.text(date_combine, 250, 60);
// doc.setFontStyle("arial");
// var header = function(data) {
// doc.setFontSize(15);
// doc.setTextColor(40);
// doc.setFontStyle('normal');
// //doc.addImage(headerImgData, 'JPEG', data.settings.margin.left, 20, 50, 50);
// // doc.text("Testing Report", data.settings.margin.left, 50);
// };
// var options = {
// beforePageContent: header,
// margin: {
// top: 120
// },
// startY: doc.autoTableEndPosY() + 20
// };
// doc.autoTable({
// head: this.headRows(),
// // margin: { top: 80 },
// body: this.bodyRows(this.finalArr.length, this.finalArr),
// options
// });
// doc.save(fileName);
// }
startAddress;
endAddress;
f_date
t_date
downloadPdf() {
var outerThis = this
let fileName =
"Current Position Report" +
new Date() +
PDF_EXTENSION;
var pdfsize = "a2";
var totalPagesExp = "{total_pages_count_string}";
outerThis.startAddress = outerThis.finalArr[0].address;
outerThis.endAddress = outerThis.finalArr[outerThis.finalArr.length - 1].address
var doc = new jsPDF("p", "pt", pdfsize);
// outerThis.f_date = moment(this.Fromdate).format('lll');
// outerThis.t_date =moment(this.todate).format('lll');
// var date_combine = f_date + ' to ' + t_date;
// doc.setFontSize(30);
var pageHeight = doc.internal.pageSize.height || doc.internal.pageSize.getHeight();
var pageWidth = doc.internal.pageSize.width || doc.internal.pageSize.getWidth();
doc.setFontSize(15);
// doc.text(60, 20, 'Travel Path Report (Date='+date_combine+') Device Name='+this.device_name,);
doc.text("Current Position Report", 500, 30);
doc.setFontStyle("arial");
var header = function (data) {
doc.setFontSize(30);
doc.setTextColor(40);
doc.setFontStyle('arial');
};
var options = {
beforePageContent: header,
margin: {
top: 120
},
startY: doc.autoTableEndPosY() + 20
};
var logo = localStorage.getItem('logo1');
outerThis.toDataURL(logo, function (dataUrl) {
doc.autoTable({
head: outerThis.headRows(),
// margin: { top: 80 },
// startY: doc.autoTable.previous.finalY + 200,
body: outerThis.bodyRows(outerThis.finalArr.length, outerThis.finalArr),
options,
styles: { overflow: 'linebreak' },
theme: 'grid',
didDrawPage: function (data) {
// Header
doc.setFontSize(20);
doc.setTextColor(40);
doc.setFontStyle('arial');
// logo=localStorage.getItem('logo1');
if (logo)
doc.addImage(dataUrl, 'JPEG', pageWidth - 100, 6, 75, 75);
doc.autoTable({
html: "#headerTable",
styles: { fontSize: 13, textColor: "[255,72,72]" },
margin: { bottom: 140, left: 40, right: 8, top: 40 },
theme: 'plain'
});
// Footer
var str = "Page " + doc.internal.getNumberOfPages()
// Total page number plugin only available in jspdf v1.0+
if (typeof doc.putTotalPages === 'function') {
str = str + " of " + totalPagesExp;
}
doc.setFontSize(10);
// jsPDF 1.4+ uses getWidth, <1.4 uses .width
var pageSize = doc.internal.pageSize;
var pageHeight = pageSize.height ? pageSize.height : pageSize.getHeight();
doc.text(str, data.settings.margin.left, pageHeight - 10);
},
margin: { top: 85 },
});
if (typeof doc.putTotalPages === 'function') {
doc.putTotalPages(totalPagesExp);
}
doc.save(fileName);
})
}
toDataURL(url, callback) {
var xhr = new XMLHttpRequest();
xhr.onload = function () {
var reader = new FileReader();
reader.onloadend = function () {
callback(reader.result);
}
reader.readAsDataURL(xhr.response);
};
xhr.open('GET', url);
xhr.responseType = 'blob';
xhr.send();
}
headRows() {
return [
// displayedColumns=['vehicleName','IMEI','totalDistance','fuel','ignOn','ignOff','idleTime','outOfReach','noGps','trips','maxSpeed','startLocation','endLocation','details'];
{
device_name:'Object',
time:'Time',
position:'Position',
speed:'Speed',
status:'Status'
}
];
}
bodyRows(rowCount, pdfBody) {
console.log(rowCount, pdfBody);
rowCount = rowCount || 10;
let body = [];
for (var j = 0; j < rowCount; j++) {
var expDate = pdfBody[j].last_ping_on ? (moment(new Date(pdfBody[j].last_ping_on)).format('lll')) : "";
body.push({
device_name: pdfBody[j].Device_Name,
time: expDate,
position: pdfBody[j].position,
speed: (pdfBody[j].last_speed ? pdfBody[j].last_speed : "0") + ' kph',
status: pdfBody[j].status,
});
}
return body;
}
}

View file

@ -0,0 +1,113 @@
<div style="top: 0;position: absolute;">
<app-all-menus></app-all-menus>
</div>
<div class="loading" *ngIf="Load">Loading&#8230;</div>
<div class="main">
<!-- <div class="card"> -->
<div class="topnav">
<a class="active">User Transfer</a>
<div class="search-container">
<form [formGroup]="searchForm" (ngSubmit)="submit()">
<input type="text" placeholder="Search by userId/phone" formControlName="imei"
[ngClass]="{ 'is-invalid': submitted && f.imei.errors }" name="imei">
<button type="submit"><i class="fa fa-search"></i></button>
<div *ngIf="submitted && f.imei.errors" class="invalid-feedback">
<div *ngIf="f.imei.errors.required">Please Enter UserId/Phone</div>
</div>
</form>
</div>
</div>
<!-- Name:[''],
email:[''],
Dealer:[''],
supAdmin:[''],
accountSuspended:[''],
user_id:[''],
created_on:[''],
expire_date:[''], -->
<div style="padding-left:16px">
<form [formGroup]="deviceForm" class="row g-3 mt-3">
<div class="col-md-4">
<label class="form-label">Name</label>
<input type="text" readonly formControlName="Name" class="form-control">
</div>
<div class="col-md-4">
<label class="form-label">Email</label>
<input type="text" readonly formControlName="email" class="form-control">
</div>
<div class="col-md-4">
<label class="form-label">User ID</label>
<input type="text" readonly formControlName="user_id" class="form-control">
</div>
<div class="col-md-4">
<label class="form-label">Super Admin</label>
<select id="distributer" multiple="multiple">
<option *ngFor="let item of ditributers" [value]="item._id" [selected] = "item._id === selectedSupAdmin">{{item.first_name?item.first_name:""}} {{item.last_name?item.last_name:""}}</option>
</select>
<!-- <input type="text" formControlName="superAdmin" class="form-control"> -->
</div>
<div class="col-md-4">
<label class="form-label">Dealer</label>
<select id="dealer" multiple="multiple">
<option *ngFor="let item of dealers" [value]="item._id" [selected] = "item._id === selectedDealer">{{item.first_name?item.first_name:""}} {{item.last_name?item.last_name:""}}</option>
</select>
<!-- <input type="text" readonly formControlName="dealaer" class="form-control"> -->
</div>
<!-- <div class="col-md-4">
<label class="form-label">Super Admin</label>
<input type="text" readonly formControlName="supAdmin" class="form-control">
</div> -->
<!-- <div class="col-md-4">
<label class="form-label">Account Suspended</label>
<input type="text" readonly formControlName="accountSuspended" class="form-control">
</div>
<div class="col-md-4">
<label class="form-label">Created On</label>
<input type="text" readonly formControlName="created_on" class="form-control">
</div>
<div class="col-md-4">
<label class="form-label">Expiry Date</label>
<input type="text" readonly formControlName="expire_date" class="form-control">
</div>
<div class="col-md-4">
<label class="form-label">Deleted</label>
<input type="text" readonly formControlName="DeletedUser" class="form-control">
</div> -->
<div *ngIf="deleteShow" class="col-md-12 text-center mt-4">
<button class="btn btn-danger" (click)="deleteDevice()">Save <i class="fa fa-save"></i></button>
</div>
<!-- <div *ngIf="deleted" class="col-md-12 text-center mt-4">
<button class="btn btn-danger" (click)="deleteDevicePermenatly()">Delete Permanatly <i
class="fa fa-trash"></i></button>
</div> -->
</form>
</div>
</div>
<!-- </div> -->

View file

@ -0,0 +1,96 @@
.main {
padding: 20px;
margin-top: 55px;
height: 90vh;
}
.topnav {
overflow: hidden;
background-color: #e9e9e9;
}
.topnav a {
float: left;
display: block;
color: black;
text-align: center;
padding: 14px 16px;
text-decoration: none;
font-size: 17px;
}
.topnav a:hover {
background-color: #ddd;
color: black;
}
.topnav a.active {
background-color: #2196f3;
/* color: blueviolet; */
width: 290px;
font-size: larger;
font-weight: 600;
}
.topnav .search-container {
float: right;
}
.topnav input[type="text"] {
padding: 6px;
margin-top: 8px;
font-size: 17px;
border: black;
}
.topnav .search-container button {
float: right;
padding: 6px 10px;
margin-top: 8px;
margin-right: 16px;
background: #ddd;
font-size: 17px;
border: none;
cursor: pointer;
}
.topnav .search-container button:hover {
background: blue;
}
@media screen and (max-width: 600px) {
.topnav .search-container {
float: none;
}
.topnav a,
.topnav input[type="text"],
.topnav .search-container button {
float: none;
display: block;
text-align: left;
width: 100%;
margin: 0;
padding: 14px;
}
.topnav input[type="text"] {
border: 1px solid #ccc;
}
}
.col-md-6 {
margin-top: 15px;
}
.ms-choice>div {
position: inherit !important;
}
.ms-choice>span {
position: inherit !important;
}
.ms-parent {
display: contents;
}

View file

@ -0,0 +1,25 @@
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { UserSettingComponent } from './user-setting.component';
describe('UserSettingComponent', () => {
let component: UserSettingComponent;
let fixture: ComponentFixture<UserSettingComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ UserSettingComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(UserSettingComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should be created', () => {
expect(component).toBeTruthy();
});
});

View file

@ -0,0 +1,309 @@
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { MdSnackBar } from '@angular/material';
import { ContactService } from '../contact.service';
declare var $: any;
declare var google: any, swal: any;
@Component({
selector: 'app-user-setting',
templateUrl: './user-setting.component.html',
styleUrls: ['./user-setting.component.scss']
})
export class UserSettingComponent implements OnInit {
emailId: any;
Load:Boolean=false;
searchForm: FormGroup;
deleteShow: boolean = false;
submitted = false;
userId: any;
deviceForm: FormGroup
data: any;
deleted: boolean = false;
dealers: any[];
ditributers: any;
selectedSupAdmin: any;
selectedDealer: any;
// @ViewChild(BaseChartDirective) public chart: BaseChartDirective;
constructor(private contactService: ContactService, private fb: FormBuilder, public snackBar: MdSnackBar) {
}
ngOnInit(): void {
this.searchForm = this.fb.group({
imei: ['', Validators.required]
})
// Name
// emial
// dealer
// superadmin
// isdeleted
// issuspended
// user id
// createdon
// expiredon
this.deviceForm = this.fb.group({
Name: [''],
email: [''],
Dealer: [''],
supAdmin: [''],
accountSuspended: [''],
user_id: [''],
created_on: [''],
expire_date: [''],
DeletedUser: ['']
// imei:[''],
// registrationNumber:[''],
// sim1:[''],
// sim2:[''],
// dealaer:[''],
// user:[''],
// deviceModel:[''],
// vehicleType:[''],
// expirationDate:[''],
// creationDate:[''],
// superAdmin:[''],
// lastRenewal:[''],
// status:[''],
// deleted:[''],
// deletedBy:[''],
// deletedAt:[''],
// deletedFrom:['']
// 352887076587769
})
this.emailId = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).email;
this.userId = JSON.parse(window.atob(window.localStorage.token.split('.')[1]))._id;
this.loadDropdown()
this.getDistributers();
var that = this
$("#distributer").change(function () {
// alert($(this).val());
console.log($(this).val());
var value = $(this).val();
that.selectedSupAdmin = value[0];
that.getDealers(that.selectedSupAdmin)
console.log(that.selectedSupAdmin);
// var prevSelect = $("#MultiSelect_Preview").select2();
// prevSelect.val($(this).val()).trigger('change');
});
$("#dealer").change(function () {
// var that = this
// alert($(this).val());
console.log($(this).val());
var value = $(this).val();
that.selectedDealer = value[0];
// that.getUsers(that.selectedDealer)
// that.getUser(that.selectedDealer)
console.log(that.selectedDealer);
// var prevSelect = $("#MultiSelect_Preview").select2();
// prevSelect.val($(this).val()).trigger('change');
});
}
loadDropdown() {
var script = document.createElement("script");
script.setAttribute("type", "text/javascript");
script.setAttribute("src", "https://unpkg.com/multiple-select@1.3.1/dist/multiple-select.min.js");
document.getElementsByTagName("head")[0].appendChild(script);
setTimeout(() => {
$('#distributer').multipleSelect({
width: 470,
placeholder: "Select Distributer",
filter: true,
single: true,
selectAll: false
})
}, 100);
setTimeout(() => {
$('#dealer').multipleSelect({
width: 470,
placeholder: "Select Dealer",
filter: true,
single: true,
selectAll: false
})
}, 100);
}
get f() { return this.searchForm.controls; }
getDistributers() {
this.Load=true;
this.contactService.getSuperAdminList().subscribe(res => {
this.ditributers = res;
this.loadDropdown()
this.Load = false;
},err=>{
this.Load = false;
})
}
getDealers(id) {
this.Load = true;
this.dealers = []
this.contactService.getDealersDetails(id).subscribe(res => {
this.dealers = res;
this.dealers = this.dealers.concat(this.ditributers);
this.loadDropdown()
this.Load = false;
}, err => {
this.Load = false;
})
}
selectSupAdmin(event) {
console.log(event.target.value);
this.getDealers(event.target.value)
}
submit() {
console.log(this.searchForm.value);
this.Load = true;
this.submitted = true;
// stop here if form is invalid
if (this.searchForm.invalid) {
return;
}
this.contactService.get('/users/searchUser?search=' + this.searchForm.value.imei).subscribe((res: any) => {
console.log(res);
this.Load = false;
this.data = res[0];
if (res.length != 0) {
this.deleteShow = true
if (res[0].DeletedUser) {
this.deleteShow = false;
this.deleted = true;
} else {
this.deleted = false;
}
this.selectedSupAdmin = res[0].supAdmin ? res[0].supAdmin._id : ''
this.selectedDealer = res[0].Dealer ? res[0].Dealer._id : ''
console.log(res[0].Dealer ? res[0].Dealer.last_name ? res[0].Dealer.last_name : "" : '');
var dealerFirst = res[0].Dealer ? res[0].Dealer.first_name ? res[0].Dealer.first_name : '' : '';
var dealerLast = res[0].Dealer ? res[0].Dealer.last_name ? res[0].Dealer.last_name : "" : ''
var supFirst = res[0].supAdmin ? res[0].supAdmin.first_name ? res[0].supAdmin.first_name : '' : ''
var supLast = res[0].supAdmin ? res[0].supAdmin.last_name ? res[0].supAdmin.last_name : '' : ''
// var dealer=res[0].Dealer?res[0].Dealer.first_name?res[0].Dealer.first_name:'':''+' '+res[0].Dealer?res[0].Dealer.last_name?res[0].Dealer.last_name:"":''
// var supAdm=res[0].supAdmin?res[0].supAdmin.first_name?res[0].supAdmin.first_name:'':''+' '+res[0].supAdmin?res[0].supAdmin.last_name?res[0].supAdmin.last_name:'':''
this.deviceForm.patchValue({
Name: [res[0].first_name ? res[0].first_name : '' + ' ' + res[0].last_name ? res[0].last_name : ''],
email: [res[0].email],
Dealer: [res[0].Dealer ? res[0].Dealer._id:''],
supAdmin: [res[0].supAdmin ? res[0].supAdmin._id : ''],
accountSuspended: [res[0].accountSuspended == true ? 'Yes' : 'No'],
user_id: [res[0].user_id],
created_on: [new Date(res[0].created_on)],
expire_date: [new Date(res[0].expire_date)],
DeletedUser: res[0].DeletedUser == true ? 'Yes' : 'No'
})
if (this.data.supAdmin)
this.getDealers(this.data.supAdmin._id);
} else {
this.deleteShow = false;
this.deviceForm.reset();
this.snackBar.open("No Data Found", '', {
duration: 4000,
});
}
this.Load = false;
}, err => {
this.Load = false;
})
}
deleteDevice() {
swal({
title: '<strong>Are you sure?</strong>',
icon: 'warning',
html: "You won't be able to revert this!",
showCloseButton: true,
focusConfirm: false,
// confirmButtonText: 'Reset today ODO',
confirmButtonText: 'Yes, save it!',
// cancelButtonText: 'Reset total ODO',
// cancelButtonAriaLabel: 'Thumbs down'
cancelButtonText: 'No, cancel!',
}).then((result: { value: boolean; }) => {
if (result) {
var deletePayload = {
_id: this.data._id,
Dealer: this.selectedDealer ? this.selectedDealer : this.data.Dealer ? this.data.Dealer._id:undefined,
supAdmin: this.selectedSupAdmin ? this.selectedSupAdmin : this.data.supAdmin ? this.data.supAdmin._id : undefined
}
console.log(deletePayload);
this.contactService.post('/users/updateUserFrom',deletePayload).subscribe(res => {
swal({
title: 'Transfered!',
html: 'Your file has been saved.',
icon: 'success'
})
this.deviceForm.reset();
}, err => {
console.log(err);
var message = JSON.parse(err._body)
swal({
title: 'Status: ' + err.status,
html: message.message,
icon: 'warning'
})
})
}
}
)
}
deleteDevicePermenatly() {
swal({
title: '<strong>Are you sure?</strong>',
icon: 'warning',
html: "User will be deleted permanantly",
showCloseButton: true,
focusConfirm: false,
// confirmButtonText: 'Reset today ODO',
confirmButtonText: 'Yes, delete it!',
// cancelButtonText: 'Reset total ODO',
// cancelButtonAriaLabel: 'Thumbs down'
cancelButtonText: 'No, cancel!',
}).then((result: { value: boolean; }) => {
if (result) {
this.contactService.permanentDeluser(this.data._id).subscribe(res => {
swal(
'Deleted',
'User Deleted',
'success'
)
this.deviceForm.reset();
})
}
}
)
}
}