refactor: add opening hours

This commit is contained in:
Rainer Killinger
2021-08-03 15:02:59 +02:00
parent b89f5c4edd
commit bb8a9f6ba5
11 changed files with 204 additions and 36 deletions

View File

@@ -15,9 +15,15 @@
import {Injectable, OnDestroy, Pipe, PipeTransform} from '@angular/core';
import {LangChangeEvent, TranslateService} from '@ngx-translate/core';
import moment from 'moment';
import {Subscription} from 'rxjs';
import {logger} from '../_helpers/ts-logger';
// tslint:disable-next-line: no-var-requires
const openingHoursFn = require('opening_hours');
// tslint:disable: completed-docs
@Injectable()
@Pipe({
name: 'join',
@@ -89,6 +95,78 @@ export class StringSplitPipe implements PipeTransform {
}
}
@Injectable()
@Pipe({
name: 'openingHours',
pure: false, // required to update the value when the promise is resolved
})
export class OpeningHoursPipe implements PipeTransform {
locale: string;
onLangChange?: Subscription;
value = '';
constructor(private readonly translate: TranslateService) {
this.locale = translate.currentLang;
}
private _dispose(): void {
if (this.onLangChange?.closed === false) {
this.onLangChange?.unsubscribe();
}
}
transform(aString: string | unknown): string {
this.updateValue(aString);
this._dispose();
if (this.onLangChange?.closed === true) {
this.onLangChange = this.translate.onLangChange.subscribe((event: LangChangeEvent) => {
this.locale = event.lang;
this.updateValue(aString);
});
}
return this.value;
}
updateValue(aString: string | unknown) {
if (typeof aString !== 'string'){
logger.warn(`openingHours pipe unable to parse input: ${aString}`);
return;
}
const openingHours = new openingHoursFn(aString);
if ((openingHours.getWarnings() as string[]).length > 0){
logger.warn((openingHours.getWarnings() as string[]).join('. '));
return;
}
const isOpen: boolean = openingHours.getState();
const nextChange: Date = openingHours.getNextChange();
let prefixKey = isOpen ?
'common.openingHours.open_until' :
'common.openingHours.closed_until';
let formattedCalender = moment(nextChange)
.calendar();
if (moment(nextChange)
.isBefore(moment()
.add(1, 'hours'))) {
prefixKey= isOpen ?
'common.openingHours.closing_soon' :
'common.openingHours.opening_soon';
formattedCalender = formattedCalender.substr(0,1)
.toUpperCase() + formattedCalender.substr(1);
}
this.value = `${this.translate.instant(prefixKey)} ${formattedCalender}`;
}
}
@Injectable()
@Pipe({
name: 'numberLocalized',