commit b5525aef26d18b79488e132fb0571e150e373d36
Author: hlavja <hlavjah@gmail.com>
Date:   Thu May 6 11:39:33 2021 +0200

    Re #8850 - Ověření funkčnosti - implementované enpointy
    
    + new use case add position to unit
    * tweaking all calls to operations with units and sensors
    + adding sensor type enum from backend endpoint
    + some form validation :)
    - removing all endpoints from /senslog1

diff --git a/nginx.conf b/nginx.conf
index cd6e825..4e492fa 100644
--- a/nginx.conf
+++ b/nginx.conf
@@ -24,48 +24,6 @@ http {
       root   /usr/share/nginx/html;
     }
 
-    location /senslog1 {
-              proxy_set_header X-Forwarded-Host $host;
-              proxy_set_header X-Forwarded-Server $host;
-              proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
-              #proxy_pass http://<ContainerName>:<PortNumber>;
-              # In our case Container name is as we setup in docker-compose `beservice` and port 8080
-              proxy_pass http://51.15.45.95:8080;
-              proxy_max_temp_file_size "1024m";
-              proxy_read_timeout       "60s";
-
-              add_header X-Frame-Options SAMEORIGIN always;
-
-    }
-
-    location /senslog-lite2/rest {
-              proxy_set_header X-Forwarded-Host $host;
-              proxy_set_header X-Forwarded-Server $host;
-              proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
-              #proxy_pass http://<ContainerName>:<PortNumber>;
-              # In our case Container name is as we setup in docker-compose `beservice` and port 8080
-              proxy_pass http://51.15.45.95:8080;
-              proxy_max_temp_file_size "1024m";
-              proxy_read_timeout       "60s";
-
-              add_header X-Frame-Options SAMEORIGIN always;
-
-    }
-
-    location /api/SensLogV1/OGCSensorThings {
-              proxy_set_header X-Forwarded-Host $host;
-              proxy_set_header X-Forwarded-Server $host;
-              proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
-              #proxy_pass http://<ContainerName>:<PortNumber>;
-              # In our case Container name is as we setup in docker-compose `beservice` and port 8080
-              proxy_pass http://51.15.45.95:9080;
-              proxy_max_temp_file_size "1024m";
-              proxy_read_timeout       "60s";
-
-              add_header X-Frame-Options SAMEORIGIN always;
-
-    }
-
     location /analytics {
               proxy_set_header X-Forwarded-Host $host;
               proxy_set_header X-Forwarded-Server $host;
diff --git a/proxy-config.json b/proxy-config.json
index 99b1564..dacd2f7 100644
--- a/proxy-config.json
+++ b/proxy-config.json
@@ -1,16 +1,4 @@
 {
-  "/senslog1": {
-    "target": "http://51.15.45.95:8080",
-    "secure": false
-  },
-  "/senslog-lite2/rest": {
-    "target": "http://51.15.45.95:8080",
-    "secure": false
-  },
-  "/api/SensLogV1/OGCSensorThings": {
-    "target": "http://51.15.45.95:9080",
-    "secure": false
-  },
   "/analytics": {
     "target": "http://51.15.45.95:9090",
     "secure": false
diff --git a/src/app/auth/interceptors/auth.interceptor.ts b/src/app/auth/interceptors/auth.interceptor.ts
index d9c6095..00803ad 100644
--- a/src/app/auth/interceptors/auth.interceptor.ts
+++ b/src/app/auth/interceptors/auth.interceptor.ts
@@ -32,23 +32,18 @@ export class AuthInterceptor implements HttpInterceptor {
       return of(null);
     }
 
-    if (request.url.includes('DataService') || request.url.includes('GroupService') || request.url.includes('SensorService')){
-      request = request.clone({
-        setParams: {
-          user: localStorage.getItem(GlobalVariable.USER_NAME)
-        }
-      });
-    }
-
     console.log('Sending request!', request);
     return next.handle(request)
       .pipe(
         catchError(err => {
-          if ((err instanceof HttpErrorResponse && err.status === 504 || err.status === 502 || err.status === 401 ||
-            err.status === 0 || err.status === 500)) {
+          if ((err instanceof HttpErrorResponse && err.status === 502 || err.status === 401 ||
+            err.status === 0)) {
             console.log(err);
             this.toastService.showError(err.error);
             return this.handleError(request, next);
+          } else if ((err instanceof HttpErrorResponse && err.status === 500 || err.status === 504 || err.status === 500)) {
+            this.toastService.showError(err.error);
+            this.handle500Error(err);
           } else {
             return throwError(err);
           }
@@ -60,4 +55,9 @@ export class AuthInterceptor implements HttpInterceptor {
     this.authService.doLogout();
     return of(null);
   }
+
+  handle500Error(err: any) {
+    this.authService.redirectToDashboard();
+    return of(null);
+  }
 }
diff --git a/src/app/auth/services/auth.service.ts b/src/app/auth/services/auth.service.ts
index 88df5cd..4f7aa65 100644
--- a/src/app/auth/services/auth.service.ts
+++ b/src/app/auth/services/auth.service.ts
@@ -84,4 +84,8 @@ export class AuthService {
     localStorage.setItem(GlobalVariable.RIGHTS, userCookie.rightsID.toString());
     this.cookieService.set('user', username);
   }
+
+  redirectToDashboard() {
+    this.router.navigate(['/dashboard']);
+  }
 }
diff --git a/src/app/auth/states/user.state.ts b/src/app/auth/states/user.state.ts
index 7151e9d..148b16f 100644
--- a/src/app/auth/states/user.state.ts
+++ b/src/app/auth/states/user.state.ts
@@ -3,6 +3,7 @@ import {BehaviorSubject, Observable} from 'rxjs';
 import {User} from '../models/user';
 import {AuthService} from '../services/auth.service';
 import {LoginService} from '../../shared/api/endpoints/services/login.service';
+import {ToastService} from '../../shared/services/toast.service';
 
 @Injectable({
   providedIn: 'root'
@@ -11,7 +12,8 @@ export class UserState {
   private userState$: BehaviorSubject<User> = new BehaviorSubject<User>(null);
 
   constructor(
-    private loginService: LoginService
+    private loginService: LoginService,
+    private toastService: ToastService
   ) {}
 
   setUser(user: User): void {
@@ -28,8 +30,10 @@ export class UserState {
 
   getUser$(refresh: boolean = false): Observable<User> {
    if (this.userState$.getValue()){
-      this.loginService.getUserInfo().subscribe(res => this.userState$.next({...this.userState$.getValue(), userInfo: res}));
-    }
+      this.loginService.getUserInfo$Response().subscribe(res => {
+        this.userState$.next({...this.userState$.getValue(), userInfo: res.body});
+      }, err => this.toastService.showError(err.error.message));
+   }
     return this.userState$.asObservable();
   }
 
diff --git a/src/app/dashboard/components/dashboard.component.html b/src/app/dashboard/components/dashboard.component.html
index 9c36adf..449fad9 100644
--- a/src/app/dashboard/components/dashboard.component.html
+++ b/src/app/dashboard/components/dashboard.component.html
@@ -1,33 +1,30 @@
-<app-nav-bar></app-nav-bar>
+<app-nav-bar (emitNewUnit)="addUnit($event)"></app-nav-bar>
 
 <div class="container dashboard">
-<!--  <div class="row">-->
-<!--    <div class="col-md-6"></div>-->
-<!--    <div class="col-md-6 text-right">-->
-<!--      <p-button label="Add unit" icon="pi pi-cog" (onClick)="insertUnitPopup()"></p-button>-->
-<!--    </div>-->
-<!--  </div>-->
-<p-accordion>
-    <p-accordionTab *ngFor="let unit of units">
-      <p-header [className]="'dashboard-unit-wrapper'">
-        <div [className]="'row dashboard-unit'">
-          <div class="col-md-8"><h3>{{ unit.unit.description}}</h3></div>
-          <div class="col-md-4 text-right">
-            <p-button label="Sensors graph" icon="pi pi-chart-line" [routerLink]="['/dashboard/unit', unit.unit.unitId]"></p-button>
-            <p-splitButton *ngIf="loggedUser?.userInfo?.rightsId == 0 || loggedUser?.userInfo?.rightsId == 1" label="Add sensor" (onClick)="insertSensorPopup($event, unit.unit)" icon="pi pi-plus-circle" (onDropdownClick)="showItems($event, unit.unit)" [model]="items" styleClass="p-button-success"></p-splitButton>
+  <p-accordion>
+      <p-accordionTab *ngFor="let unit of units">
+        <p-header [className]="'dashboard-unit-wrapper'">
+          <div [className]="'row dashboard-unit'">
+            <div class="col-md-8"><h3>{{ unit.unit.description}}</h3></div>
+            <div class="col-md-4 text-right">
+              <p-button label="Sensors graph" icon="pi pi-chart-line" [routerLink]="['/dashboard/unit', unit.unit.unitId]"></p-button>
+              <p-splitButton *ngIf="loggedUser?.userInfo?.rightsId == 0 || loggedUser?.userInfo?.rightsId == 1" label="Add sensor" (onClick)="insertSensorPopup($event, unit.unit)"
+                             icon="pi pi-plus-circle" (onDropdownClick)="showItems($event, unit.unit)" [model]="items" styleClass="p-button-success"></p-splitButton>
+            </div>
           </div>
+        </p-header>
+        <div>
+          <ng-container *ngFor="let sensor of unit.sensors">
+            <app-sensors *ngIf="sensor" [sensor]="sensor" [unitId]="unit.unit.unitId" [phenomenons]="phenomenons" [loggedUser]="loggedUser" (emitSensorDeletion)="deleteSensor(unit.unit.unitId, $event)"></app-sensors>
+          </ng-container>
         </div>
-      </p-header>
-      <div>
-        <app-sensors *ngFor="let sensor of unit.sensors" [sensor]="sensor" [unitId]="unit.unit.unitId" [phenomenons]="phenomenons" [loggedUser]="loggedUser"></app-sensors>
-      </div>
-    </p-accordionTab>
-</p-accordion>
+      </p-accordionTab>
+  </p-accordion>
 </div>
 
-<app-unit-popup *ngIf="editedUnit" [(isVisible)]="showEditUnitPopup" [unit]="editedUnit"></app-unit-popup>
-<app-sensor-insert-popup *ngIf="editedUnit" [unit]="editedUnit" [(isVisible)]="showInsertSensorPopup" [phenomenons]="phenomenons"></app-sensor-insert-popup>
-
+<app-unit-popup *ngIf="showEditUnitPopup" [(isVisible)]="showEditUnitPopup" [unit]="editedUnit"></app-unit-popup>
+<app-sensor-insert-popup *ngIf="showInsertSensorPopup" [unit]="editedUnit" [(isVisible)]="showInsertSensorPopup" [phenomenons]="phenomenons" [sensorTypes]="sensorTypes" (emitNewSensor)="addSensors($event)"></app-sensor-insert-popup>
+<app-position-insert-popup *ngIf="showInsertPositionPopup" [unitId]="editedUnit.unitId" [(isVisible)]="showInsertPositionPopup"></app-position-insert-popup>
 
 
 <p-confirmDialog [style]="{width: '50vw'}" key="positionDialog" [position]="position" [baseZIndex]="10000" rejectButtonStyleClass="p-button-outlined"></p-confirmDialog>
diff --git a/src/app/dashboard/components/dashboard.component.ts b/src/app/dashboard/components/dashboard.component.ts
index 1e59973..7617a06 100644
--- a/src/app/dashboard/components/dashboard.component.ts
+++ b/src/app/dashboard/components/dashboard.component.ts
@@ -10,12 +10,12 @@ import {Phenomenon} from '../../shared/api/endpoints/models/phenomenon';
 import {SensorsService} from '../../shared/api/endpoints/services/sensors.service';
 import {ConfirmationService, MenuItem, MessageService} from 'primeng/api';
 import {ManagementService} from '../../shared/api/endpoints/services/management.service';
-import {InsertUnit} from '../../shared/api/endpoints/models/insert-unit';
 import {ToastService} from '../../shared/services/toast.service';
 import {map} from 'rxjs/operators';
 import {HttpResponse} from '@angular/common/http';
 import {AuthService} from '../../auth/services/auth.service';
 import {User} from '../../auth/models/user';
+import {SensorType} from '../../shared/api/endpoints/models/sensor-type';
 
 @Component({
   selector: 'app-dashboard',
@@ -32,7 +32,9 @@ export class DashboardComponent implements OnInit {
   editedUnit: Unit;
   showEditUnitPopup = false;
   showInsertSensorPopup = false;
+  showInsertPositionPopup = false;
   phenomenons: Phenomenon[];
+  sensorTypes: SensorType[];
 
   constructor(
     private dataService: DataService,
@@ -76,6 +78,9 @@ export class DashboardComponent implements OnInit {
 
   insertSensorPopup($event: any, unit: Unit) {
     $event.stopPropagation();
+    this.sensorService.getSensorTypes().subscribe(
+      response => this.sensorTypes = response
+    )
     this.showInsertSensorPopup = true;
     this.editedUnit = unit;
   }
@@ -87,7 +92,7 @@ export class DashboardComponent implements OnInit {
       header: 'Delete Unit Confirmation',
       icon: 'pi pi-info-circle',
       accept: () => {
-        // TODO this.processUnitDeletion(unit);
+        this.processUnitDeletion(unit);
       },
       reject: () => {
         this.toastService.operationRejected();
@@ -96,11 +101,16 @@ export class DashboardComponent implements OnInit {
     });
   }
 
-  processUnitDeletion(insertUnit: InsertUnit) {
-    this.managementService.deleteUnit$Response({body: {unit: insertUnit}}).pipe(
+  processUnitDeletion(unit: Unit) {
+    this.managementService.deleteUnit$Response({body: {
+      unit: {
+        unit_id: unit.unitId
+      }}
+    }).pipe(
       map((response: HttpResponse<any>) => {
         if (response.status === 200) {
           this.toastService.showSuccessMessage(response.body.message);
+          this.units = this.units.filter(testedUnit => testedUnit.unit.unitId !== unit.unitId);
         } else {
         }
       })
@@ -114,10 +124,59 @@ export class DashboardComponent implements OnInit {
           event.stopPropagation();
           this.editUnitPopup($event, unit);
         }},
+      {label: 'Insert position', icon: 'pi pi-cog', command: () => {
+          event.stopPropagation();
+          this.insertPosition($event, unit);
+        }},
       {label: 'Delete unit', icon: 'pi pi-times', command: () => {
           event.stopPropagation();
           this.deleteUnit($event, unit);
         }}
     ]
   }
+
+  addUnit(inserted: any) {
+    const sensors: Sensor[] = [];
+    inserted.sensors.forEach(sens => {
+      sensors.push({
+        sensorId: sens.sensor_id,
+        sensorType: sens.sensor_type,
+        sensorName: sens.sensor_name,
+        phenomenon: {
+          phenomenonId: sens.phenomenon.phenomenon_id.toString()
+        }
+      })
+    });
+    this.units.push({
+      unit: {
+        unitId: inserted.unit.unit_id,
+        description: inserted.unit.description
+      },
+      sensors
+    })
+  }
+
+  addSensors(inserted: any) {
+    inserted.sensors.forEach(sens => {
+      this.units.find(un => un.unit.unitId === inserted.unit.unit_id).sensors.push({
+        sensorId: sens.sensor_id,
+        sensorType: sens.sensor_type,
+        sensorName: sens.sensor_name,
+        phenomenon: {
+          phenomenonId: sens.phenomenon.phenomenon_id.toString()
+        }
+      })
+    });
+  }
+
+  deleteSensor(unitId: number, sensor: Sensor) {
+    this.units.find(unit => unit.unit.unitId === unitId).sensors =
+      this.units.find(unit => unit.unit.unitId === unitId).sensors.filter(testedSensor => testedSensor.sensorId !== sensor.sensorId);
+  }
+
+  private insertPosition($event: any, unit: Unit) {
+    $event.stopPropagation();
+    this.showInsertPositionPopup = true;
+    this.editedUnit = unit;
+  }
 }
diff --git a/src/app/dashboard/components/position-insert-popup/position-insert-popup.component.html b/src/app/dashboard/components/position-insert-popup/position-insert-popup.component.html
new file mode 100644
index 0000000..e0bd011
--- /dev/null
+++ b/src/app/dashboard/components/position-insert-popup/position-insert-popup.component.html
@@ -0,0 +1,83 @@
+<p-dialog [visible]="isVisible" [modal]="true" [closable]="false" [draggable]="false" header="Add position to unit!" [style]="{width: '70vw'}"
+          [baseZIndex]="10000" (onShow)="clearFormArray()">
+
+  <form [formGroup]="insertForm">
+    <div class="input-group form-group">
+      <div class="input-group-prepend">
+        <span class="input-group-text">Latitude</span>
+      </div>
+      <input type="number" formControlName="lat" class="form-control" id="lat"
+             placeholder="Latitude WGS-84 coordinates" step="0.0001" min="-90" max="90"/>
+      <div *ngIf="insertForm.get('lat').invalid &&
+        insertForm.get('lat').errors &&
+        (insertForm.get('lat').dirty || insertForm.get('lat').touched)">
+        <small class="text-danger"
+               *ngIf="insertForm.get('lat').hasError('required')">
+          This field is required.
+        </small>
+        <small class="text-danger"
+               *ngIf="insertForm.get('lat').hasError('min')">
+          The minimum value for this field is -90.
+        </small>
+        <small class="text-danger"
+               *ngIf="insertForm.get('lat').hasError('max')">
+          The minimum value for this field is 90.
+        </small>
+      </div>
+    </div>
+    <div class="input-group form-group">
+      <div class="input-group-prepend">
+        <span class="input-group-text">Longitude</span>
+      </div>
+      <input type="number" formControlName="lon" class="form-control" id="lon"
+             placeholder="Longitude WGS-84 coordinates" step="0.0001" min="-180" max="180"/>
+      <div *ngIf="insertForm.get('lon').invalid &&
+        insertForm.get('lon').errors &&
+        (insertForm.get('lon').dirty || insertForm.get('lon').touched)">
+        <small class="text-danger"
+               *ngIf="insertForm.get('lon').hasError('required')">
+          This field is required.
+        </small>
+        <small class="text-danger"
+               *ngIf="insertForm.get('lon').hasError('min')">
+          The minimum value for this field is -180.
+        </small>
+        <small class="text-danger"
+               *ngIf="insertForm.get('lon').hasError('max')">
+          The minimum value for this field is 180.
+        </small>
+      </div>
+    </div>
+    <hr>
+    <div class="input-group form-group">
+      <div class="input-group-prepend">
+        <span class="input-group-text">Altitude</span>
+      </div>
+      <input type="number" formControlName="alt" class="form-control" id="alt"
+             placeholder="Altitude in meters"/>
+    </div>
+    <div class="input-group form-group">
+      <div class="input-group-prepend">
+        <span class="input-group-text">Speed</span>
+      </div>
+      <input type="number" formControlName="speed" class="form-control" id="speed"
+             placeholder="Speed of the unit"/>
+    </div>
+    <div class="input-group form-group">
+      <div class="input-group-prepend">
+        <span class="input-group-text">Dilution</span>
+      </div>
+      <input type="number" formControlName="dop" class="form-control" id="dop"
+             placeholder="Dilution of precision"/>
+    </div>
+  </form>
+
+  <p-footer>
+    <div class="row justify-content-end align-items-center">
+      <div>
+        <p-button icon="pi pi-times" (click)="close()" label="Close" class="pr-2"></p-button>
+        <p-button icon="pi pi-check" (click)="processInsertion()" type="submit" label="Save" class="pr-2"></p-button>
+      </div>
+    </div>
+  </p-footer>
+</p-dialog>
diff --git a/src/app/dashboard/components/position-insert-popup/position-insert-popup.component.scss b/src/app/dashboard/components/position-insert-popup/position-insert-popup.component.scss
new file mode 100644
index 0000000..e69de29
diff --git a/src/app/dashboard/components/position-insert-popup/position-insert-popup.component.ts b/src/app/dashboard/components/position-insert-popup/position-insert-popup.component.ts
new file mode 100644
index 0000000..15d367f
--- /dev/null
+++ b/src/app/dashboard/components/position-insert-popup/position-insert-popup.component.ts
@@ -0,0 +1,73 @@
+import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
+import {FormArray, FormBuilder, FormGroup, Validators} from '@angular/forms';
+import {ManagementService} from '../../../shared/api/endpoints/services/management.service';
+import * as moment from 'moment-timezone';
+import {map} from 'rxjs/operators';
+import {HttpResponse} from '@angular/common/http';
+import {ToastService} from '../../../shared/services/toast.service';
+import {SensorsService} from '../../../shared/api/endpoints/services/sensors.service';
+
+@Component({
+  selector: 'app-position-insert-popup',
+  templateUrl: './position-insert-popup.component.html',
+  styleUrls: ['./position-insert-popup.component.scss']
+})
+export class PositionInsertPopupComponent implements OnInit {
+
+  insertForm: FormGroup;
+
+  @Input() isVisible;
+  @Input() unitId;
+  @Output() isVisibleChange: EventEmitter<boolean> = new EventEmitter<boolean>();
+
+  constructor(
+    private formBuilder: FormBuilder,
+    private sensorService: SensorsService,
+    private toastService: ToastService,
+  ) {
+    this.initForm();
+  }
+
+  ngOnInit(): void {
+  }
+  initForm() {
+    this.insertForm = this.formBuilder.group({
+      lat: ['', [Validators.required, Validators.min(-90), Validators.max(90)]],
+      lon: ['', [Validators.required, Validators.min(-180), Validators.max(180)]],
+      alt: '',
+      speed: '',
+      dop: ''
+    });
+  }
+
+  clearFormArray() {
+    this.insertForm.reset();
+  }
+
+  processInsertion() {
+    if (this.insertForm.valid) {
+      const lat = this.insertForm.controls.lat.value;
+      const lon = this.insertForm.controls.lon.value;
+      const alt = this.insertForm.controls.alt.value;
+      const speed = this.insertForm.controls.speed.value;
+      const dop = this.insertForm.controls.dop.value;
+
+      this.sensorService.insertPosition$Response( {
+        lat, lon, alt, speed, dop, unit_id: this.unitId, date: moment().format('yyyy-MM-DD HH:mm:ssZZ')
+      }).pipe(
+        map((response: HttpResponse<any>) => {
+          if (response.status === 200) {
+            this.toastService.showSuccessMessage('Position to unit ' + this.unitId + ' inserted!');
+            this.close();
+          } else {
+            this.toastService.showError('Position insertion caused error!');
+          }
+        })
+      ).toPromise().then().catch(err => this.toastService.showError(err.error.message));
+    }
+  }
+
+  close() {
+    this.isVisibleChange.emit(false);
+  }
+}
diff --git a/src/app/dashboard/components/sensor-insert-popup/sensor-insert-popup.component.html b/src/app/dashboard/components/sensor-insert-popup/sensor-insert-popup.component.html
index 7a8f11c..6c8b3b6 100644
--- a/src/app/dashboard/components/sensor-insert-popup/sensor-insert-popup.component.html
+++ b/src/app/dashboard/components/sensor-insert-popup/sensor-insert-popup.component.html
@@ -22,8 +22,11 @@
           <div class="input-group-prepend">
             <span class="input-group-text">Sensor type</span>
           </div>
-          <input type="text" formControlName="sensorType" class="form-control" id="sensorType"
-                 placeholder="sensorType"/>
+          <select formControlName="sensorType" id="sensorType">
+            <option *ngFor="let sensorType of sensorTypes; let i = index" [value]="sensorTypes[i].sensorType">
+              {{sensorTypes[i].sensorType}}
+            </option>
+          </select>
         </div>
         <div class="input-group form-group">
           <div class="input-group-prepend">
@@ -45,8 +48,8 @@
   <p-footer>
     <div class="row justify-content-end align-items-center">
       <div>
-        <p-button icon="pi pi-check" (click)="processSensorInsertion()" type="submit" label="Uložit" class="pr-2"></p-button>
-        <p-button icon="pi pi-times" (click)="close()" label="Zavřít" class="pr-2"></p-button>
+        <p-button icon="pi pi-times" (click)="close()" label="Close" class="pr-2"></p-button>
+        <p-button icon="pi pi-check" (click)="processSensorInsertion()" type="submit" label="Save" class="pr-2"></p-button>
       </div>
     </div>
   </p-footer>
diff --git a/src/app/dashboard/components/sensor-insert-popup/sensor-insert-popup.component.ts b/src/app/dashboard/components/sensor-insert-popup/sensor-insert-popup.component.ts
index 2bede41..58c70f9 100644
--- a/src/app/dashboard/components/sensor-insert-popup/sensor-insert-popup.component.ts
+++ b/src/app/dashboard/components/sensor-insert-popup/sensor-insert-popup.component.ts
@@ -6,6 +6,8 @@ import {InsertSensor} from '../../../shared/api/endpoints/models/insert-sensor';
 import {map} from 'rxjs/operators';
 import {HttpResponse} from '@angular/common/http';
 import {ToastService} from '../../../shared/services/toast.service';
+import {SensorType} from '../../../shared/api/endpoints/models/sensor-type';
+import {Phenomenon} from '../../../shared/api/endpoints/models/phenomenon';
 
 @Component({
   selector: 'app-sensor-insert-popup',
@@ -17,10 +19,13 @@ export class SensorInsertPopupComponent implements OnInit {
   insertForm: FormGroup;
   items: FormArray;
 
-  @Input() phenomenons;
+  @Input() phenomenons: Phenomenon[];
   @Input() isVisible;
   @Input() unit;
+  @Input() sensorTypes: SensorType[];
   @Output() isVisibleChange: EventEmitter<boolean> = new EventEmitter<boolean>();
+  @Output() emitNewSensor: EventEmitter<{unit: InsertUnit, sensors: InsertSensor[]}> =
+    new EventEmitter<{unit: InsertUnit, sensors: InsertSensor[]}>()
 
   constructor(
     private formBuilder: FormBuilder,
@@ -86,15 +91,16 @@ export class SensorInsertPopupComponent implements OnInit {
         sensors.push(sensor);
       });
 
-      /* TODO this.managementService.insertSensor$Response({body: {unit, sensors}}).pipe(
+      this.managementService.insertSensor$Response({body: {unit, sensors}}).pipe(
         map((response: HttpResponse<any>) => {
           if (response.status === 200) {
             this.toastService.showSuccessMessage('Sensors inserted to unit!');
-            this.close()
+            this.emitNewSensor.emit({unit, sensors});
+            this.close();
           } else {
           }
         })
-      ).toPromise().then().catch(err => this.toastService.showError(err.error.message));*/
+      ).toPromise().then().catch(err => this.toastService.showError(err.error.message));
     }
   }
 }
diff --git a/src/app/dashboard/components/sensor-popup/sensor-popup.component.html b/src/app/dashboard/components/sensor-popup/sensor-popup.component.html
index 64ffaf3..aa25847 100644
--- a/src/app/dashboard/components/sensor-popup/sensor-popup.component.html
+++ b/src/app/dashboard/components/sensor-popup/sensor-popup.component.html
@@ -28,11 +28,9 @@
       </div>
   </form>
   <p-footer>
-    <div class="row justify-content-end align-items-center">
       <div>
-        <p-button icon="pi pi-check" (click)="processSensorEdition()" type="submit" label="Uložit" class="pr-2"></p-button>
-        <p-button icon="pi pi-times" (click)="close()" label="Zavřít" class="pr-2"></p-button>
+        <p-button icon="pi pi-times" (click)="close()" label="Close" class="pr-2"></p-button>
+        <p-button icon="pi pi-check" (click)="processSensorEdition()" type="submit" label="Save" class="pr-2"></p-button>
       </div>
-    </div>
   </p-footer>
 </p-dialog>
diff --git a/src/app/dashboard/components/sensor-popup/sensor-popup.component.ts b/src/app/dashboard/components/sensor-popup/sensor-popup.component.ts
index 877b3dc..aa7f7e6 100644
--- a/src/app/dashboard/components/sensor-popup/sensor-popup.component.ts
+++ b/src/app/dashboard/components/sensor-popup/sensor-popup.component.ts
@@ -4,6 +4,7 @@ import {ManagementService} from '../../../shared/api/endpoints/services/manageme
 import {map} from 'rxjs/operators';
 import {HttpResponse} from '@angular/common/http';
 import {ToastService} from '../../../shared/services/toast.service';
+import {Sensor} from '../../../shared/api/endpoints/models/sensor';
 
 @Component({
   selector: 'app-sensor-popup',
@@ -15,7 +16,7 @@ export class SensorPopupComponent implements OnInit {
   insertForm: FormGroup;
 
   @Input() isVisible;
-  @Input() sensor;
+  @Input() sensor: Sensor;
   @Input() phenomenons;
   @Input() unitId;
   @Output() isVisibleChange: EventEmitter<boolean> = new EventEmitter<boolean>();
@@ -50,7 +51,7 @@ export class SensorPopupComponent implements OnInit {
 
   processSensorEdition() {
     if (this.insertForm.valid) {
-      /* TODO this.managementService.updateSensor$Response({body: {
+      this.managementService.updateSensor$Response({body: {
         unit: {
           unit_id: this.unitId
         },
@@ -60,7 +61,7 @@ export class SensorPopupComponent implements OnInit {
               sensor_type: this.insertForm.controls.sensorType.value,
               sensor_name: this.insertForm.controls.sensorName.value,
               phenomenon: {
-                phenomenon_id: this.insertForm.controls.phenomenon.value.phenomenonId
+                phenomenon_id: this.insertForm.controls.phenomenon.value
               }
             }
           ]
@@ -68,11 +69,18 @@ export class SensorPopupComponent implements OnInit {
        map((response: HttpResponse<any>) => {
          if (response.status === 200) {
            this.toastService.showSuccessMessage('Sensor ' + response.body.sensors[0].sensorName + ' updated!');
+           this.changeSensor();
            this.close()
          } else {
          }
        })
-     ).toPromise().then().catch(err => this.toastService.showError(err.error.message));*/
+     ).toPromise().then().catch(err => this.toastService.showError(err.error.message));
     }
   }
+
+  private changeSensor() {
+    this.sensor.sensorType = this.insertForm.controls.sensorType.value;
+    this.sensor.sensorName = this.insertForm.controls.sensorName.value;
+    this.sensor.phenomenon.phenomenonId = this.insertForm.controls.phenomenon.value;
+  }
 }
diff --git a/src/app/dashboard/components/sensors/sensors.component.ts b/src/app/dashboard/components/sensors/sensors.component.ts
index f31f420..58706f7 100644
--- a/src/app/dashboard/components/sensors/sensors.component.ts
+++ b/src/app/dashboard/components/sensors/sensors.component.ts
@@ -1,4 +1,4 @@
-import {Component, Input, OnInit} from '@angular/core';
+import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
 import {Sensor} from '../../../shared/api/endpoints/models/sensor';
 import {ConfirmationService} from 'primeng/api';
 import {ManagementService} from '../../../shared/api/endpoints/services/management.service';
@@ -18,6 +18,7 @@ export class SensorsComponent implements OnInit {
   @Input() unitId: number;
   @Input() phenomenons;
   @Input() loggedUser: User;
+  @Output() emitSensorDeletion: EventEmitter<Sensor> = new EventEmitter<Sensor>()
   showSensorPopup = false;
   editedSensor: Sensor;
   constructor(
@@ -41,8 +42,7 @@ export class SensorsComponent implements OnInit {
       header: 'Delete Sensor Confirmation',
       icon: 'pi pi-info-circle',
       accept: () => {
-        console.log('ACCEPTED');
-        // TODO this.processSensorDeletion(sensor);
+        this.processSensorDeletion(sensor);
       },
       reject: () => {
         this.toastService.operationRejected();
@@ -65,6 +65,7 @@ export class SensorsComponent implements OnInit {
       map((response: HttpResponse<any>) => {
         if (response.status === 200) {
           this.toastService.showSuccessMessage(response.body.message);
+          this.emitSensorDeletion.emit(sensor);
         } else {
         }
       })
diff --git a/src/app/dashboard/components/unit-popup/unit-popup.component.html b/src/app/dashboard/components/unit-popup/unit-popup.component.html
index a307d5f..8df24e0 100644
--- a/src/app/dashboard/components/unit-popup/unit-popup.component.html
+++ b/src/app/dashboard/components/unit-popup/unit-popup.component.html
@@ -12,8 +12,8 @@
   <p-footer>
     <div class="row justify-content-end align-items-center">
       <div>
-        <p-button icon="pi pi-check" (click)="saveUnit()" type="submit" label="Save" class="pr-2"></p-button>
         <p-button icon="pi pi-times" (click)="close()" label="Close" class="pr-2"></p-button>
+        <p-button icon="pi pi-check" (click)="saveUnit()" type="submit" label="Save" class="pr-2"></p-button>
       </div>
     </div>
   </p-footer>
diff --git a/src/app/dashboard/components/unit-popup/unit-popup.component.ts b/src/app/dashboard/components/unit-popup/unit-popup.component.ts
index f2a5ccd..d6504f9 100644
--- a/src/app/dashboard/components/unit-popup/unit-popup.component.ts
+++ b/src/app/dashboard/components/unit-popup/unit-popup.component.ts
@@ -40,11 +40,19 @@ export class UnitPopupComponent implements OnInit {
   saveUnit() {
     if (this.insertForm.controls.unitDescription.value && this.insertForm.controls.unitDescription.value !== this.unit.description) {
       this.unit.description = this.insertForm.controls.unitDescription.value;
-      /*TODO this.managementService.updateUnit$Response({ body: { unit: this.unit}}).toPromise().then( res => {
-        if (res) {
+      this.managementService.updateUnit$Response({ body: {
+        unit: {
+            unit_id: this.unit.unitId,
+            description: this.unit.description
+          }}
+      }).toPromise().then( response => {
+        if (response.status === 200) {
           this.toastService.showSuccess();
+          this.close();
+        } else {
+          this.toastService.showError(response.body);
         }
-      }).catch(err => this.toastService.showError(err.body.message));*/
+      }).catch(err => this.toastService.showError(err.body.message));
     }
   }
 
diff --git a/src/app/dashboard/dashboard.module.ts b/src/app/dashboard/dashboard.module.ts
index a4cd14e..07429ea 100644
--- a/src/app/dashboard/dashboard.module.ts
+++ b/src/app/dashboard/dashboard.module.ts
@@ -13,11 +13,12 @@ import {ReactiveFormsModule} from '@angular/forms';
 import { SensorInsertPopupComponent } from './components/sensor-insert-popup/sensor-insert-popup.component';
 import {ConfirmDialogModule} from 'primeng/confirmdialog';
 import {SplitButtonModule} from 'primeng/splitbutton';
+import { PositionInsertPopupComponent } from './components/position-insert-popup/position-insert-popup.component';
 
 
 
 @NgModule({
-  declarations: [DashboardComponent, SensorsComponent, UnitPopupComponent, SensorPopupComponent, SensorInsertPopupComponent],
+  declarations: [DashboardComponent, SensorsComponent, UnitPopupComponent, SensorPopupComponent, SensorInsertPopupComponent, PositionInsertPopupComponent],
   imports: [
     CommonModule,
     NavBarModule,
diff --git a/src/app/sensor/components/sensor.component.ts b/src/app/sensor/components/sensor.component.ts
index 38bfeb0..9365157 100644
--- a/src/app/sensor/components/sensor.component.ts
+++ b/src/app/sensor/components/sensor.component.ts
@@ -2,7 +2,7 @@ import {Component, OnInit} from '@angular/core';
 import {ActivatedRoute} from '@angular/router';
 import * as moment from 'moment-timezone';
 import {AnalyticsService} from '../../shared/api/endpoints/services/analytics.service';
-import {AggreationModel} from '../../shared/models/aggreation.model';
+import {AggregationModel} from '../../shared/models/aggregationModel';
 import {GraphLoader} from '../../shared/graph-loading/graphloader';
 import {ObservationService} from '../../shared/api/endpoints/services/observation.service';
 import {HttpResponse} from '@angular/common/http';
@@ -24,7 +24,7 @@ export class SensorComponent implements OnInit {
   to: Date;
   today: Date;
   showAggregation = false;
-  aggregationFunction: AggreationModel[];
+  aggregationFunction: AggregationModel[];
   selectedAggregationFunction = 'HOUR';
 
   constructor(
diff --git a/src/app/shared/api/endpoints/models.ts b/src/app/shared/api/endpoints/models.ts
index 2c4f785..4621cf6 100644
--- a/src/app/shared/api/endpoints/models.ts
+++ b/src/app/shared/api/endpoints/models.ts
@@ -20,3 +20,4 @@ export { Data } from './models/data';
 export { Observation } from './models/observation';
 export { Statistics } from './models/statistics';
 export { OldObservation } from './models/old-observation';
+export { SensorType } from './models/sensor-type';
diff --git a/src/app/shared/api/endpoints/services/data.service.ts b/src/app/shared/api/endpoints/services/data.service.ts
index 63f4ed7..5a0f615 100644
--- a/src/app/shared/api/endpoints/services/data.service.ts
+++ b/src/app/shared/api/endpoints/services/data.service.ts
@@ -33,7 +33,7 @@ export class DataService extends BaseService {
   /**
    * Path part for operation getData
    */
-  static readonly GetDataPath = '/senslog1/DataService?Operation=GetUnits';
+  static readonly GetDataPath = '/senslog15/DataService?Operation=GetUnits';
 
   /**
    * Get data.
diff --git a/src/app/shared/api/endpoints/services/group.service.ts b/src/app/shared/api/endpoints/services/group.service.ts
index beff9c5..e568659 100644
--- a/src/app/shared/api/endpoints/services/group.service.ts
+++ b/src/app/shared/api/endpoints/services/group.service.ts
@@ -29,7 +29,7 @@ export class GroupService extends BaseService {
   /**
    * Path part for operation getGroups
    */
-  static readonly GetGroupsPath = '/senslog1/GroupService';
+  static readonly GetGroupsPath = '/senslog15/GroupService';
 
   /**
    * Get groups.
diff --git a/src/app/shared/api/endpoints/services/observation.service.ts b/src/app/shared/api/endpoints/services/observation.service.ts
index 55043a1..dd1f84f 100644
--- a/src/app/shared/api/endpoints/services/observation.service.ts
+++ b/src/app/shared/api/endpoints/services/observation.service.ts
@@ -29,7 +29,7 @@ export class ObservationService extends BaseService {
   /**
    * Path part for operation getObservation
    */
-  static readonly GetObservationPath = '/senslog1/SensorService?Operation=GetObservations';
+  static readonly GetObservationPath = '/senslog15/SensorService?Operation=GetObservations';
 
   /**
    * Get observation.
diff --git a/src/app/shared/api/endpoints/services/sensors.service.ts b/src/app/shared/api/endpoints/services/sensors.service.ts
index c2d2f4a..3e3bd9a 100644
--- a/src/app/shared/api/endpoints/services/sensors.service.ts
+++ b/src/app/shared/api/endpoints/services/sensors.service.ts
@@ -11,6 +11,7 @@ import { map, filter } from 'rxjs/operators';
 
 import { Phenomenon } from '../models/phenomenon';
 import { Sensor } from '../models/sensor';
+import { SensorType } from '../models/sensor-type';
 
 
 /**
@@ -30,7 +31,7 @@ export class SensorsService extends BaseService {
   /**
    * Path part for operation getUnitSensors
    */
-  static readonly GetUnitSensorsPath = '/senslog1/SensorService?Operation=GetSensors';
+  static readonly GetUnitSensorsPath = '/senslog15/SensorService?Operation=GetSensors';
 
   /**
    * Get unit sensors.
@@ -132,4 +133,127 @@ export class SensorsService extends BaseService {
     );
   }
 
+  /**
+   * Path part for operation getSensorTypes
+   */
+  static readonly GetSensorTypesPath = '/senslog15/SensorService?Operation=GetAllSensorTypes';
+
+  /**
+   * Get sensor types.
+   *
+   *
+   *
+   * This method provides access to the full `HttpResponse`, allowing access to response headers.
+   * To access only the response body, use `getSensorTypes()` instead.
+   *
+   * This method doesn't expect any request body.
+   */
+  getSensorTypes$Response(params?: {
+  }): Observable<StrictHttpResponse<Array<SensorType>>> {
+
+    const rb = new RequestBuilder(this.rootUrl, SensorsService.GetSensorTypesPath, 'get');
+    if (params) {
+    }
+
+    return this.http.request(rb.build({
+      responseType: 'json',
+      accept: 'application/json'
+    })).pipe(
+      filter((r: any) => r instanceof HttpResponse),
+      map((r: HttpResponse<any>) => {
+        return r as StrictHttpResponse<Array<SensorType>>;
+      })
+    );
+  }
+
+  /**
+   * Get sensor types.
+   *
+   *
+   *
+   * This method provides access to only to the response body.
+   * To access the full response (for headers, for example), `getSensorTypes$Response()` instead.
+   *
+   * This method doesn't expect any request body.
+   */
+  getSensorTypes(params?: {
+  }): Observable<Array<SensorType>> {
+
+    return this.getSensorTypes$Response(params).pipe(
+      map((r: StrictHttpResponse<Array<SensorType>>) => r.body as Array<SensorType>)
+    );
+  }
+
+  /**
+   * Path part for operation insertPosition
+   */
+  static readonly InsertPositionPath = '/senslog15/FeederServlet?Operation=InsertPosition';
+
+  /**
+   * Insert position to unit.
+   *
+   *
+   *
+   * This method provides access to the full `HttpResponse`, allowing access to response headers.
+   * To access only the response body, use `insertPosition()` instead.
+   *
+   * This method doesn't expect any request body.
+   */
+  insertPosition$Response(params: {
+    lat: number;
+    lon: number;
+    unit_id: number;
+    date: string;
+    alt?: string;
+    speed?: number;
+    dop?: number;
+  }): Observable<StrictHttpResponse<void>> {
+
+    const rb = new RequestBuilder(this.rootUrl, SensorsService.InsertPositionPath, 'get');
+    if (params) {
+      rb.query('lat', params.lat, {});
+      rb.query('lon', params.lon, {});
+      rb.query('unit_id', params.unit_id, {});
+      rb.query('date', params.date, {});
+      rb.query('alt', params.alt, {});
+      rb.query('speed', params.speed, {});
+      rb.query('dop', params.dop, {});
+    }
+
+    return this.http.request(rb.build({
+      responseType: 'text',
+      accept: '*/*'
+    })).pipe(
+      filter((r: any) => r instanceof HttpResponse),
+      map((r: HttpResponse<any>) => {
+        return (r as HttpResponse<any>).clone({ body: undefined }) as StrictHttpResponse<void>;
+      })
+    );
+  }
+
+  /**
+   * Insert position to unit.
+   *
+   *
+   *
+   * This method provides access to only to the response body.
+   * To access the full response (for headers, for example), `insertPosition$Response()` instead.
+   *
+   * This method doesn't expect any request body.
+   */
+  insertPosition(params: {
+    lat: number;
+    lon: number;
+    unit_id: number;
+    date: string;
+    alt?: string;
+    speed?: number;
+    dop?: number;
+  }): Observable<void> {
+
+    return this.insertPosition$Response(params).pipe(
+      map((r: StrictHttpResponse<void>) => r.body as void)
+    );
+  }
+
 }
diff --git a/src/app/shared/api/openapi.yaml b/src/app/shared/api/openapi.yaml
index 7d666fb..0db904e 100644
--- a/src/app/shared/api/openapi.yaml
+++ b/src/app/shared/api/openapi.yaml
@@ -88,7 +88,7 @@ paths:
             schema:
               $ref: '#/components/schemas/UserInfo'
 
-  /senslog1/SensorService?Operation=GetSensors:
+  /senslog15/SensorService?Operation=GetSensors:
     get:
       tags:
         - sensors
@@ -111,7 +111,7 @@ paths:
                   $ref: '#/components/schemas/Sensor'
 
 
-  /senslog1/SensorService?Operation=GetObservations:
+  /senslog15/SensorService?Operation=GetObservations:
     get:
       tags:
         - observation
@@ -148,7 +148,7 @@ paths:
         500:
           description: Internal server error
 
-  /senslog1/GroupService:
+  /senslog15/GroupService:
     get:
       tags:
       - group
@@ -180,7 +180,7 @@ paths:
                 items:
                   $ref: '#/components/schemas/Group'
 
-  /senslog1/DataService?Operation=GetUnits:
+  /senslog15/DataService?Operation=GetUnits:
     get:
       tags:
         - data
@@ -367,6 +367,22 @@ paths:
                 items:
                   $ref: '#/components/schemas/Phenomenon'
 
+  /senslog15/SensorService?Operation=GetAllSensorTypes:
+    get:
+      tags:
+        - sensors
+      summary: Get sensor types
+      operationId: getSensorTypes
+      responses:
+        200:
+          description: Getting all Sensor types
+          content:
+            application/json:
+              schema:
+                type: array
+                items:
+                  $ref: '#/components/schemas/SensorType'
+
   /senslog15/ManagementService?Operation=UpdateUnit:
     put:
       tags:
@@ -523,6 +539,51 @@ paths:
                 items:
                   $ref: '#/components/schemas/Right'
 
+  /senslog15/FeederServlet?Operation=InsertPosition:
+    get:
+      tags:
+        - sensors
+      parameters:
+        - in: query
+          name: lat
+          required: true
+          schema:
+            type: number
+        - in: query
+          name: lon
+          required: true
+          schema:
+            type: number
+        - in: query
+          name: unit_id
+          required: true
+          schema:
+            type: integer
+        - in: query
+          name: date
+          required: true
+          schema:
+            type: string
+        - in: query
+          name: alt
+          required: false
+          schema:
+            type: string
+        - in: query
+          name: speed
+          required: false
+          schema:
+            type: number
+        - in: query
+          name: dop
+          required: false
+          schema:
+            type: number
+      summary: Insert position to unit
+      operationId: insertPosition
+      responses:
+        200:
+          description: success
 
 components:
   schemas:
@@ -672,7 +733,7 @@ components:
           type: boolean
         is_moving:
           type: boolean
-    #TODO
+
     AlertEvents:
       type: array
 
@@ -685,10 +746,10 @@ components:
           $ref: '#/components/schemas/Attributes'
         position:
           $ref: '#/components/schemas/Position'
-    #TODO
+
     GeneralInfo:
       type: array
-    #TODO
+
     Drivers:
       type: array
 
@@ -752,6 +813,18 @@ components:
         value:
           type: number
 
+    SensorType:
+      type: object
+      properties:
+        phenomenon:
+          $ref: '#/components/schemas/Phenomenon'
+        sensorId:
+          type: integer
+        sensorName:
+          type: string
+        sensorType:
+          type: string
+
 
 
 
diff --git a/src/app/shared/models/aggreation.model.ts b/src/app/shared/models/aggreation.model.ts
deleted file mode 100644
index e873395..0000000
--- a/src/app/shared/models/aggreation.model.ts
+++ /dev/null
@@ -1,6 +0,0 @@
-/* tslint:disable */
-/* eslint-disable */
-export interface AggreationModel {
-  name?: string,
-  code?: string
-}
diff --git a/src/app/shared/models/aggregationModel.ts b/src/app/shared/models/aggregationModel.ts
new file mode 100644
index 0000000..cc21c3b
--- /dev/null
+++ b/src/app/shared/models/aggregationModel.ts
@@ -0,0 +1,6 @@
+/* tslint:disable */
+/* eslint-disable */
+export interface AggregationModel {
+  name?: string,
+  code?: string
+}
diff --git a/src/app/shared/models/vegaModel.ts b/src/app/shared/models/vegaModel.ts
new file mode 100644
index 0000000..92c69aa
--- /dev/null
+++ b/src/app/shared/models/vegaModel.ts
@@ -0,0 +1,6 @@
+/* tslint:disable */
+/* eslint-disable */
+export interface VegaModel {
+  sensordId?: string,
+  data?: []
+}
diff --git a/src/app/shared/nav-bar/components/nav-bar.component.html b/src/app/shared/nav-bar/components/nav-bar.component.html
index 7ff268d..d356143 100644
--- a/src/app/shared/nav-bar/components/nav-bar.component.html
+++ b/src/app/shared/nav-bar/components/nav-bar.component.html
@@ -36,4 +36,4 @@
 </div>
 
 <app-user-insert-popup *ngIf="showAddUserPopup" [(isVisible)]="showAddUserPopup"></app-user-insert-popup>
-<app-unit-insert-popup [(isVisible)]="showInsertUnitPopup" [phenomenons]="phenomenons"></app-unit-insert-popup>
+<app-unit-insert-popup [(isVisible)]="showInsertUnitPopup" [phenomenons]="phenomenons" (emitNewUnit)="addUnit($event)"></app-unit-insert-popup>
diff --git a/src/app/shared/nav-bar/components/nav-bar.component.ts b/src/app/shared/nav-bar/components/nav-bar.component.ts
index d471534..65d9e42 100644
--- a/src/app/shared/nav-bar/components/nav-bar.component.ts
+++ b/src/app/shared/nav-bar/components/nav-bar.component.ts
@@ -1,10 +1,12 @@
-import {Component, OnDestroy, OnInit} from '@angular/core';
+import {Component, EventEmitter, OnDestroy, OnInit, Output} from '@angular/core';
 import {AuthService} from '../../../auth/services/auth.service';
 import {User} from '../../../auth/models/user';
 import {Subscription} from 'rxjs';
 import {Right} from '../../api/endpoints/models/right';
 import {Phenomenon} from '../../api/endpoints/models/phenomenon';
 import {SensorsService} from '../../api/endpoints/services/sensors.service';
+import {InsertUnit} from '../../api/endpoints/models/insert-unit';
+import {InsertSensor} from '../../api/endpoints/models/insert-sensor';
 
 @Component({
   selector: 'app-nav-bar',
@@ -19,6 +21,8 @@ export class NavBarComponent implements OnInit, OnDestroy {
   rights: Right[];
   showInsertUnitPopup = false;
   phenomenons: Phenomenon[];
+  @Output() emitNewUnit: EventEmitter<{unit: InsertUnit, sensors: InsertSensor[]}> =
+    new EventEmitter<{unit: InsertUnit, sensors: InsertSensor[]}>()
   constructor(
     private authService: AuthService,
     private sensorService: SensorsService
@@ -55,4 +59,8 @@ export class NavBarComponent implements OnInit, OnDestroy {
   addUser() {
     this.showAddUserPopup = true;
   }
+
+  addUnit(inserted: any) {
+    this.emitNewUnit.emit(inserted);
+  }
 }
diff --git a/src/app/shared/nav-bar/components/unit-insert-popup/unit-insert-popup.component.html b/src/app/shared/nav-bar/components/unit-insert-popup/unit-insert-popup.component.html
index 1b2f4bc..013c6f0 100644
--- a/src/app/shared/nav-bar/components/unit-insert-popup/unit-insert-popup.component.html
+++ b/src/app/shared/nav-bar/components/unit-insert-popup/unit-insert-popup.component.html
@@ -7,6 +7,14 @@
         <span class="input-group-text">Unit ID</span>
       </div>
       <input type="text" formControlName="unitId" class="form-control" id="unitId" placeholder="unitId"/>
+      <div *ngIf="insertForm.get('unitId').invalid &&
+        insertForm.get('unitId').errors &&
+        (insertForm.get('unitId').dirty || insertForm.get('unitId').touched)">
+        <small class="text-danger"
+               *ngIf="insertForm.get('unitId').hasError('required')">
+          This field is required.
+        </small>
+      </div>
     </div>
     <div class="input-group form-group">
       <div class="input-group-prepend">
@@ -14,6 +22,60 @@
       </div>
       <input type="text" formControlName="unitDescription" class="form-control" id="unitDescription"
              placeholder="unitDescription"/>
+      <div *ngIf="insertForm.get('unitDescription').invalid &&
+        insertForm.get('unitDescription').errors &&
+        (insertForm.get('unitDescription').dirty || insertForm.get('unitDescription').touched)">
+        <small class="text-danger"
+               *ngIf="insertForm.get('unitDescription').hasError('required')">
+          This field is required.
+        </small>
+      </div>
+    </div>
+    <div class="input-group form-group">
+      <div class="input-group-prepend">
+        <span class="input-group-text">Latitude</span>
+      </div>
+      <input type="number" formControlName="lat" class="form-control" id="lat"
+             placeholder="Latitude WGS-84 coordinates" step="0.0001" min="-90" max="90"/>
+      <div *ngIf="insertForm.get('lat').invalid &&
+        insertForm.get('lat').errors &&
+        (insertForm.get('lat').dirty || insertForm.get('lat').touched)">
+        <small class="text-danger"
+               *ngIf="insertForm.get('lat').hasError('required')">
+          This field is required.
+        </small>
+        <small class="text-danger"
+               *ngIf="insertForm.get('lat').hasError('min')">
+          The minimum value for this field is -90.
+        </small>
+        <small class="text-danger"
+               *ngIf="insertForm.get('lat').hasError('max')">
+          The minimum value for this field is 90.
+        </small>
+      </div>
+    </div>
+    <div class="input-group form-group">
+      <div class="input-group-prepend">
+        <span class="input-group-text">Longitude</span>
+      </div>
+      <input type="number" formControlName="lon" class="form-control" id="lon"
+             placeholder="Longitude WGS-84 coordinates" step="0.0001" min="-180" max="180"/>
+      <div *ngIf="insertForm.get('lon').invalid &&
+        insertForm.get('lon').errors &&
+        (insertForm.get('lon').dirty || insertForm.get('lon').touched)">
+        <small class="text-danger"
+               *ngIf="insertForm.get('lon').hasError('required')">
+          This field is required.
+        </small>
+        <small class="text-danger"
+               *ngIf="insertForm.get('lon').hasError('min')">
+          The minimum value for this field is -180.
+        </small>
+        <small class="text-danger"
+               *ngIf="insertForm.get('lon').hasError('max')">
+          The minimum value for this field is 180.
+        </small>
+      </div>
     </div>
     <hr>
     <div class="input-group form-group">
@@ -62,8 +124,8 @@
   <p-footer>
     <div class="row justify-content-end align-items-center">
       <div>
-        <p-button icon="pi pi-check" (click)="processInsertion()" type="submit" label="Uložit" class="pr-2"></p-button>
-        <p-button icon="pi pi-times" (click)="close()" label="Zavřít" class="pr-2"></p-button>
+        <p-button icon="pi pi-times" (click)="close()" label="Close" class="pr-2"></p-button>
+        <p-button icon="pi pi-check" (click)="processInsertion()" type="submit" label="Save" class="pr-2"></p-button>
       </div>
     </div>
   </p-footer>
diff --git a/src/app/shared/nav-bar/components/unit-insert-popup/unit-insert-popup.component.ts b/src/app/shared/nav-bar/components/unit-insert-popup/unit-insert-popup.component.ts
index 1d18419..43e1674 100644
--- a/src/app/shared/nav-bar/components/unit-insert-popup/unit-insert-popup.component.ts
+++ b/src/app/shared/nav-bar/components/unit-insert-popup/unit-insert-popup.component.ts
@@ -8,6 +8,7 @@ import {InsertUnit} from '../../../api/endpoints/models/insert-unit';
 import {InsertSensor} from '../../../api/endpoints/models/insert-sensor';
 import {Phenomenon} from '../../../api/endpoints/models/phenomenon';
 import {SensorsService} from '../../../api/endpoints/services/sensors.service';
+import * as moment from 'moment-timezone';
 
 @Component({
   selector: 'app-unit-insert-popup',
@@ -22,6 +23,8 @@ export class UnitInsertPopupComponent implements OnInit {
   @Input()phenomenons: Phenomenon[];
   @Input() isVisible;
   @Output() isVisibleChange: EventEmitter<boolean> = new EventEmitter<boolean>();
+  @Output() emitNewUnit: EventEmitter<{unit: InsertUnit, sensors: InsertSensor[]}> =
+    new EventEmitter<{unit: InsertUnit, sensors: InsertSensor[]}>()
 
   constructor(
     private formBuilder: FormBuilder,
@@ -43,6 +46,8 @@ export class UnitInsertPopupComponent implements OnInit {
     this.insertForm = this.formBuilder.group({
       unitId: ['', [Validators.required]],
       unitDescription: ['', Validators.required],
+      lat: ['', [Validators.required, Validators.min(-90), Validators.max(90)]],
+      lon: ['', [Validators.required, Validators.min(-180), Validators.max(180)]],
       sensors: this.formBuilder.array([this.createSensor()])
     });
   }
@@ -72,6 +77,8 @@ export class UnitInsertPopupComponent implements OnInit {
 
   processInsertion() {
     if (this.insertForm.valid) {
+      const lat = this.insertForm.controls.lat.value;
+      const lon = this.insertForm.controls.lon.value;
       const unit: InsertUnit = {
         unit_id: this.insertForm.controls.unitId.value,
         description: this.insertForm.controls.unitDescription.value
@@ -94,8 +101,20 @@ export class UnitInsertPopupComponent implements OnInit {
       this.managementService.insertUnit$Response({ body: { unit, sensors}}).pipe(
         map((response: HttpResponse<any>) => {
           if (response.status === 200) {
-            this.toastService.showSuccessMessage('Unit ' + response.body.unitId + ' inserted!');
-            this.close()
+            this.sensorService.insertPosition$Response( {lat, lon, unit_id: this.insertForm.controls.unitId.value, date: moment().format('yyyy-MM-DD HH:mm:ssZZ')}).pipe(
+              map((response2: HttpResponse<any>) => {
+                if (response2.status === 200) {
+                  this.toastService.showSuccessMessage('Unit ' + response.body.unitId + ' inserted!');
+                  this.toastService.showSuccessMessage('Position to unit ' + response2.body.unitId + ' inserted!');
+                  this.emitNewUnit.emit({unit, sensors});
+                  this.close();
+                } else {
+                  this.toastService.showError('Unit insertion ' + response2.body.unitId + ' caused error! Wrong position!');
+                  this.managementService.deleteUnit({body: {unit}}).toPromise().then().catch(
+                    err => this.toastService.showError(err.error.message));
+                }
+              })
+            ).toPromise().then().catch(err => this.toastService.showError(err.error.message));
           } else {
           }
         })
diff --git a/src/app/shared/nav-bar/components/user-insert-popup/user-insert-popup.component.html b/src/app/shared/nav-bar/components/user-insert-popup/user-insert-popup.component.html
index 2acf842..8a31dd1 100644
--- a/src/app/shared/nav-bar/components/user-insert-popup/user-insert-popup.component.html
+++ b/src/app/shared/nav-bar/components/user-insert-popup/user-insert-popup.component.html
@@ -23,16 +23,16 @@
         <input type="text" formControlName="userRealName" class="form-control" id="userRealName"
                placeholder="User real name"/>
       </div>
-<!--      <div class="input-group form-group">
+      <div class="input-group form-group">
         <div class="input-group-prepend">
           <span class="input-group-text">Group</span>
         </div>
         <select formControlName="groups" id="groups">
           <option *ngFor="let group of groups; let i = index" [value]="groups[i].id">
-            {{group[i]?.group_name}}
+            {{groups[i].group_name}}
           </option>
         </select>
-      </div>-->
+      </div>
       <div class="input-group form-group">
         <div class="input-group-prepend">
           <span class="input-group-text">Role</span>
@@ -49,8 +49,8 @@
   <p-footer>
     <div class="row justify-content-end align-items-center">
       <div>
-        <p-button icon="pi pi-check" (click)="saveUser()" type="submit" label="Save" class="pr-2"></p-button>
         <p-button icon="pi pi-times" (click)="close()" label="Close" class="pr-2"></p-button>
+        <p-button icon="pi pi-check" (click)="saveUser()" type="submit" label="Save" class="pr-2"></p-button>
       </div>
     </div>
   </p-footer>
diff --git a/src/app/shared/nav-bar/components/user-insert-popup/user-insert-popup.component.ts b/src/app/shared/nav-bar/components/user-insert-popup/user-insert-popup.component.ts
index 463a3fd..98cb4c8 100644
--- a/src/app/shared/nav-bar/components/user-insert-popup/user-insert-popup.component.ts
+++ b/src/app/shared/nav-bar/components/user-insert-popup/user-insert-popup.component.ts
@@ -28,7 +28,7 @@ export class UserInsertPopupComponent implements OnInit {
     private toastService: ToastService
   ) {
     this.initForm();
-    // TODO this.getGroups();
+    this.getGroups();
   }
 
   ngOnInit(): void {
@@ -38,7 +38,6 @@ export class UserInsertPopupComponent implements OnInit {
     this.groupService.getGroups({Operation: 'GetGroups'}).pipe(
       tap(data => this.groups = data)
     ).subscribe();
-    console.log(this.groups);
   }
 
   getRights() {
@@ -58,7 +57,7 @@ export class UserInsertPopupComponent implements OnInit {
         userName: this.insertForm.controls.userName.value,
         rightsId: this.insertForm.controls.rights.value,
         userRealName: this.insertForm.controls.userRealName.value,
-        groupId: 2 // TODO
+        groupId: this.insertForm.controls.groups.value
         }
       }).pipe(
         map((response: HttpResponse<any>) => {
@@ -78,7 +77,7 @@ export class UserInsertPopupComponent implements OnInit {
       userName: ['', Validators.required],
       userPass: ['', Validators.required],
       userRealName: ['', Validators.required],
-      // TODO groups: ['', Validators.required],
+      groups: ['', Validators.required],
       rights: ['', Validators.required]
     });
   }
diff --git a/src/app/unit/components/unit.component.ts b/src/app/unit/components/unit.component.ts
index aed8bc2..e7a08e0 100644
--- a/src/app/unit/components/unit.component.ts
+++ b/src/app/unit/components/unit.component.ts
@@ -2,7 +2,7 @@ import {Component, OnInit} from '@angular/core';
 import {ActivatedRoute} from '@angular/router';
 import {AnalyticsService} from '../../shared/api/endpoints/services/analytics.service';
 import {map, tap} from 'rxjs/operators';
-import {AggreationModel} from '../../shared/models/aggreation.model';
+import {AggregationModel} from '../../shared/models/aggregationModel';
 import * as moment from 'moment-timezone';
 import {GraphLoader} from '../../shared/graph-loading/graphloader';
 import {SensorsService} from '../../shared/api/endpoints/services/sensors.service';
@@ -31,7 +31,7 @@ export class UnitComponent implements OnInit {
   selectedSensors = [];
   sensors: Sensor[];
   showAggregation = false;
-  aggregationFunction: AggreationModel[];
+  aggregationFunction: AggregationModel[];
   selectedAggregationFunction = 'HOUR';
 
   constructor(
@@ -53,11 +53,11 @@ export class UnitComponent implements OnInit {
         this.sensors = sensors;
         if (sensors) {
           sensors.forEach(sensor => {
-            const sensorType = sensor.sensorId.toString().slice(0, 2);
+            const sensorType = sensor.sensorId.toString().slice(0, 5);
             if (!this.sensorGroups.some(group => group === sensorType)) {
               this.sensorGroups.push(sensorType);
             }
-            if (!this.selectedSensors.some(sens => sens.toString().slice(0, 2) === sensorType)) {
+            if (!this.selectedSensors.some(sens => sens.toString().slice(0, 5) === sensorType)) {
               this.selectedSensors.push(sensor.sensorId);
             }
           })
@@ -111,7 +111,7 @@ export class UnitComponent implements OnInit {
         const objectKeys = Object.keys(data);
         for(const key of objectKeys ) {
           if (data[key].data) {
-            const view = '#vega_container_' + key.slice(0, 2);
+            const view = '#vega_container_' + key.slice(0, 5);
             if (this.selectedSensors.some(sens => sens.toString() === key)) {
               GraphLoader.getGraph(key, data[key].data, data[key].interval, view);
             }
