[65] #IMPLEMENT 'Export Functionality'
LocationBasedServices/maptology/angular-time-sheet-feature This commit looks good

{- Export function added (.csv, .json).
 - Minor fixes in layout and code. }
This commit is contained in:
Adriano Markovic
2020-02-12 23:52:14 +01:00
parent 0772ea42d8
commit 6bd1076e75
4 changed files with 309 additions and 204 deletions
@@ -448,10 +448,16 @@ export class ResourceService {
// TODO: Time Sheet labels DE
'time_sheet_title': 'Stundenzettel',
'time_sheet_table_date': 'Datum',
'time_sheet_table_from': 'von',
'time_sheet_table_to': 'bis',
'time_sheet_table_working_time': 'Arbeitszeit',
'time_sheet_table_place': 'Arbeitsplatz',
'time_sheet_table_device': 'Gerät',
'time_sheet_config_label': 'Konfiguration',
'time_sheet_toggle_default_label': 'Standard',
'time_sheet_toggle_acc_label': 'Akk.',
'time_sheet_toggle_by_days_label': 'Nach Tagen',
'time_sheet_toggle_raw_label': 'Rohdaten',
'time_sheet_select_device_label': 'Gerät',
'time_sheet_no_device_selected': 'Keins',
'time_sheet_break_time_label': 'Pausendauer',
@@ -904,10 +910,16 @@ export class ResourceService {
// TODO: Time Sheet labels EN
'time_sheet_title': 'Time Sheet',
'time_sheet_table_date': 'Date',
'time_sheet_table_from': 'from',
'time_sheet_table_to': 'to',
'time_sheet_table_working_time': 'Working Hours',
'time_sheet_table_place': 'Workplace',
'time_sheet_table_device': 'Device',
'time_sheet_config_label': 'Configuration',
'time_sheet_toggle_default_label': 'Default',
'time_sheet_toggle_acc_label': 'Acc.',
'time_sheet_toggle_by_days_label': 'By Days',
'time_sheet_toggle_raw_label': 'Raw',
'time_sheet_select_device_label': 'Device',
'time_sheet_no_device_selected': 'None',
'time_sheet_break_time_label': 'Break Time',
@@ -1,6 +1,7 @@
import { Injectable } from '@angular/core';
import { Time } from '@angular/common';
import { Time, formatDate } from '@angular/common';
import { HttpResponse } from '@angular/common/http';
import { MatTableDataSource, MatPaginator, MatSort } from '@angular/material';
import { BehaviorSubject } from 'rxjs';
import { SatDatepickerRangeValue } from 'saturn-datepicker';
@@ -8,7 +9,7 @@ import { SatDatepickerRangeValue } from 'saturn-datepicker';
import { Page } from '../utils/pagination';
import { ApiClientService } from '../../api';
import { VisitPage, Device, Place, Visit } from '../../api/models';
import { MatTableDataSource } from '@angular/material';
import { UserService } from './user.service';
export interface TimeSheetData {
@@ -23,20 +24,23 @@ export interface TimeSheetData {
}
export enum Grouping {
RAW = 1,
BY_DAY = 2,
BY_DAY_ACC = 3
DEFAULT = 1,
BY_DAY_ACC = 2,
BY_DAY = 3,
RAW = 4
}
// export interface TimeSheetPage {
// size: number;
// offset: number;
// total: number;
// elements: TimeSheet[];
// }
export enum ExportType {
CSV = '.csv',
JSON = '.json',
XML = '.xml'
}
type DateRange = { range?: SatDatepickerRangeValue<Date>, begin?: number, end?: number };
const COLUMN_SEPARATOR = ';';
const LINE_SEPARATOR = '\r\n';
@Injectable({
providedIn: 'root'
})
@@ -44,17 +48,14 @@ export class TimeSheetService extends MatTableDataSource<TimeSheetData> {
// export class TimeSheetService {
private static readonly BATCH_SIZE = 500;
private static readonly COLUMN_SEPARATOR = ';';
private static readonly LINE_SEPARATOR = '\r\n';
private static readonly DAY_IN_MILLI = 86_400_000;
private subscriptions = 0;
/* Properties representing the current progress in
* fetching Visit data from the server. */
fetching$ = new BehaviorSubject<boolean>(false);
error$ = new BehaviorSubject<boolean>(false);
private _visitsAvailable: boolean = false;
private visitsPage: VisitPage = TimeSheetService.emptyPage();
private request = 0;
@@ -67,7 +68,8 @@ export class TimeSheetService extends MatTableDataSource<TimeSheetData> {
* Remark: The prefixed _prev... values serve as a workaround
* for a known bug in angular, where mat-selection is fireing
* a "selectionChange" event twice when the selected value is null. */
private _grouped: Grouping = Grouping.RAW;
private _grouped: Grouping = Grouping.DEFAULT;
private _prevGrouped: Grouping = Grouping.DEFAULT;
private _device: Device = null;
private _prevDevice: Device = null;
private _breakTime: number = null;
@@ -76,15 +78,22 @@ export class TimeSheetService extends MatTableDataSource<TimeSheetData> {
private _workPlaces: Place[] = [];
/* Final data which is shown to the user. */
timeSheet$ = new BehaviorSubject<TimeSheetData[]>([]);
// timeSheet: TimeSheetData[] = [];
/** Creates an empty page. */
private static emptyPage() {
return { elements: [], offset: 0, total: -1, size: 0 };
}
constructor(private apiClientService: ApiClientService) {
super();
constructor(
private apiClientService: ApiClientService,
private userService: UserService
) {
super([]);
}
get isTimeSheetReady(): boolean {
return this.visitsAvailable === true && this.dateRange !== null && this.workPlaces.length > 0;
}
private get visitsAvailable(): boolean {
@@ -103,6 +112,9 @@ export class TimeSheetService extends MatTableDataSource<TimeSheetData> {
set grouped(grouped: Grouping) {
if (grouped != null) {
if (this._grouped !== grouped) {
if (this._grouped === Grouping.DEFAULT && this._breakTime)
this._breakTime = null;
this._prevGrouped = this._grouped;
this._grouped = grouped;
this.updateTimeSheet();
}
@@ -139,10 +151,12 @@ export class TimeSheetService extends MatTableDataSource<TimeSheetData> {
set dateRange(dateRange: SatDatepickerRangeValue<Date> | null) {
if (dateRange !== null) {
const beginMillis = dateRange.begin.getTime();
const endMillis = new Date(dateRange.end.getTime() + TimeSheetService.DAY_IN_MILLI).getTime();
this._dateRange = {
range: dateRange,
begin: Date.parse(dateRange.begin.toDateString()),
end: Date.parse(dateRange.end.toDateString())
begin: beginMillis,
end: endMillis
};
} else {
this._dateRange = {};
@@ -159,32 +173,33 @@ export class TimeSheetService extends MatTableDataSource<TimeSheetData> {
this.updateTimeSheet();
}
connect(): BehaviorSubject<TimeSheetData[]> {
this.subscriptions += 1;
this.startFetching();
return this.timeSheet$;
setup(paginator?: MatPaginator, sort?: MatSort): void{
this.paginator = paginator;
this.sort = sort;
this.fetchData();
}
disconnect(): void {
this.subscriptions -= 1;
reset(): void {
this.paginator = null;
this.sort = null;
this.resetService(false);
this.resetFilters();
}
startFetching(): void {
fetchData(): void {
if (this.fetching$.getValue()) return;
this.resetService(true);
this.fetchAllVisits(this.request);
}
resetService(isFetch: boolean): void {
private resetService(isFetch: boolean): void {
this.request += 1;
this.fetching$.next(isFetch);
this.visitsAvailable = false;
this.visitsPage = TimeSheetService.emptyPage();
}
resetFilters(): void {
private resetFilters(): void {
this._grouped = Grouping.RAW;
this._device = null;
this._breakTime = null;
@@ -234,7 +249,7 @@ export class TimeSheetService extends MatTableDataSource<TimeSheetData> {
private updateTimeSheet(): void {
let timeSheet: TimeSheetData[] = [];
if (this.visitsAvailable === true && this.dateRange !== null && this.workPlaces.length > 0) {
if (this.isTimeSheetReady) {
/* Filter all relevant places and dates. */
let filteredVisits = this.visitsPage.elements.filter((visit: Visit) => {
if (this._dateRange.begin <= visit.beginTime && visit.endTime < this._dateRange.end
@@ -249,8 +264,9 @@ export class TimeSheetService extends MatTableDataSource<TimeSheetData> {
/* Map filtered visits to TimeSheetData */
if (filteredVisits.length > 0) {
switch (this.grouped) {
case Grouping.RAW:
timeSheet = this.mapVisitsToTimeSheet(filteredVisits);
case Grouping.DEFAULT:
case Grouping.BY_DAY_ACC:
timeSheet = this.accumulateV2TsByDay(filteredVisits);
break;
case Grouping.BY_DAY:
let tsMap = this.mapV2TsByDay(filteredVisits);
@@ -259,16 +275,13 @@ export class TimeSheetService extends MatTableDataSource<TimeSheetData> {
timeSheet.push(...ts);
});
break;
case Grouping.BY_DAY_ACC:
timeSheet = this.accumulateV2TsByDay(filteredVisits);
case Grouping.RAW:
timeSheet = this.mapVisitsToTimeSheet(filteredVisits);
break;
}
console.log(timeSheet);
}
} else if (this.visitsAvailable === false && this.dateRange !== null && this.workPlaces.length > 0) {
// TODO: Implement process bar logic.
}
this.timeSheet$.next(timeSheet);
}
this.data = timeSheet;
}
/**
@@ -365,6 +378,7 @@ export class TimeSheetService extends MatTableDataSource<TimeSheetData> {
* representing a single day.
*
* @param visits Visits to map.
* @param workingTimeAcc Function to accumulate the working time.
* @returns List of accumulated TimeSheetData.
*/
private accumulateV2TsByDay(visits: Visit[]): TimeSheetData[] {
@@ -378,17 +392,6 @@ export class TimeSheetService extends MatTableDataSource<TimeSheetData> {
const latestEnd = tsList
.map((ts: TimeSheetData) => ts.endDate.getTime())
.reduce((prev, curr) => prev > curr ? prev : curr, Number.MIN_SAFE_INTEGER);
const accWorkingHours = tsList
.map((ts: TimeSheetData) => ts.workingTime)
.reduce((prev, curr) => {
prev.hours += curr.hours;
prev.minutes += curr.minutes;
return prev;
},
{ hours: 0, minutes: 0}
);
accWorkingHours.hours += Math.floor(accWorkingHours.minutes / 60);
accWorkingHours.minutes = accWorkingHours.minutes % 60;
const places = new Set<number>();
const devices = new Set<number>();
tsList.forEach((ts: TimeSheetData) => {
@@ -396,6 +399,52 @@ export class TimeSheetService extends MatTableDataSource<TimeSheetData> {
if (ts.deviceId) devices.add(ts.deviceId);
});
let accWorkingHours: Time;
if (Grouping.DEFAULT && this.breakTime !== null) {
const btThreshold = this.breakTime * 60_000;
accWorkingHours = tsList
.reduce(
(prev: { sheet?: TimeSheetData, skip: boolean, acc: Time }, curr: TimeSheetData) => {
// FIXME: The accumulation with the break time included is not working properly.
if (!prev.skip) {
if (prev) {
const breakDiff = curr.beginDate.getTime() - prev.sheet.endDate.getTime();
if (breakDiff <= btThreshold) {
const time = this.getWorkingTime(prev.sheet.beginDate.getTime(), curr.endDate.getTime());
prev.acc.hours += time.hours;
prev.acc.minutes += time.minutes;
prev.skip = true;
} else {
prev.acc.hours += curr.workingTime.hours;
prev.acc.minutes += curr.workingTime.minutes;
}
}
} else {
prev.skip = false;
}
// console.log('prev', prev);
// console.log('curr', curr);
prev.sheet = curr;
return prev;
},
{ sheet: null, skip: false, acc: { hours: 0, minutes: 0 }}
).acc;
} else {
accWorkingHours = tsList
.map((ts: TimeSheetData) => ts.workingTime)
.reduce((prev, curr) => {
prev.hours += curr.hours;
prev.minutes += curr.minutes;
return prev;
},
{ hours: 0, minutes: 0 }
);
}
accWorkingHours.hours += Math.floor(accWorkingHours.minutes / 60);
accWorkingHours.minutes = accWorkingHours.minutes % 60;
if (this.grouped == Grouping.DEFAULT && accWorkingHours.hours > 10)
accWorkingHours = { hours: 10, minutes: 0 };
timeSheet.push({
overlappingDays: false,
beginDate: new Date(erliestBegin),
@@ -431,55 +480,115 @@ export class TimeSheetService extends MatTableDataSource<TimeSheetData> {
return { hours, minutes };
}
// private getWorkingTime(millis: number): Time {
// let additionalTime = millis / 3_600_000;
// let hours = Math.floor(additionalTime);
// let minutes = Math.round(60 * (additionalTime - hours));
// if (minutes >= 60) {
// const additionalHours = Math.floor(minutes / 60)
// hours += additionalHours;
// minutes = minutes - (60 * additionalHours);
// }
// return { hours, minutes };
// }
getWorkplaceName(place: Place): string {
return (place.nickname != null && place.nickname.length > 0)? place.nickname : place.address;
}
// private generateZip(code: number) {
// const zip = new JSZip();
// const object = this;
// const devices = this.createDevices();
// const places = this.createPlaces();
// const visits = this.createVisits();
// if (devices != null) { zip.file('devices.csv', devices); }
// if (places != null) { zip.file('places.csv', places); }
// if (visits != null) { zip.file('visits.csv', visits); }
// zip.file('README.txt', this.createReadme());
// zip.generateAsync({type: 'blob'}).then( content => {
// object.finishZip(code, content);
// }, this.createErrorHandler(code));
// }
getWorkplaceString(data: TimeSheetData): string {
let res = '';
if (data.placeId) {
const place = this.workPlaces.find(place => place.id === data.placeId);
res = this.getWorkplaceName(place);
} else {
data.placesSet.forEach(id => {
const place = this.workPlaces.find(place => place.id === id);
res += this.getWorkplaceName(place) + ', '
});
res = res.slice(0, res.length - 2);
}
return res;
}
private createVisits(): string {
const visits = this.visitsPage.elements;
if (visits == null || visits.length === 0) { return null; }
getDate(data: TimeSheetData): string {
if (this.grouped == Grouping.RAW) {
let prefix = '';
let date = formatDate(data.endDate, 'dd.LL.yyyy', 'de');
if (data.overlappingDays) {
prefix = formatDate(data.beginDate, 'dd', 'de') + ' - ';
}
return prefix + date;
} else {
return formatDate(data.beginDate, 'dd.LL.yyyy', 'de');
}
}
exportTimeSheet(type: string): boolean {
let exportStr: string;
switch (type) {
case 'csv':
exportStr = this.createCSV();
break;
case 'json':
exportStr = this.createJSON();
break;
case 'xml':
exportStr = this.createXML();
break;
}
if (!exportStr) return false;
/* '\ufeff' -> UTF-8 Header Byte prepended. */
const blob = new Blob(['\ufeff', exportStr], { type: `text/${type};` });
const login = this.userService.getLogin();
let name = 'timesheet-export';
if (login != null) name += '-' + login;
name += '-' + Date.now();
this.saveAs(`${name}.${type}`, blob);
return true;
}
private saveAs(name: string, blob: Blob): void {
if (navigator.msSaveBlob) {
navigator.msSaveBlob(blob, name);
} else {
const link = document.createElement('a');
(<any>link).download = name;
link.href = URL.createObjectURL(blob);
link.click();
setTimeout(() => {
URL.revokeObjectURL(link.href);
link.remove();
}, 10);
}
}
private createCSV(): string | null {
if (this.data.length === 0)
return null;
let result = '';
result += 'ID' + TimeSheetService.COLUMN_SEPARATOR;
result += 'DEVICE_ID' + TimeSheetService.COLUMN_SEPARATOR;
result += 'PLACE_ID' + TimeSheetService.COLUMN_SEPARATOR;
result += 'BEGIN' + TimeSheetService.COLUMN_SEPARATOR;
result += 'END' + TimeSheetService.COLUMN_SEPARATOR;
result += 'CREATED' + TimeSheetService.COLUMN_SEPARATOR;
result += 'MODIFIED' + TimeSheetService.COLUMN_SEPARATOR;
result += TimeSheetService.LINE_SEPARATOR;
visits.forEach((visit) => {
result += visit.id + TimeSheetService.COLUMN_SEPARATOR;
result += visit.device + TimeSheetService.COLUMN_SEPARATOR;
result += visit.place + TimeSheetService.COLUMN_SEPARATOR;
result += visit.beginTime + TimeSheetService.COLUMN_SEPARATOR;
result += visit.endTime + TimeSheetService.COLUMN_SEPARATOR;
result += visit.creationTime + TimeSheetService.COLUMN_SEPARATOR;
result += visit.modificationTime + TimeSheetService.COLUMN_SEPARATOR;
result += TimeSheetService.LINE_SEPARATOR;
result += 'DATE' + COLUMN_SEPARATOR;
result += 'FROM' + COLUMN_SEPARATOR;
result += 'TO' + COLUMN_SEPARATOR;
result += 'WORKING_TIME' + COLUMN_SEPARATOR;
result += 'PLACES' + COLUMN_SEPARATOR;
result += LINE_SEPARATOR;
this.data.forEach((td: TimeSheetData) => {
result += this.getDate(td) + COLUMN_SEPARATOR;
result += formatDate(td.beginDate, 'H:mm', 'de') + COLUMN_SEPARATOR;
result += formatDate(td.endDate, 'H:mm', 'de') + COLUMN_SEPARATOR;
result += `${td.workingTime.hours} h ${td.workingTime.minutes} m` + COLUMN_SEPARATOR;
result += this.getWorkplaceString(td) + COLUMN_SEPARATOR;
result += LINE_SEPARATOR;
});
return result;
}
private createJSON(): string | null {
return JSON.stringify(
this.data.reduce((prev: object[], td: TimeSheetData) => {
prev.push({
date: this.getDate(td),
from: formatDate(td.beginDate, 'H:mm', 'de'),
to: formatDate(td.endDate, 'H:mm', 'de'),
workingTime: `${td.workingTime.hours} h ${td.workingTime.minutes} m`,
workplaces: this.getWorkplaceString(td)
});
return prev;
}, [])
);
}
private createXML(): string | null {
throw new Error('Not implemented yet');
}
}
@@ -83,57 +83,42 @@
}
</style>
<div fxLayout="column" fxLayoutAlign="start stretch" fxFlexFill>
<mat-toolbar style="margin-top:20px;background:transparent;">
<mat-toolbar style="background:transparent;">
<mat-toolbar-row style="flex: 1 1 auto;">
<div>
<mat-icon style="margin-left: 5px;">access_time_icon</mat-icon>
<span style="margin-left: 10px">{{ res.strings('time_sheet_title') }}</span>
<!-- <p style="margin-left: 5px;font-size: small;">{{ res.strings('time_sheet_subtitle') }}</p> -->
</div>
<div class="flex-spacer"></div>
<button mat-raised-button class="mat-elevation-z2"
*ngIf="isSidenavOpened; else iconUpdateButton"
color="primary" style="margin-right: 10px;"
(click)="updateTimeSheetTable()">
<mat-icon class="icon-button">update_icon</mat-icon>
<span>{{ res.strings('button_update') }}</span>
</button>
<ng-template #iconUpdateButton>
<button mat-mini-fab class="mat-elevation-z2"
color="primary" style="margin-right: 10px;"
(click)="updateTimeSheetTable()">
<mat-icon class="icon-button">update_icon</mat-icon>
<div>
<button mat-icon-button style="padding-right: 10px;" (click)="updateTimeSheetTable()">
<mat-icon>update_icon</mat-icon>
</button>
</ng-template>
<mat-menu #exportMenu="matMenu" class="mat-elevation-z2">
<ng-template matMenuContent>
<button mat-menu-item (click)="exportTimeSheet('.csv')" disabled>as CSV</button>
<button mat-menu-item (click)="exportTimeSheet('.json')" disabled>as JSON</button>
<button mat-menu-item (click)="exportTimeSheet('.xml')" disabled>as XML</button>
</ng-template>
</mat-menu>
<button mat-raised-button class="mat-elevation-z2"
*ngIf="isSidenavOpened; else iconExportButton"
[matMenuTriggerFor]="exportMenu"
color="primary">
<mat-icon class="icon-button">import_export</mat-icon>
<span>{{ res.strings('button_export') }}</span>
</button>
<ng-template #iconExportButton>
<button mat-mini-fab class="mat-elevation-z2"
[matMenuTriggerFor]="exportMenu"
color="primary">
<mat-icon class="icon-button">import_export</mat-icon>
<mat-menu #exportMenu="matMenu" class="mat-elevation-z1">
<ng-template matMenuContent>
<button mat-menu-item
(click)="exportTimeSheet('csv')"
[disabled]="!timeSheetService.isTimeSheetReady">as CSV</button>
<button mat-menu-item
(click)="exportTimeSheet('json')"
[disabled]="!timeSheetService.isTimeSheetReady">as JSON</button>
<!-- <button mat-menu-item
(click)="exportTimeSheet('xml')"
[disabled]="!timeSheetService.isTimeSheetReady">as XML</button> -->
</ng-template>
</mat-menu>
<button mat-icon-button style="margin-right: 10px;" [matMenuTriggerFor]="exportMenu">
<mat-icon>import_export</mat-icon>
</button>
</ng-template>
</div>
</mat-toolbar-row>
</mat-toolbar>
<!-- Page Content -->
<mat-sidenav-container style="flex: 1;">
<mat-sidenav-container style="flex: 1; overflow: hidden;">
<mat-sidenav class="mat-elevation-z4" role="region" position="end" mode="side" disableClose
[opened]="isSidenavOpened"
style="border-radius: 10px;">
@@ -143,12 +128,14 @@
<h3 mat-subheader>{{ res.strings('time_sheet_config_label') }}</h3>
</mat-list-item>
<mat-list-item fxLayoutAlign="center">
<mat-button-toggle-group
<mat-button-toggle-group
[(value)]="timeSheetService.grouped"
name="groupingChoice" aria-label="Grouping Choice">
<mat-button-toggle [value]="1">Normal</mat-button-toggle>
<mat-button-toggle [value]="2">Nach Tagen</mat-button-toggle>
<mat-button-toggle [value]="3">Akk.</mat-button-toggle>
name="groupingChoice"
aria-label="Grouping Choice">
<mat-button-toggle [value]="1">{{ res.strings('time_sheet_toggle_default_label') }}</mat-button-toggle>
<mat-button-toggle [value]="2">{{ res.strings('time_sheet_toggle_acc_label') }}</mat-button-toggle>
<mat-button-toggle [value]="3">{{ res.strings('time_sheet_toggle_by_days_label') }}</mat-button-toggle>
<mat-button-toggle [value]="4" hidden>{{ res.strings('time_sheet_toggle_raw_label') }}</mat-button-toggle>
</mat-button-toggle-group>
</mat-list-item>
</mat-list>
@@ -171,11 +158,12 @@
<mat-form-field>
<mat-label>{{ res.strings('time_sheet_break_time_label') }}</mat-label>
<mat-select
[(value)]="timeSheetService.breakTime">
<mat-option [value]="null">{{ res.strings('time_sheet_no_break_time_selected') }}</mat-option>
<mat-option *ngFor="let opt of breakTimeOptions" [value]="opt">
{{ opt }}
</mat-option>
[(value)]="timeSheetService.breakTime"
[disabled]="timeSheetService.grouped > 1">
<mat-option [value]="null">{{ res.strings('time_sheet_no_break_time_selected') }}</mat-option>
<mat-option *ngFor="let opt of breakTimeOptions" [value]="opt">
{{ opt }}
</mat-option>
</mat-select>
</mat-form-field>
</mat-list-item>
@@ -244,6 +232,15 @@
<mat-list-item fxLayoutAlign="center">
<h3 mat-subheader>{{ res.strings('time_sheet_config_label') }}</h3>
</mat-list-item>
<mat-list-item fxLayoutAlign="center">
<mat-button-toggle-group
[(value)]="timeSheetService.grouped"
name="groupingChoice"
aria-label="Grouping Choice">
<mat-button-toggle [value]="1">{{ res.strings('time_sheet_toggle_default_label') }}</mat-button-toggle>
<mat-button-toggle [value]="2">{{ res.strings('time_sheet_toggle_acc_label') }}</mat-button-toggle>
</mat-button-toggle-group>
</mat-list-item>
<mat-list-item fxLayoutAlign="center">
<mat-form-field>
<mat-label>{{ res.strings('time_sheet_select_device_label') }}</mat-label>
@@ -262,11 +259,12 @@
<mat-form-field>
<mat-label>{{ res.strings('time_sheet_break_time_label') }}</mat-label>
<mat-select
[(value)]="timeSheetService.breakTime">
<mat-option [value]="null">{{ res.strings('time_sheet_no_break_time_selected') }}</mat-option>
<mat-option *ngFor="let opt of breakTimeOptions" [value]="opt">
{{ opt }}
</mat-option>
[(value)]="timeSheetService.breakTime"
[disabled]="timeSheetService.grouped > 1">
<mat-option [value]="null">{{ res.strings('time_sheet_no_break_time_selected') }}</mat-option>
<mat-option *ngFor="let opt of breakTimeOptions" [value]="opt">
{{ opt }}
</mat-option>
</mat-select>
</mat-form-field>
</mat-list-item>
@@ -329,55 +327,52 @@
</ng-container>
<!-- Table Content -->
<!-- <ng-container *ngIf="loading.getValue() || deleting.getValue()"> -->
<ng-container *ngIf="false">
<mat-progress-bar mode="indeterminate" color="accent"></mat-progress-bar>
</ng-container>
<mat-card class="mat-elevation-z4" style="margin: 4px;">
<mat-card class="main-content mat-elevation-z4">
<mat-card-content>
<table mat-table #timeSheet [dataSource]="timeSheetDataSource">
<table mat-table #timeSheet [dataSource]="timeSheetDataSource" matSort>
<ng-container matColumnDef="date">
<th mat-header-cell *matHeaderCellDef>{{ res.strings('time_sheet_table_date') }}</th>
<th mat-header-cell *matHeaderCellDef mat-sort-header="date">{{ res.strings('time_sheet_table_date') }}</th>
<td mat-cell *matCellDef="let data">{{ getDate(data) }}</td>
</ng-container>
<ng-container matColumnDef="from-time">
<th mat-header-cell *matHeaderCellDef>{{ 'von' }}</th>
<th mat-header-cell *matHeaderCellDef>{{ res.strings('time_sheet_table_from') }}</th>
<td mat-cell *matCellDef="let data">
{{ data.beginDate | date:'H:mm' }}
</td>
</ng-container>
<ng-container matColumnDef="to-time">
<th mat-header-cell *matHeaderCellDef>{{ 'bis' }}</th>
<th mat-header-cell *matHeaderCellDef>{{ res.strings('time_sheet_table_to') }}</th>
<td mat-cell *matCellDef="let data">
{{ data.endDate | date:'H:mm' }}
</td>
</ng-container>
<ng-container matColumnDef="time">
<th mat-header-cell *matHeaderCellDef>{{ res.strings('time_sheet_table_working_time') }}</th>
<th mat-header-cell *matHeaderCellDef mat-sort-header>{{ res.strings('time_sheet_table_working_time') }}</th>
<td mat-cell *matCellDef="let data">{{ getWorkingTime(data.workingTime) }}</td>
</ng-container>
<ng-container matColumnDef="place">
<th mat-header-cell *matHeaderCellDef>{{ res.strings('time_sheet_table_place') }}</th>
<th mat-header-cell *matHeaderCellDef mat-sort-header>{{ res.strings('time_sheet_table_place') }}</th>
<td mat-cell *matCellDef="let data">{{ getWorkplaceString(data) }}</td>
</ng-container>
<ng-container matColumnDef="device">
<th mat-header-cell *matHeaderCellDef>{{ res.strings('time_sheet_table_device') }}</th>
<th mat-header-cell *matHeaderCellDef mat-sort-header>{{ res.strings('time_sheet_table_device') }}</th>
<td mat-cell *matCellDef="let data">{{ getDeviceNameString(data) }}</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns; sticky: true"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
<mat-paginator #paginator [pageSizeOptions]="[10, 20, 50, 100]" showFirstLastButtons></mat-paginator>
</mat-card-content>
<mat-card-footer>
<mat-paginator #paginator [pageSizeOptions]="[10, 20, 50, 100]" [showFirstLastButtons]="true"></mat-paginator>
</mat-card-footer>
</mat-card>
</mat-sidenav-content>
</mat-sidenav-container>
@@ -1,6 +1,6 @@
import { Component, OnInit, HostListener, ViewChild, OnDestroy, ElementRef } from '@angular/core';
import { Time, formatDate } from '@angular/common';
import { MatSidenav, MatPaginator, MatTableDataSource } from "@angular/material";
import { Component, OnInit, HostListener, ViewChild, OnDestroy, ElementRef, AfterViewInit } from '@angular/core';
import { Time } from '@angular/common';
import { MatSidenav, MatPaginator, MatTableDataSource, MatSort } from "@angular/material";
import { MatDialog } from "@angular/material/dialog";
import { CdkTable } from '@angular/cdk/table';
@@ -14,37 +14,38 @@ import { PaginationHandler, Page } from '../utils/pagination';
import { Device, Place } from '../../api/models';
enum ExportType {
CSV = '.csv',
JSON = '.json',
XML = '.xml'
}
@Component({
selector: 'app-time-sheet',
templateUrl: './time-sheet.component.html',
styles: [
'table { width: 100%; }',
'mat-sidenav { width: 350px }',
'mat-button-toggle { font-size: 14px; }'
'mat-button-toggle { font-size: 14px; }',
`.main-content {
margin: 4px;
padding-right: 16px;
padding-left: 16px;
padding-bottom: 8px;
padding-top: 8px;
}`
],
})
export class TimeSheetComponent implements OnInit, OnDestroy {
export class TimeSheetComponent implements OnInit, OnDestroy, AfterViewInit {
private static readonly SIDENAV_BREAKPOINT = 960;
readonly breakTimeOptions = [5, 10, 15, 20, 30, 45, 60, 90, 120, 150];
@ViewChild(MatSidenav, { static: true }) sidenav: MatSidenav;
@ViewChild('workPlacesTable', { read: CdkTable, static: false }) workPlacesTable: CdkTable<Place>;
@ViewChild(ElementRef, { static: true }) timeSheet: ElementRef;
@ViewChild(MatSort, { static: true }) sort: MatSort;
@ViewChild(MatPaginator, { static: true }) paginator: MatPaginator;
compact = false;
isSidenavOpened = true;
// TODO: Implement TableHandler Logic.
displayedColumns = ['date', 'from-time', 'to-time', 'time', 'device', 'place'];
compactDisplayCol = ['date', 'time'];
static readonly normalDisplayCol = ['date', 'from-time', 'to-time', 'time', 'device', 'place'];
static readonly compactDisplayCol = ['date', 'time'];
displayedColumns = TimeSheetComponent.normalDisplayCol;
workPlaces: Place[];
devices: Device[];
@@ -76,12 +77,15 @@ export class TimeSheetComponent implements OnInit, OnDestroy {
);
this.deviceService.reload();
this.timeSheetService.connect();
}
ngAfterViewInit(): void {
this.timeSheetService.setup(this.paginator, this.sort);
}
ngOnDestroy(): void {
this.deviceService.disconnect(null);
this.timeSheetService.disconnect();
this.timeSheetService.reset();
this.subscriptions.unsubscribe();
}
@@ -91,13 +95,15 @@ export class TimeSheetComponent implements OnInit, OnDestroy {
}
updateTimeSheetTable(): void {
if (!this.timeSheetService.fetching$.getValue())
this.timeSheetService.startFetching();
// if (!this.timeSheetService.fetching$.getValue())
// this.timeSheetService.fetchData();
console.log(this.sort);
}
exportTimeSheet(type: string): void {
// TODO: Implement.
console.log(type);
if (!this.timeSheetService.exportTimeSheet(type)) {
console.log('Did not export!');
}
}
openWorkPlacesDialog(): void {
@@ -110,22 +116,11 @@ export class TimeSheetComponent implements OnInit, OnDestroy {
}
getWorkplaceName(place: Place): string {
return (place.nickname != null && place.nickname.length > 0)? place.nickname : place.address;
return this.timeSheetService.getWorkplaceName(place);
}
getWorkplaceString(data: TimeSheetData): string {
let res = '';
if (data.placeId) {
const place = this.workPlaces.find(place => place.id === data.placeId);
res = this.getWorkplaceName(place);
} else {
data.placesSet.forEach(id => {
const place = this.workPlaces.find(place => place.id === id);
res += this.getWorkplaceName(place) + '; '
});
res = res.slice(0, res.length - 2);
}
return res;
return this.timeSheetService.getWorkplaceString(data);
}
getDeviceNameString(data: TimeSheetData): string {
@@ -163,16 +158,7 @@ export class TimeSheetComponent implements OnInit, OnDestroy {
}
getDate(data: TimeSheetData): string {
if (this.timeSheetService.grouped == Grouping.RAW) {
let prefix = '';
let date = formatDate(data.endDate, 'dd.LL.yyyy', 'de');
if (data.overlappingDays) {
prefix = formatDate(data.beginDate, 'dd', 'de') + ' - ';
}
return prefix + date;
} else {
return formatDate(data.beginDate, 'dd.LL.yyyy', 'de');
}
return this.timeSheetService.getDate(data);
}
private updateSidenav(width: number): void {
@@ -180,10 +166,13 @@ export class TimeSheetComponent implements OnInit, OnDestroy {
this.sidenav.close();
this.compact = true;
this.isSidenavOpened = false;
this.displayedColumns = TimeSheetComponent.compactDisplayCol;
this.timeSheetService.grouped = Grouping.BY_DAY_ACC;
} else if (width >= TimeSheetComponent.SIDENAV_BREAKPOINT && this.compact) {
this.compact = false;
this.sidenav.open();
this.isSidenavOpened = true;
this.displayedColumns = TimeSheetComponent.normalDisplayCol;
}
if (this.sidenav.opened !== this.isSidenavOpened) {
if (this.isSidenavOpened)