Run Command > npx prettier --write .

This commit is contained in:
Lorenz Hilpert
2020-09-09 16:15:14 +02:00
parent b8924fbf43
commit 0b0f0706b7
772 changed files with 13060 additions and 11036 deletions

View File

@@ -5,7 +5,8 @@ This library was generated with [Angular CLI](https://github.com/angular/angular
## Code scaffolding
Run `ng generate component component-name --project native-container` to generate a new component. You can also use `ng generate directive|pipe|service|class|guard|interface|enum|module --project native-container`.
> Note: Don't forget to add `--project native-container` or else it will be added to the default project in your `angular.json` file.
> Note: Don't forget to add `--project native-container` or else it will be added to the default project in your `angular.json` file.
## Build

View File

@@ -10,15 +10,15 @@ module.exports = function (config) {
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'),
require('karma-coverage-istanbul-reporter'),
require('@angular-devkit/build-angular/plugins/karma')
require('@angular-devkit/build-angular/plugins/karma'),
],
client: {
clearContext: false // leave Jasmine Spec Runner output visible in browser
clearContext: false, // leave Jasmine Spec Runner output visible in browser
},
coverageIstanbulReporter: {
dir: require('path').join(__dirname, '../../coverage/native-container'),
reports: ['html', 'lcovonly', 'text-summary'],
fixWebpackSourcePaths: true
fixWebpackSourcePaths: true,
},
reporters: ['progress', 'kjhtml'],
port: 9876,
@@ -27,6 +27,6 @@ module.exports = function (config) {
autoWatch: true,
browsers: ['Chrome'],
singleRun: false,
restartOnFileChange: true
restartOnFileChange: true,
});
};

View File

@@ -1,7 +1,7 @@
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
providedIn: 'root',
})
export class WindowRef {
get nativeWindow(): Window {

View File

@@ -3,18 +3,12 @@
import 'zone.js/dist/zone';
import 'zone.js/dist/zone-testing';
import { getTestBed } from '@angular/core/testing';
import {
BrowserDynamicTestingModule,
platformBrowserDynamicTesting
} from '@angular/platform-browser-dynamic/testing';
import { BrowserDynamicTestingModule, platformBrowserDynamicTesting } from '@angular/platform-browser-dynamic/testing';
declare const require: any;
// First, initialize the Angular testing environment.
getTestBed().initTestEnvironment(
BrowserDynamicTestingModule,
platformBrowserDynamicTesting()
);
getTestBed().initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting());
// Then we find all the tests.
const context = require.context('./', true, /\.spec\.ts$/);
// And load the modules.

View File

@@ -5,11 +5,9 @@ const { SpecReporter } = require('jasmine-spec-reporter');
exports.config = {
allScriptsTimeout: 11000,
specs: [
'./src/**/*.e2e-spec.ts'
],
specs: ['./src/**/*.e2e-spec.ts'],
capabilities: {
'browserName': 'chrome'
browserName: 'chrome',
},
directConnect: true,
baseUrl: 'http://localhost:4200/',
@@ -17,12 +15,12 @@ exports.config = {
jasmineNodeOpts: {
showColors: true,
defaultTimeoutInterval: 30000,
print: function() {}
print: function () {},
},
onPrepare() {
require('ts-node').register({
project: require('path').join(__dirname, './tsconfig.e2e.json')
project: require('path').join(__dirname, './tsconfig.e2e.json'),
});
jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } }));
}
};
},
};

View File

@@ -1,7 +1,7 @@
// Karma configuration file, see link for more information
// https://karma-runner.github.io/1.0/config/configuration-file.html
module.exports = function(config) {
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine', '@angular-devkit/build-angular'],
@@ -10,15 +10,15 @@ module.exports = function(config) {
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'),
require('karma-coverage-istanbul-reporter'),
require('@angular-devkit/build-angular/plugins/karma')
require('@angular-devkit/build-angular/plugins/karma'),
],
client: {
clearContext: false // leave Jasmine Spec Runner output visible in browser
clearContext: false, // leave Jasmine Spec Runner output visible in browser
},
coverageIstanbulReporter: {
dir: require('path').join(__dirname, '../../coverage'),
reports: ['html', 'lcovonly', 'text-summary'],
fixWebpackSourcePaths: true
fixWebpackSourcePaths: true,
},
reporters: ['progress', 'kjhtml'],
port: 9876,
@@ -27,6 +27,6 @@ module.exports = function(config) {
autoWatch: true,
browsers: ['ChromeHeadless'],
singleRun: false,
restartOnFileChange: true
restartOnFileChange: true,
});
};

View File

@@ -11,7 +11,6 @@ import { EisConfiguration } from '@swagger/eis';
import { AppConfiguration } from './app-configuration';
export function catConfigurationFactory(config: AppConfiguration) {
return config.swagger.api;
}
@@ -56,4 +55,4 @@ export function eisConfigurationFactory(config: AppConfiguration) {
{ provide: EisConfiguration, useFactory: eisConfigurationFactory, deps: [AppConfiguration] },
],
})
export class AppSwaggerModule { }
export class AppSwaggerModule {}

View File

@@ -22,4 +22,4 @@
})(window, document, 'script', 'https://www.google-analytics.com/analytics.js', 'ga');
ga('create', 'UA-76423009-4', 'auto');
</script>
</script>

View File

@@ -6,7 +6,7 @@ describe('AppComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [RouterTestingModule],
declarations: [AppComponent]
declarations: [AppComponent],
}).compileComponents();
}));
});

View File

@@ -13,7 +13,7 @@ import { NativeContainerService } from 'shared/lib/barcode-scanner';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
styleUrls: ['./app.component.scss'],
})
export class AppComponent implements OnInit, OnDestroy {
title = 'Hugendubel InstoreApp';

View File

@@ -1,45 +1,40 @@
<div class="breadacrumb-grid" [ngClass]="{ 'grid-with-arrow': !showBack, 'breadcumb-mb-5': lowerMargin }" *ngIf="breadcrumbs">
<app-back-arrow
*ngIf="showBack"
(back)="goBack(breadcrumbs[breadcrumbs.length - 2])"
class="align-right back-arrow"
></app-back-arrow>
<div
class="layer-fade-start"
*ngIf="showBackNavigationArrow"
(mouseover)="showBackNavArrow()"
(mouseleave)="hideBackNavArrow($event)"
></div>
<div class="icon-start" *ngIf="showBackNavigationArrow && showBackArrow" (click)="navigateBack()" (mouseleave)="hideBackNavArrowIcon()">
<lib-icon class="icon-start" width="40px" name="tab_Arrow_3" type="png"></lib-icon>
</div>
<div class="breadcrumb-start-layer-fade" *ngIf="!showBackNavigationArrow"></div>
<div class="align-center breadcrumb-container" #container>
<span
*ngFor="let breadcrumb of breadcrumbs; let i = index; let last = last"
class="breadcrumb show"
(click)="selectBreadcrumb(breadcrumb)"
[ngClass]="{ selected: last, branch: module === 1 }"
>
<lib-icon *ngIf="breadcrumbs.indexOf(breadcrumb) > 0 && i != 0 && i !== last" class="next" name="Arrow_Next" alt="next"></lib-icon>
<span>{{ breadcrumb ? breadcrumb.name : '' }}</span>
</span>
<span class="breadcrumb last" *ngIf="showBack"></span>
</div>
<div class="breadcrumb-end-layer-fade" *ngIf="!showForwardNavigationalArrow"></div>
<div
class="layer-fade-end"
*ngIf="showForwardNavigationalArrow"
(mouseover)="showForwardNavArrow()"
(mouseleave)="hideForwardNavArrow($event)"
></div>
<div
class="icon-end"
*ngIf="showForwardNavigationalArrow && showForrwardArrow"
(click)="navigateForward()"
(mouseleave)="hideForwardNavArrowIcon()"
>
<lib-icon class="icon-end" width="40px" name="tab_Arrow_2" type="png"></lib-icon>
</div>
<div class="breadacrumb-grid" [ngClass]="{ 'grid-with-arrow': !showBack, 'breadcumb-mb-5': lowerMargin }" *ngIf="breadcrumbs">
<app-back-arrow *ngIf="showBack" (back)="goBack(breadcrumbs[breadcrumbs.length - 2])" class="align-right back-arrow"></app-back-arrow>
<div
class="layer-fade-start"
*ngIf="showBackNavigationArrow"
(mouseover)="showBackNavArrow()"
(mouseleave)="hideBackNavArrow($event)"
></div>
<div class="icon-start" *ngIf="showBackNavigationArrow && showBackArrow" (click)="navigateBack()" (mouseleave)="hideBackNavArrowIcon()">
<lib-icon class="icon-start" width="40px" name="tab_Arrow_3" type="png"></lib-icon>
</div>
<div class="breadcrumb-start-layer-fade" *ngIf="!showBackNavigationArrow"></div>
<div class="align-center breadcrumb-container" #container>
<span
*ngFor="let breadcrumb of breadcrumbs; let i = index; let last = last"
class="breadcrumb show"
(click)="selectBreadcrumb(breadcrumb)"
[ngClass]="{ selected: last, branch: module === 1 }"
>
<lib-icon *ngIf="breadcrumbs.indexOf(breadcrumb) > 0 && i != 0 && i !== last" class="next" name="Arrow_Next" alt="next"></lib-icon>
<span>{{ breadcrumb ? breadcrumb.name : '' }}</span>
</span>
<span class="breadcrumb last" *ngIf="showBack"></span>
</div>
<div class="breadcrumb-end-layer-fade" *ngIf="!showForwardNavigationalArrow"></div>
<div
class="layer-fade-end"
*ngIf="showForwardNavigationalArrow"
(mouseover)="showForwardNavArrow()"
(mouseleave)="hideForwardNavArrow($event)"
></div>
<div
class="icon-end"
*ngIf="showForwardNavigationalArrow && showForrwardArrow"
(click)="navigateForward()"
(mouseleave)="hideForwardNavArrowIcon()"
>
<lib-icon class="icon-end" width="40px" name="tab_Arrow_2" type="png"></lib-icon>
</div>
</div>

View File

@@ -5,7 +5,7 @@ import { BreadcrumbsComponent } from './breadcrumbs.component';
describe('BreadcrumbsComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [BreadcrumbsComponent]
declarations: [BreadcrumbsComponent],
}).compileComponents();
}));
});

View File

@@ -12,10 +12,7 @@ import { Subject, Observable } from 'rxjs';
import { Breadcrumb } from '../../core/models/breadcrumb.model';
import { Process } from '../../core/models/process.model';
import { Store, Select } from '@ngxs/store';
import {
ChangeCurrentRoute,
ResetProcessProductFilters,
} from '../../core/store/actions/process.actions';
import { ChangeCurrentRoute, ResetProcessProductFilters } from '../../core/store/actions/process.actions';
import { Router } from '@angular/router';
import { takeUntil, switchMap, distinctUntilChanged } from 'rxjs/operators';
import { SharedSelectors } from '../../core/store/selectors/shared.selectors';
@@ -36,12 +33,8 @@ import { FILIALE_LANDING_PAGE } from '../../core/utils/app.constants';
export class BreadcrumbsComponent implements OnInit, OnDestroy, AfterViewInit {
@ViewChild('container', { read: ElementRef, static: false })
public container: ElementRef<any>;
@Select(SharedSelectors.getBreadcrumbs) breadcrumbs$: Observable<
Breadcrumb[]
>;
@Select(SharedSelectors.getCurrentProcess) currentProcess$: Observable<
Process
>;
@Select(SharedSelectors.getBreadcrumbs) breadcrumbs$: Observable<Breadcrumb[]>;
@Select(SharedSelectors.getCurrentProcess) currentProcess$: Observable<Process>;
module: ModuleSwitcher;
destroy$ = new Subject();
breadcrumbs: Breadcrumb[] = [];
@@ -71,10 +64,7 @@ export class BreadcrumbsComponent implements OnInit, OnDestroy, AfterViewInit {
}
get backArrow() {
return (
this.router.url.substring(0, 16) === '/product/details' &&
this.breadsCount > 1
);
return this.router.url.substring(0, 16) === '/product/details' && this.breadsCount > 1;
}
get selectedBreadCrumbIndex() {
@@ -103,12 +93,7 @@ export class BreadcrumbsComponent implements OnInit, OnDestroy, AfterViewInit {
return false;
}
constructor(
private store: Store,
private router: Router,
private cdrf: ChangeDetectorRef,
private appService: AppService
) {}
constructor(private store: Store, private router: Router, private cdrf: ChangeDetectorRef, private appService: AppService) {}
getBreadcrumbsFromCurentProcess() {
this.currentProcess$
@@ -135,18 +120,10 @@ export class BreadcrumbsComponent implements OnInit, OnDestroy, AfterViewInit {
this.showBackNavigationArrow = false;
if (breadcrumbs) {
const breadName =
breadcrumbs.length > 0
? breadcrumbs[breadcrumbs.length - 1]
? breadcrumbs[breadcrumbs.length - 1].name
: ''
: '';
this.showBack = !(
breadName === 'Bestellbestätigung' || breadName === 'Remission'
);
breadcrumbs.length > 0 ? (breadcrumbs[breadcrumbs.length - 1] ? breadcrumbs[breadcrumbs.length - 1].name : '') : '';
this.showBack = !(breadName === 'Bestellbestätigung' || breadName === 'Remission');
this.breadcrumbs = breadcrumbs;
this.breadsCount = Object.keys(this.breadcrumbs)
? Object.keys(this.breadcrumbs).length
: 0;
this.breadsCount = Object.keys(this.breadcrumbs) ? Object.keys(this.breadcrumbs).length : 0;
this.cdrf.detectChanges();
if (!this.isIPad) {
setTimeout(() => {
@@ -168,9 +145,7 @@ export class BreadcrumbsComponent implements OnInit, OnDestroy, AfterViewInit {
if (this.module === ModuleSwitcher.Customer) {
this.store.dispatch(new ChangeCurrentRoute(breadcrumb.path, true));
} else {
this.store.dispatch(
new SetBranchProcessCurrentPath(breadcrumb.path, true)
);
this.store.dispatch(new SetBranchProcessCurrentPath(breadcrumb.path, true));
}
this.router.navigate([breadcrumb.path], {
queryParams: breadcrumb.queryParams ? breadcrumb.queryParams : {},
@@ -184,9 +159,7 @@ export class BreadcrumbsComponent implements OnInit, OnDestroy, AfterViewInit {
this.store.dispatch(new ChangeCurrentRoute(breadcrumb.path, false));
this.router.navigate(['/product/results']);
} else {
this.store.dispatch(
new SetBranchProcessCurrentPath(breadcrumb.path, false)
);
this.store.dispatch(new SetBranchProcessCurrentPath(breadcrumb.path, false));
this.router.navigate([FILIALE_LANDING_PAGE]);
}
}
@@ -236,10 +209,7 @@ export class BreadcrumbsComponent implements OnInit, OnDestroy, AfterViewInit {
elementProcessed++;
childrenWidth += this.container.nativeElement.children[i].offsetWidth;
}
if (
breadcrumbs === elementProcessed &&
containerWidth <= childrenWidth
) {
if (breadcrumbs === elementProcessed && containerWidth <= childrenWidth) {
this.showBackNavigationArrow = true;
this.cdrf.detectChanges();
} else {
@@ -257,11 +227,7 @@ export class BreadcrumbsComponent implements OnInit, OnDestroy, AfterViewInit {
hideBackNavArrow(event) {
if (event) {
const e = event.toElement || event.relatedTarget;
if (
e &&
e.classList &&
(e.classList[0] === 'icon' || e.classList[0] === 'ng-star-inserted')
) {
if (e && e.classList && (e.classList[0] === 'icon' || e.classList[0] === 'ng-star-inserted')) {
return;
}
this.showBackArrow = false;
@@ -279,11 +245,7 @@ export class BreadcrumbsComponent implements OnInit, OnDestroy, AfterViewInit {
hideForwardNavArrow(event) {
if (event) {
const e = event.toElement || event.relatedTarget;
if (
e &&
e.classList &&
(e.classList[0] === 'icon' || e.classList[0] === 'ng-star-inserted')
) {
if (e && e.classList && (e.classList[0] === 'icon' || e.classList[0] === 'ng-star-inserted')) {
return;
}
this.showForrwardArrow = false;

View File

@@ -1,4 +1,3 @@
// start:ng42.barrel
export * from './content-header.component';
// end:ng42.barrel

View File

@@ -8,7 +8,7 @@ describe('HeaderComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [HeaderComponent]
declarations: [HeaderComponent],
}).compileComponents();
}));

View File

@@ -23,7 +23,7 @@ export class HeaderComponent implements OnInit, OnDestroy {
module: ModuleSwitcher = ModuleSwitcher.Customer;
destroy$ = new Subject();
constructor(private moduleSwitcherService: ModuleSwitcherService, private store: Store, private router: Router) { }
constructor(private moduleSwitcherService: ModuleSwitcherService, private store: Store, private router: Router) {}
customer = 'Kunden';

View File

@@ -8,7 +8,7 @@ describe('LogOutComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [LogOutComponent]
declarations: [LogOutComponent],
}).compileComponents();
}));

View File

@@ -3,38 +3,56 @@
<div class="menu-grid">
<div class="menu-item-grid align-center active" (click)="routeToMenu('/product/search', 'productsearch')">
<div>
<lib-icon class="menu-icon" name="{{
<lib-icon
class="menu-icon"
name="{{
router.url === '/product/search' || router.url.startsWith('/product/results') || router.url.startsWith('/product/details')
? 'Icon_Artikelsuche'
: 'Icon_Artikelsuche_inactive'
}}" width="34px" height="24px"></lib-icon>
}}"
width="34px"
height="24px"
></lib-icon>
</div>
<span *ngIf="
<span
*ngIf="
router.url === '/product/search' || router.url.startsWith('/product/results') || router.url.startsWith('/product/details');
else articleSearchLabelElse
" class="menu-item selected">Artikelsuche</span>
"
class="menu-item selected"
>Artikelsuche</span
>
<ng-template #articleSearchLabelElse>
<span class="menu-item">Artikelsuche</span>
</ng-template>
</div>
<div class="menu-item-grid align-center active" (click)="routeToMenu('/customer/search', 'customersearch')">
<div>
<lib-icon class="menu-icon" name="{{
<lib-icon
class="menu-icon"
name="{{
router.url === '/customer/search' ||
router.url === '/customer/results' ||
router.url.startsWith('/customer/edit') ||
router.url.startsWith('/customer')
? 'Icon_Kundensuche'
: 'Icon_Kundensuche_inactive'
}}" width="34px" height="24px"></lib-icon>
}}"
width="34px"
height="24px"
></lib-icon>
</div>
<span *ngIf="
<span
*ngIf="
router.url === '/customer/search' ||
router.url === '/customer/results' ||
router.url.startsWith('/customer/edit') ||
router.url.startsWith('/customer');
else customerSearchLabelElse
" class="menu-item selected">Kundensuche</span>
"
class="menu-item selected"
>Kundensuche</span
>
<ng-template #customerSearchLabelElse>
<span class="menu-item">Kundensuche</span>
</ng-template>
@@ -42,18 +60,27 @@
<div class="menu-item-grid align-center active" (click)="routeToMenu('/shelf/search', 'shelfsearch')">
<!-- <div class="menu-item-grid align-center"> -->
<div>
<lib-icon class="menu-icon" name="{{
<lib-icon
class="menu-icon"
name="{{
router.url === '/shelf/search' || router.url.startsWith('/shelf/results') || router.url.startsWith('/shelf/details')
? 'Icon_Abholfach'
: 'Icon_Abholfach_inactive'
}}" width="34px" height="24px"></lib-icon>
}}"
width="34px"
height="24px"
></lib-icon>
</div>
<span *ngIf="
<span
*ngIf="
router.url === '/shelf/search' || router.url.startsWith('/shelf/results') || router.url.startsWith('/shelf/details');
else shelfSearchLabelElse
" class="menu-item selected">Warenausgabe</span>
"
class="menu-item selected"
>Warenausgabe</span
>
<ng-template #shelfSearchLabelElse>
<span class="menu-item ">Warenausgabe</span>
<span class="menu-item">Warenausgabe</span>
</ng-template>
</div>
</div>
@@ -64,7 +91,9 @@
<div class="menu-item-grid align-center">
<!-- <div class="menu-item-grid align-center" (click)="routeToMenu('/branch/main', 'branchmain')"> -->
<div>
<lib-icon class="menu-icon" name="{{
<lib-icon
class="menu-icon"
name="{{
router.url === '/branch/main' ||
router.url === '/goodsin/search' ||
router.url === '/goodsin/results' ||
@@ -72,49 +101,68 @@
router.url.startsWith('/shelf/edit')
? 'Icon_Abholfach_B'
: 'Icon_Abholfach_B_disabled'
}}" width="34px" height="24px"></lib-icon>
}}"
width="34px"
height="24px"
></lib-icon>
</div>
<span *ngIf="
<span
*ngIf="
router.url === '/branch/main' ||
router.url === '/goodsin/search' ||
router.url === '/goodsin/results' ||
router.url.startsWith('/goodsin/details') ||
router.url.startsWith('/shelf/edit');
else abholfachLabelElse
" class="branch-menu-item branch-selected">Abholfach</span>
"
class="branch-menu-item branch-selected"
>Abholfach</span
>
<ng-template #abholfachLabelElse>
<span class="branch-menu-item branch-disabled">Abholfach</span>
</ng-template>
</div>
<div class="menu-item-grid align-center active">
<div>
<lib-icon class="menu-icon" name="{{
router.url === '/task-calendar/calendar' ||
router.url === '/task-calendar/tasks'
<lib-icon
class="menu-icon"
name="{{
router.url === '/task-calendar/calendar' || router.url === '/task-calendar/tasks'
? 'Icon_Tatigkeitskalender'
: 'Icon_Tatigkeitskalender_disabled'
}}" width="34px" height="24px"></lib-icon>
}}"
width="34px"
height="24px"
></lib-icon>
</div>
<span *ngIf="
router.url === '/task-calendar/calendar' ||
router.url === '/task-calendar/tasks';
else taskCalendarLabelElse
" class="branch-menu-item branch-selected">Tätigkeitskalender</span>
<span
*ngIf="router.url === '/task-calendar/calendar' || router.url === '/task-calendar/tasks'; else taskCalendarLabelElse"
class="branch-menu-item branch-selected"
>Tätigkeitskalender</span
>
<ng-template #taskCalendarLabelElse>
<span class="branch-menu-item branch-disabled">Tätigkeitskalender</span>
</ng-template>
</div>
<div class="menu-item-grid align-center active" (click)="routeToMenu('/remission/create', 'remission')">
<div>
<lib-icon class="menu-icon" name="{{
<lib-icon
class="menu-icon"
name="{{
router.url === '/remission/create' || router.url === '/remission/started' ? 'Icon_Remission' : 'Icon_Remission_inactive'
}}" width="34px" height="24px"></lib-icon>
}}"
width="34px"
height="24px"
></lib-icon>
</div>
<span *ngIf="router.url === '/remission/create' || router.url === '/remission/started'; else remissionLabelElse"
class="branch-menu-item branch-selected">Remission</span>
<span
*ngIf="router.url === '/remission/create' || router.url === '/remission/started'; else remissionLabelElse"
class="branch-menu-item branch-selected"
>Remission</span
>
<ng-template #remissionLabelElse>
<span class="branch-menu-item">Remission</span>
</ng-template>
</div>
</div>
</div>
</div>

View File

@@ -52,7 +52,7 @@
color: $branch-color-inactive;
&.branch-disabled {
color: #EDEFF0;
color: #edeff0;
}
}

View File

@@ -8,7 +8,7 @@ describe('MenuComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [MenuComponent]
declarations: [MenuComponent],
}).compileComponents();
}));

View File

@@ -7,7 +7,7 @@ import {
AddProcess,
ChangeCurrentRoute,
ResetProcessProductFilters,
SetOnlineCustomerCreationStatus
SetOnlineCustomerCreationStatus,
} from '../../core/store/actions/process.actions';
import { Breadcrumb } from '../../core/models/breadcrumb.model';
import { ResetBreadcrumbsTo, AddBreadcrumb } from '../../core/store/actions/breadcrumb.actions';
@@ -27,7 +27,7 @@ import { CustomerHelperService } from '../../modules/customer/services/customer-
@Component({
selector: 'app-menu',
templateUrl: './menu.component.html',
styleUrls: ['./menu.component.scss']
styleUrls: ['./menu.component.scss'],
})
export class MenuComponent implements OnInit, OnDestroy {
@Select(ProcessSelectors.getProcesses) processes$: Observable<Process[]>;
@@ -53,7 +53,7 @@ export class MenuComponent implements OnInit, OnDestroy {
new ResetBreadcrumbsTo(
<Breadcrumb>{
name: this.nameFromPath(menuPath),
path: menuPath
path: menuPath,
},
this.breadCrumbId,
true
@@ -101,7 +101,7 @@ export class MenuComponent implements OnInit, OnDestroy {
const newProcess = <Process>{
id: 1,
name: 'Vorgang 1',
currentRoute: menuPath
currentRoute: menuPath,
};
this.store.dispatch(new AddProcess(newProcess));
}
@@ -131,7 +131,7 @@ export class MenuComponent implements OnInit, OnDestroy {
return 'Remission';
case '/task-calendar/calendar':
this.breadCrumbId = 'taskCalendar';
return 'Tätigkeitskalendar'
return 'Tätigkeitskalendar';
default:
this.breadCrumbId = 'product';
return 'Artikelsuche';
@@ -161,7 +161,7 @@ export class MenuComponent implements OnInit, OnDestroy {
new ResetBreadcrumbsTo(
<Breadcrumb>{
name: 'Remission',
path: path
path: path,
},
'remission',
true

View File

@@ -8,7 +8,7 @@ describe('PrinterSelectionComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [PrinterSelectionComponent]
declarations: [PrinterSelectionComponent],
}).compileComponents();
}));

View File

@@ -1,2 +1 @@
export const PRINT_ERROR_MSG =
'Der Druckauftrag konnte nicht ausgeführt werden.';
export const PRINT_ERROR_MSG = 'Der Druckauftrag konnte nicht ausgeführt werden.';

View File

@@ -3,6 +3,6 @@ import { trigger, transition, animate, style } from '@angular/animations';
export const addAnimation = trigger('add', [
transition('void => true', [
style({ opacity: 0, transform: 'translateX(200%)' }),
animate('0.3s ease-out', style({ opacity: 1, transform: 'translateX(0%)' }))
])
animate('0.3s ease-out', style({ opacity: 1, transform: 'translateX(0%)' })),
]),
]);

View File

@@ -6,7 +6,7 @@
<div class="process-grid-container" [ngClass]="{ adding: showAddingPadding }" *ngIf="module === 0" #panel>
<app-process-tab
id="{{ process.id }}"
style="display: inline-block;height: 100%;"
style="display: inline-block; height: 100%;"
*ngFor="let process of processes; let last = last"
[module]="module"
[last]="last"
@@ -17,7 +17,7 @@
<div class="process-grid-container" *ngIf="module === 1" #panel>
<app-process-tab
id="{{ branchProcess.id }}"
style="display: inline-block;height: 100%;"
style="display: inline-block; height: 100%;"
[module]="module"
[process]="branchProcess"
></app-process-tab>

View File

@@ -8,7 +8,7 @@ describe('ProcessHeaderComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ProcessHeaderComponent]
declarations: [ProcessHeaderComponent],
}).compileComponents();
}));

View File

@@ -43,14 +43,14 @@ export class ProcessHeaderComponent implements OnInit, OnDestroy {
private iPadDetected = false;
private iPadEventRecieved = false;
constructor(private store: Store, private router: Router, private cdr: ChangeDetectorRef, private windowRef: WindowRef) { }
constructor(private store: Store, private router: Router, private cdr: ChangeDetectorRef, private windowRef: WindowRef) {}
addProcess() {
const itemNo = !this.processes
? 0
: this.processes && this.processes.length === 0
? 1
: this.processes[this.processes.length - 1].id + 1;
? 1
: this.processes[this.processes.length - 1].id + 1;
const newProcess = <Process>{
id: itemNo,
new: true,

View File

@@ -13,7 +13,7 @@
height="16px"
name="Shopping_Cart"
*ngIf="!cartBackgroundForDownload && process.id === (currentProcessId$ | async)"
class="process-cart-icon "
class="process-cart-icon"
></lib-icon>
<lib-icon
mt="12px"
@@ -22,7 +22,7 @@
height="16px"
name="Shopping_Cart_Inactive"
*ngIf="!cartBackgroundForDownload && process.id !== (currentProcessId$ | async)"
class="process-cart-icon "
class="process-cart-icon"
></lib-icon>
<lib-icon
mt="12px"
@@ -31,7 +31,7 @@
height="16px"
name="shopping_cart_white"
*ngIf="cartBackgroundForDownload"
class="process-cart-icon "
class="process-cart-icon"
></lib-icon>
<div [@cartnumber]="cartanimation" class="pt-3 process-cart-number-container">
<span class="process-cart-number" [ngClass]="{ 'number-download': cartBackgroundForDownload }">{{ cartCount }}</span>

View File

@@ -8,7 +8,7 @@ describe('ProcessTabComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ProcessTabComponent]
declarations: [ProcessTabComponent],
}).compileComponents();
}));

View File

@@ -1,4 +1,14 @@
import { Component, OnInit, Input, ViewChild, OnDestroy, ChangeDetectionStrategy, ChangeDetectorRef, AfterViewInit, ViewRef } from '@angular/core';
import {
Component,
OnInit,
Input,
ViewChild,
OnDestroy,
ChangeDetectionStrategy,
ChangeDetectorRef,
AfterViewInit,
ViewRef,
} from '@angular/core';
import { Process } from '../../core/models/process.model';
import { Router, ActivatedRoute, NavigationEnd } from '@angular/router';
import { Store, Select } from '@ngxs/store';
@@ -6,7 +16,7 @@ import {
DeleteProcess,
PreventProductLoad,
ChangeCurrentRoute,
SetProcessNewStatusToFalse
SetProcessNewStatusToFalse,
} from '../../core/store/actions/process.actions';
import { Breadcrumb } from '../../core/models/breadcrumb.model';
import { ProcessDeleteDialogComponent } from '../../modules/process/components/process-delete-dialog/process-delete-dialog.component';
@@ -39,13 +49,13 @@ import { DeleteFormState } from '../../core/store/actions/forms.actions';
style({ transform: 'translateY(10%)', opacity: 1, offset: 0.4 }),
style({ transform: 'translateY(0%)', opacity: 1, offset: 0.6 }),
style({ transform: 'translateY(5%)', opacity: 1, offset: 0.8 }),
style({ transform: 'translateY(0%)', opacity: 1, offset: 0.99 })
style({ transform: 'translateY(0%)', opacity: 1, offset: 0.99 }),
])
)
])
])
),
]),
]),
],
changeDetection: ChangeDetectionStrategy.OnPush
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ProcessTabComponent implements OnInit, OnDestroy, AfterViewInit {
@Input() process: Process;
@@ -63,7 +73,7 @@ export class ProcessTabComponent implements OnInit, OnDestroy, AfterViewInit {
cartanimation = '';
cartBackgroundForDownload = false;
constructor(private store: Store, private router: Router, private cdr: ChangeDetectorRef, private route: ActivatedRoute) { }
constructor(private store: Store, private router: Router, private cdr: ChangeDetectorRef, private route: ActivatedRoute) {}
isProcessFinished = this.router.url === '/cart/confirmation';
deleteProcess(process: Process) {
@@ -120,7 +130,7 @@ export class ProcessTabComponent implements OnInit, OnDestroy, AfterViewInit {
.select(SharedSelectors.getCartTabData)
.pipe(
takeUntil(this.destroy$),
map(filterFn => filterFn(this.process.id))
map((filterFn) => filterFn(this.process.id))
)
.subscribe((quantity: number) => {
if (quantity < this.cartCount) {
@@ -135,9 +145,9 @@ export class ProcessTabComponent implements OnInit, OnDestroy, AfterViewInit {
.select(ProcessSelectors.getCurrentRoute)
.pipe(
takeUntil(this.destroy$),
switchMap(route =>
switchMap((route) =>
this.cartHasDownloadForProcess$.pipe(
map(data => {
map((data) => {
return { route: route, data: data };
})
)
@@ -168,7 +178,7 @@ export class ProcessTabComponent implements OnInit, OnDestroy, AfterViewInit {
this.selectProcess(process);
const newBread: Breadcrumb = {
name: 'Warenkorb',
path: '/cart/review'
path: '/cart/review',
};
this.store.dispatch(new AddBreadcrumb(newBread, 'shoppingCart'));

View File

@@ -8,7 +8,7 @@ describe('ErrorComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ErrorComponent]
declarations: [ErrorComponent],
}).compileComponents();
}));

View File

@@ -6,7 +6,7 @@ export class ErrorService {
private errors = new Subject<{ code: number; message: string; invalidProperties: string; logout: boolean }>();
private recovery = new Subject<boolean>();
constructor() { }
constructor() {}
public addErrors = (code: number, errors: string, invalidProperties: string, logout = false): void =>
// tslint:disable-next-line: semicolon

View File

@@ -18,7 +18,7 @@ export class BasicAuthorizationInterceptor implements HttpInterceptor {
constructor(options$: Observable<BasicAuthorizationOptions>) {
options$
.pipe(
map(options => {
map((options) => {
const token = btoa(`${options.client}:${options.password}`);
const endpointMatchers: RegExp[] = [];
for (const endpoint of options.endpoints) {
@@ -40,16 +40,16 @@ export class BasicAuthorizationInterceptor implements HttpInterceptor {
return this.optionsSub.pipe(
first(),
map(options => {
map((options) => {
let request = req;
if (options.endpointMatchers.find(matcher => matcher.test(req.url))) {
if (options.endpointMatchers.find((matcher) => matcher.test(req.url))) {
const headers = req.headers.set('Authorization', `Basic ${options.token}`);
request = req.clone({ headers });
}
return request;
}),
flatMap(request => next.handle(request))
flatMap((request) => next.handle(request))
);
}
}

View File

@@ -1,10 +1,4 @@
import {
HttpInterceptor,
HttpRequest,
HttpHandler,
HttpEvent,
HttpErrorResponse,
} from '@angular/common/http';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpErrorResponse } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { ErrorService } from '../error/component/error.service';
@@ -15,22 +9,10 @@ import { isWhiteList } from '../utils/http-interceptor-whitelist.utils';
@Injectable()
export class HttpErrorHandlerInterceptor implements HttpInterceptor {
constructor(
private errorService: ErrorService,
private logger: LoggingService
) {}
constructor(private errorService: ErrorService, private logger: LoggingService) {}
intercept(
req: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
return next
.handle(req)
.pipe(
catchError((error: HttpErrorResponse, caught: any) =>
this.handleError(error)
)
);
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(req).pipe(catchError((error: HttpErrorResponse, caught: any) => this.handleError(error)));
}
getInvalidProperties(error: any) {
@@ -57,11 +39,7 @@ export class HttpErrorHandlerInterceptor implements HttpInterceptor {
return throwError(error);
}
let errorMessage = '';
this.logger.log(
'HUGENDUBEL INSTORE MA APP Backend',
error,
LogType.Error
);
this.logger.log('HUGENDUBEL INSTORE MA APP Backend', error, LogType.Error);
if (error.error instanceof OAuthErrorEvent) {
return;
} else if (error.error instanceof ErrorEvent) {
@@ -80,12 +58,7 @@ export class HttpErrorHandlerInterceptor implements HttpInterceptor {
const invalidProperties = this.getInvalidProperties(error);
const logout = error.status === 401;
this.errorService.addErrors(
error.status,
message,
invalidProperties,
logout
);
this.errorService.addErrors(error.status, message, invalidProperties, logout);
}
return throwError(errorMessage);
} else {
@@ -94,12 +67,8 @@ export class HttpErrorHandlerInterceptor implements HttpInterceptor {
}
private showInvalidProperties(url: string, code: number = -1) {
const blackList: { url: string; codes: number[] }[] = [
{ url: '/order/checkout', codes: [400] },
];
const blackList: { url: string; codes: number[] }[] = [{ url: '/order/checkout', codes: [400] }];
return !blackList.find(
(entry) => !!url.includes(entry.url) && !!entry.codes.includes(code)
);
return !blackList.find((entry) => !!url.includes(entry.url) && !!entry.codes.includes(code));
}
}

View File

@@ -14,10 +14,7 @@ import {
ShippingAddressDTO,
} from '@swagger/crm';
import { NotificationChannels } from '../models/notification-channels.enum';
import {
EntityDTOContainerOfBranchDTO,
ShippingAddressDTO as CheckoutShippingAddressDTO,
} from '@swagger/checkout';
import { EntityDTOContainerOfBranchDTO, ShippingAddressDTO as CheckoutShippingAddressDTO } from '@swagger/checkout';
import { DatePipe } from '@angular/common';
import { BACKEND_API_TIMESTAMP_FORMAT } from '../utils/app.formats';
import { KeyValueDTOOfStringAndString } from '@swagger/cat';
@@ -63,9 +60,7 @@ export class CustomerMapping {
zipCode: customer.delivery_addres.zip + '',
street: customer.delivery_addres.street,
streetNumber: customer.delivery_addres.streetNo + '',
info: customer.delivery_addres.note
? customer.delivery_addres.note
: null,
info: customer.delivery_addres.note ? customer.delivery_addres.note : null,
};
}
@@ -76,9 +71,7 @@ export class CustomerMapping {
zipCode: customer.invoice_address.zip + '',
street: customer.invoice_address.street,
streetNumber: customer.invoice_address.streetNo + '',
info: customer.invoice_address.note
? customer.invoice_address.note
: null,
info: customer.invoice_address.note ? customer.invoice_address.note : null,
};
}
@@ -91,20 +84,14 @@ export class CustomerMapping {
};
}
if (
Array.isArray(customer.poossible_delivery_addresses) &&
customer.poossible_delivery_addresses.length > 0
) {
if (Array.isArray(customer.poossible_delivery_addresses) && customer.poossible_delivery_addresses.length > 0) {
customer.poossible_delivery_addresses.forEach((adrs: Address) => {
addresses.push(this.addressesItem(adrs));
shippingAddresses.push(this.addressesItem(adrs));
});
}
if (
Array.isArray(customer.poossible_invoice_addresses) &&
customer.poossible_invoice_addresses.length > 0
) {
if (Array.isArray(customer.poossible_invoice_addresses) && customer.poossible_invoice_addresses.length > 0) {
customer.poossible_invoice_addresses.forEach((adrs: Address) => {
if (adrs) {
addresses.push(this.addressesItem(adrs));
@@ -191,9 +178,7 @@ export class CustomerMapping {
}
}
private addressesItem(
address: Address
): EntityDTOContainerOfShippingAddressDTO {
private addressesItem(address: Address): EntityDTOContainerOfShippingAddressDTO {
if (!address) {
return;
}
@@ -229,9 +214,7 @@ export class CustomerMapping {
customerInfoDTOtoUser(customerInfo: CustomerInfoDTO): User {
if (isNullOrUndefined(customerInfo)) {
throw new Error(
'argument customerInfo:CustomerInfoDTO is null or undefined.'
);
throw new Error('argument customerInfo:CustomerInfoDTO is null or undefined.');
}
const id = customerInfo.id;
@@ -277,14 +260,10 @@ export class CustomerMapping {
first_name: customerInfo.firstName,
last_name: customerInfo.lastName,
city: customerInfo.address.city ? customerInfo.address.city : undefined,
zip: customerInfo.address.zipCode
? customerInfo.address.zipCode
: undefined,
zip: customerInfo.address.zipCode ? customerInfo.address.zipCode : undefined,
country: customerInfo.address.country,
street: customerInfo.address.street,
streetNo: customerInfo.address.streetNumber
? +customerInfo.address.streetNumber
: undefined,
streetNo: customerInfo.address.streetNumber ? +customerInfo.address.streetNumber : undefined,
};
}
@@ -356,9 +335,7 @@ export class CustomerMapping {
customerDTOtoUser(customerDto: CustomerDTO): User {
if (isNullOrUndefined(customerDto)) {
throw new Error(
'argument customerDto:CustomerInfoDTO is null or undefined.'
);
throw new Error('argument customerDto:CustomerInfoDTO is null or undefined.');
}
const id = customerDto.id;
@@ -389,8 +366,7 @@ export class CustomerMapping {
let notificationEmail = false;
if (customerDto.notificationChannels) {
notificationSms =
customerDto.notificationChannels === NotificationChannels.Sms ||
customerDto.notificationChannels === NotificationChannels.EmailSms;
customerDto.notificationChannels === NotificationChannels.Sms || customerDto.notificationChannels === NotificationChannels.EmailSms;
notificationEmail =
customerDto.notificationChannels === NotificationChannels.Email ||
customerDto.notificationChannels === NotificationChannels.EmailSms;
@@ -447,9 +423,7 @@ export class CustomerMapping {
mobile_number: mobileNumber,
newUser: newUser,
customer_card: false,
createdInBranch: customerDto.createdInBranch
? customerDto.createdInBranch.id
: null,
createdInBranch: customerDto.createdInBranch ? customerDto.createdInBranch.id : null,
newsletter: false, // missing info from API
shop: false,
notificationSms: notificationSms,
@@ -466,13 +440,9 @@ export class CustomerMapping {
};
}
fromShippingAddressDtoToAddress(
shippingAddress: ShippingAddressDTO
): Address {
fromShippingAddressDtoToAddress(shippingAddress: ShippingAddressDTO): Address {
if (isNullOrUndefined(shippingAddress)) {
throw new Error(
'argument shippingAddress:ShippingAddressDTO is null or undefined.'
);
throw new Error('argument shippingAddress:ShippingAddressDTO is null or undefined.');
}
let gender = '';
@@ -525,10 +495,7 @@ export class CustomerMapping {
};
}
fromAddressToShippingAddressDTO(
address: Address,
forUpdate: boolean
): ShippingAddressDTO {
fromAddressToShippingAddressDTO(address: Address, forUpdate: boolean): ShippingAddressDTO {
if (isNullOrUndefined(address)) {
throw new Error('argument address:Address is null or undefined.');
}
@@ -560,10 +527,7 @@ export class CustomerMapping {
lastName: address.last_name,
gender: this.getGender(address.gender),
status: 1,
isDefault: this.datePipe.transform(
new Date(),
BACKEND_API_TIMESTAMP_FORMAT
),
isDefault: this.datePipe.transform(new Date(), BACKEND_API_TIMESTAMP_FORMAT),
organisation: <OrganisationDTO>{
name: address.company_name,
department: address.company_department,
@@ -618,10 +582,7 @@ export class CustomerMapping {
lastName: address.last_name,
gender: this.getGender(address.gender),
status: 1,
isDefault: this.datePipe.transform(
new Date(),
BACKEND_API_TIMESTAMP_FORMAT
),
isDefault: this.datePipe.transform(new Date(), BACKEND_API_TIMESTAMP_FORMAT),
address: _address,
payerNumber: address.payer_number,
payerStatus: address.payer_status,
@@ -636,9 +597,7 @@ export class CustomerMapping {
fromAssignedPayerDtoToAddress(assignedPayers: AssignedPayerDTO): Address {
if (isNullOrUndefined(assignedPayers)) {
throw new Error(
'argument shippingAddress:ShippingAddressDTO is null or undefined.'
);
throw new Error('argument shippingAddress:ShippingAddressDTO is null or undefined.');
}
let id = null;
@@ -651,11 +610,7 @@ export class CustomerMapping {
}
let gender = '';
if (
!!assignedPayers.payer &&
!!assignedPayers.payer.data &&
!!assignedPayers.payer.data.gender
) {
if (!!assignedPayers.payer && !!assignedPayers.payer.data && !!assignedPayers.payer.data.gender) {
gender = this.getGenderFromCode(assignedPayers.payer.data.gender);
}
@@ -664,11 +619,7 @@ export class CustomerMapping {
let street = '';
let streetNo = null;
let zip: string = null;
if (
!!assignedPayers.payer &&
!!assignedPayers.payer.data &&
!!assignedPayers.payer.data.address
) {
if (!!assignedPayers.payer && !!assignedPayers.payer.data && !!assignedPayers.payer.data.address) {
country = assignedPayers.payer.data.address.country;
city = assignedPayers.payer.data.address.city;
street = assignedPayers.payer.data.address.street;
@@ -690,11 +641,7 @@ export class CustomerMapping {
let company_name = null;
let company_department = null;
let company_tax_number = null;
if (
!!assignedPayers.payer &&
!!assignedPayers.payer.data &&
!!assignedPayers.payer.data.organisation
) {
if (!!assignedPayers.payer && !!assignedPayers.payer.data && !!assignedPayers.payer.data.organisation) {
company_name = assignedPayers.payer.data.organisation.name;
company_department = assignedPayers.payer.data.organisation.department;
company_tax_number = assignedPayers.payer.data.organisation.vatId;
@@ -757,9 +704,7 @@ export class CustomerMapping {
zipCode: customer.delivery_addres.zip + '',
street: customer.delivery_addres.street,
streetNumber: customer.delivery_addres.streetNo + '',
info: customer.delivery_addres.note
? customer.delivery_addres.note
: null,
info: customer.delivery_addres.note ? customer.delivery_addres.note : null,
};
}
@@ -821,9 +766,7 @@ export class CustomerMapping {
: NotificationChannels.NotSet;
}
fromOrganisationToOrganisationDTO(
organisation: Organisation
): OrganisationDTO {
fromOrganisationToOrganisationDTO(organisation: Organisation): OrganisationDTO {
if (!organisation) {
return {};
}

View File

@@ -18,14 +18,14 @@ export class FeedMapping {
let kpi: FeedKpi = null;
if (feed.items && feed.type === 'products') {
feed.items.forEach(item => {
feed.items.forEach((item) => {
books.push({
ean: item.product.ean,
name: item.product.name,
});
});
} else if (feed.type === 'info') {
feed.items.forEach(i => {
feed.items.forEach((i) => {
news.push(<FeedNews>{
id: i.id,
title: i.heading,

View File

@@ -39,9 +39,7 @@ export class ProductMapping {
let assortment: string;
if (item.shelfInfos) {
assortment = item.shelfInfos[0].assortment
? item.shelfInfos[0].assortment
: item.shelfInfos[0].label;
assortment = item.shelfInfos[0].assortment ? item.shelfInfos[0].assortment : item.shelfInfos[0].label;
}
return {

View File

@@ -9,10 +9,10 @@ export class CustomerFeatures {
constructor(features: Features[]) {
if (features && features.length > 0) {
this.online = !isNullOrUndefined(features.find(feature => feature.key === 'onlineshop'));
this.guest = !isNullOrUndefined(features.find(feature => feature.key === 'guestaccount'));
this.card = !isNullOrUndefined(features.find(feature => feature.key === 'p4mUser'));
this.employee = !isNullOrUndefined(features.find(feature => feature.key === 'staff'));
this.online = !isNullOrUndefined(features.find((feature) => feature.key === 'onlineshop'));
this.guest = !isNullOrUndefined(features.find((feature) => feature.key === 'guestaccount'));
this.card = !isNullOrUndefined(features.find((feature) => feature.key === 'p4mUser'));
this.employee = !isNullOrUndefined(features.find((feature) => feature.key === 'staff'));
} else {
this.online = false;
this.guest = false;

View File

@@ -1,6 +1,6 @@
export interface FeedEvent {
id: number;
title: string;
content: string;
imageUrl: string;
id: number;
title: string;
content: string;
imageUrl: string;
}

View File

@@ -1,6 +1,6 @@
export interface FeedNews {
id: number;
title: string;
content: string;
icon: string;
id: number;
title: string;
content: string;
icon: string;
}

View File

@@ -1,5 +1,5 @@
export interface FeedRecommandation {
id: number;
title: string;
content: string;
id: number;
title: string;
content: string;
}

View File

@@ -1,14 +1,14 @@
import { FilterItem } from './filter-item.model';
export class Filter {
id: string;
name: string;
expanded: boolean;
/**
* undefined => all items can be selected => multiselect
* if max is set to 3, 3 items ca be selected => multiselect
* if max is set to 1 only one item can be selected => select
*/
max?: number;
items: FilterItem[];
id: string;
name: string;
expanded: boolean;
/**
* undefined => all items can be selected => multiselect
* if max is set to 3, 3 items ca be selected => multiselect
* if max is set to 1 only one item can be selected => select
*/
max?: number;
items: FilterItem[];
}

View File

@@ -22,7 +22,7 @@ export interface Product {
location: string;
ean: string;
imageId: string;
ssc: string,
ssc: string;
sscText: string;
storeStatusCode: number;
}

View File

@@ -1,4 +1,4 @@
export interface RecentArticleSearch {
id: number;
name: string;
id: number;
name: string;
}

View File

@@ -1,13 +1,5 @@
import {
RemissionProcess,
RemissionProduct,
ShippingDocument,
} from '@isa/remission';
import {
RemissionActiveView,
RemissionFinishingProcessStatus,
RemissionResourceType,
} from '../../modules/remission/models';
import { RemissionProcess, RemissionProduct, ShippingDocument } from '@isa/remission';
import { RemissionActiveView, RemissionFinishingProcessStatus, RemissionResourceType } from '../../modules/remission/models';
export interface Remission {
remissionProcessCreated?: boolean;

View File

@@ -62,12 +62,7 @@ export class Address {
}
export class Organisation {
constructor(
public name?: string,
public extraAddress?: string,
public department?: string,
public vatId?: string
) {}
constructor(public name?: string, public extraAddress?: string, public department?: string, public vatId?: string) {}
}
export class Features {

View File

@@ -2,4 +2,3 @@
export * from './modal.component';
export * from './modal.module';
// end:ng42.barrel

View File

@@ -1,9 +1,7 @@
<div class="modal-container">
<ng-container [ngSwitch]="contentType">
<ng-container *ngSwitchCase="'template'">
<ng-container
*ngTemplateOutlet="content; context: context"
></ng-container>
<ng-container *ngTemplateOutlet="content; context: context"></ng-container>
</ng-container>
<ng-container *ngSwitchCase="'component'">

View File

@@ -1,10 +1,4 @@
import {
Component,
OnInit,
ChangeDetectionStrategy,
TemplateRef,
Type,
} from '@angular/core';
import { Component, OnInit, ChangeDetectionStrategy, TemplateRef, Type } from '@angular/core';
import { IsaModalOverlayRef } from '../isa-modal-overlay-ref';
import { ModalContent } from '../defs';

View File

@@ -6,14 +6,8 @@ import { ModalDialogData } from './modal-dialog-data';
export class IsaModalOverlayRef<T = any> {
afterClosed$ = new Subject<OverlayCloseEvent<T>>();
constructor(
public overlay: OverlayRef,
public content: ModalContent,
public data: ModalDialogData<T>
) {
this.overlay
.backdropClick()
.subscribe(() => this.closeModal('backdropClick', null));
constructor(public overlay: OverlayRef, public content: ModalContent, public data: ModalDialogData<T>) {
this.overlay.backdropClick().subscribe(() => this.closeModal('backdropClick', null));
}
public close(data?: T) {

View File

@@ -1,11 +1,4 @@
import {
Injectable,
Inject,
TemplateRef,
Injector,
Type,
InjectionToken,
} from '@angular/core';
import { Injectable, Inject, TemplateRef, Injector, Type, InjectionToken } from '@angular/core';
import { DOCUMENT } from '@angular/common';
import { Overlay, OverlayConfig, OverlayRef } from '@angular/cdk/overlay';
import { config } from './default-dialog.config';
@@ -19,16 +12,9 @@ import { ModalDialogData } from './modal-dialog-data';
export class ModalService {
modal: OverlayRef;
constructor(
@Inject(DOCUMENT) private document: Document,
private overlay: Overlay,
private injector: Injector
) {}
constructor(@Inject(DOCUMENT) private document: Document, private overlay: Overlay, private injector: Injector) {}
open<T>(
content: ModalContent,
data: ModalDialogData<T>
): IsaModalOverlayRef<T> {
open<T>(content: ModalContent, data: ModalDialogData<T>): IsaModalOverlayRef<T> {
if (this.modal) {
this.modal.dispose();
}
@@ -38,9 +24,7 @@ export class ModalService {
const modalRef = new IsaModalOverlayRef<T>(overlayRef, content, data);
const injector = this.createInjector(modalRef, { ...data, ref: modalRef });
overlayRef.attach(
new ComponentPortal(ModalDialogueSharedComponent, null, injector)
);
overlayRef.attach(new ComponentPortal(ModalDialogueSharedComponent, null, injector));
return modalRef;
}

View File

@@ -1,6 +1,4 @@
import { OverlayContent } from './defs';
import { InjectionToken } from '@angular/core';
export const OVERLAY_DATA = new InjectionToken<
OverlayContent<{ queryString: string }>
>('OVERLAY_DATA');
export const OVERLAY_DATA = new InjectionToken<OverlayContent<{ queryString: string }>>('OVERLAY_DATA');

View File

@@ -1,10 +1,4 @@
import {
trigger,
transition,
style,
animate,
keyframes,
} from '@angular/animations';
import { trigger, transition, style, animate, keyframes } from '@angular/animations';
export const topRightInOut = trigger('topRightInOut', [
transition(':enter', [
@@ -15,10 +9,7 @@ export const topRightInOut = trigger('topRightInOut', [
overflow: 'hidden',
opacity: '0',
}),
animate(
300,
style({ width: '100%', height: '100%', opacity: '1', borderRadius: '0%' })
),
animate(300, style({ width: '100%', height: '100%', opacity: '1', borderRadius: '0%' })),
]),
transition('* => out', [
style({

View File

@@ -61,11 +61,7 @@ export class CollectingShelfService {
throw new Error(response.message);
}
return {
result: this.mapper.fromOrderItemListItemDTOArrayToCollectingShelfOrder(
response.result,
this,
skip === 0
),
result: this.mapper.fromOrderItemListItemDTOArrayToCollectingShelfOrder(response.result, this, skip === 0),
hits: response.hits,
};
})
@@ -73,9 +69,7 @@ export class CollectingShelfService {
}
searchShelfCached() {
return this.store
.select(CollectingShelfSelectors.getCachedResults)
.pipe(filter((data) => !isNullOrUndefined(data)));
return this.store.select(CollectingShelfSelectors.getCachedResults).pipe(filter((data) => !isNullOrUndefined(data)));
}
searchShelfHasResults(input: string, branchNumber: string): Observable<number> {
@@ -153,9 +147,7 @@ export class CollectingShelfService {
);
}
getOrderItemSubsetByOrderItemSubsetId(
orderItemSubsetId: number
): Observable<OrderItemSubsetDTO> {
getOrderItemSubsetByOrderItemSubsetId(orderItemSubsetId: number): Observable<OrderItemSubsetDTO> {
return this.omsService.OrderGetOrderItemSubset(orderItemSubsetId).pipe(
map((response) => {
if (response.error) {
@@ -166,18 +158,13 @@ export class CollectingShelfService {
);
}
getOrdersByCompartmentNumber(
compartmentNumbers: string[],
orderId: number
): Observable<OrderDTO> {
getOrdersByCompartmentNumber(compartmentNumbers: string[], orderId: number): Observable<OrderDTO> {
return this.omsService.OrderGetOrdersByCompartment(compartmentNumbers).pipe(
map((response) => {
if (response.error) {
throw new Error(response.message);
}
return response.result
? response.result.find((o) => +o.id === +orderId)
: null;
return response.result ? response.result.find((o) => +o.id === +orderId) : null;
})
);
}
@@ -236,16 +223,8 @@ export class CollectingShelfService {
);
}
extendPickUpPeriod(
orderId: number,
orderItemId: number,
orderItemSubsetId: number,
date: Date
): Observable<OrderItemSubsetDTO> {
const compartmentStop = this.datepipe.transform(
date,
BACKEND_API_TIMESTAMP_FORMAT
);
extendPickUpPeriod(orderId: number, orderItemId: number, orderItemSubsetId: number, date: Date): Observable<OrderItemSubsetDTO> {
const compartmentStop = this.datepipe.transform(date, BACKEND_API_TIMESTAMP_FORMAT);
const params = <OrderService.OrderPatchOrderItemSubsetParams>{
orderId,
orderItemId,
@@ -264,16 +243,8 @@ export class CollectingShelfService {
);
}
updateEstimatedShippingDate(
orderId: number,
orderItemId: number,
orderItemSubsetId: number,
date: Date
): Observable<OrderItemSubsetDTO> {
const estimatedShippingDate = this.datepipe.transform(
date,
BACKEND_API_TIMESTAMP_FORMAT
);
updateEstimatedShippingDate(orderId: number, orderItemId: number, orderItemSubsetId: number, date: Date): Observable<OrderItemSubsetDTO> {
const estimatedShippingDate = this.datepipe.transform(date, BACKEND_API_TIMESTAMP_FORMAT);
const params = <OrderService.OrderPatchOrderItemSubsetParams>{
orderId,
orderItemId,
@@ -292,11 +263,7 @@ export class CollectingShelfService {
);
}
patchOrderItem(
orderId: number,
orderItemId: number,
orderItem: OrderItemDTO
) {
patchOrderItem(orderId: number, orderItemId: number, orderItem: OrderItemDTO) {
const params = <OrderService.OrderPatchOrderItemParams>{
orderId,
orderItemId,
@@ -381,9 +348,7 @@ export class CollectingShelfService {
if (response.error) {
throw new Error(response.message);
}
return response.result && response.result[0]
? response.result[0].supplierDescription
: null;
return response.result && response.result[0] ? response.result[0].supplierDescription : null;
})
);
}
@@ -410,23 +375,14 @@ export class CollectingShelfService {
);
}
processOrderCompartmentNumber(
orders: OrderItemListItemDTO[],
order: OrderItemListItemDTO,
index: number,
firstBatch: boolean
) {
processOrderCompartmentNumber(orders: OrderItemListItemDTO[], order: OrderItemListItemDTO, index: number, firstBatch: boolean) {
const tempOrders = [...orders];
const prevOrders = tempOrders.slice(0, index);
let hideCompartmentNumber = false;
if (index === 0 && !firstBatch) {
const olderOrders = this.store.selectSnapshot(
CollectingShelfSelectors.getShelfOrders
);
const olderOrders = this.store.selectSnapshot(CollectingShelfSelectors.getShelfOrders);
if (olderOrders && olderOrders.length > 0) {
const filteredOrders = olderOrders.filter(
(t) => t.orderId === order.orderId
);
const filteredOrders = olderOrders.filter((t) => t.orderId === order.orderId);
if (
order.compartmentCode &&
order.processingStatus &&
@@ -435,10 +391,8 @@ export class CollectingShelfService {
filteredOrders[filteredOrders.length - 1] &&
filteredOrders[filteredOrders.length - 1].compartmentCode &&
filteredOrders[filteredOrders.length - 1].processingStatus &&
filteredOrders[filteredOrders.length - 1].compartmentCode ===
order.compartmentCode &&
filteredOrders[filteredOrders.length - 1].processingStatus ===
order.processingStatus
filteredOrders[filteredOrders.length - 1].compartmentCode === order.compartmentCode &&
filteredOrders[filteredOrders.length - 1].processingStatus === order.processingStatus
) {
hideCompartmentNumber = true;
}
@@ -451,10 +405,8 @@ export class CollectingShelfService {
prevOrders[prevOrders.length - 1] &&
prevOrders[prevOrders.length - 1].compartmentCode &&
prevOrders[prevOrders.length - 1].processingStatus &&
prevOrders[prevOrders.length - 1].compartmentCode ===
order.compartmentCode &&
prevOrders[prevOrders.length - 1].processingStatus ===
order.processingStatus
prevOrders[prevOrders.length - 1].compartmentCode === order.compartmentCode &&
prevOrders[prevOrders.length - 1].processingStatus === order.processingStatus
) {
hideCompartmentNumber = true;
}

View File

@@ -47,12 +47,7 @@ export class ContentHeaderService {
filter((url) => !isNullOrUndefined(url)),
switchMap((activeSection) => {
if (activeSection.includes('remission')) {
return this.remissionFilters$.pipe(
map(
(selectedFilters) =>
selectedFilters && !!Object.entries(selectedFilters).length
)
);
return this.remissionFilters$.pipe(map((selectedFilters) => selectedFilters && !!Object.entries(selectedFilters).length));
}
if (activeSection.includes('shelf')) {
@@ -114,22 +109,13 @@ export class ContentHeaderService {
const applicableBlacklist = this.blackList[type];
if (type === 'filter') {
const isOnWhiteList = !!applicableWhitelist.find(
(whitelistetUrl) =>
whitelistetUrl.includes(url) || url.includes(whitelistetUrl)
);
const isOnBlacklist = applicableBlacklist.find(
(blackListUrl) =>
blackListUrl.includes(url) || url.includes(blackListUrl)
);
const isOnWhiteList = !!applicableWhitelist.find((whitelistetUrl) => whitelistetUrl.includes(url) || url.includes(whitelistetUrl));
const isOnBlacklist = applicableBlacklist.find((blackListUrl) => blackListUrl.includes(url) || url.includes(blackListUrl));
return isOnWhiteList && !isOnBlacklist;
}
if (type === 'breadcrumbs') {
const isOnBlackList = !!applicableBlacklist.find(
(blacklistetUrl) =>
blacklistetUrl.includes(url) || url.includes(blacklistetUrl)
);
const isOnBlackList = !!applicableBlacklist.find((blacklistetUrl) => blacklistetUrl.includes(url) || url.includes(blacklistetUrl));
return !isOnBlackList;
}
}

View File

@@ -1,9 +1,6 @@
import { Injectable } from '@angular/core';
import { QueryTokenDTO } from '@swagger/cat';
import {
CustomerService as CustomerApiService,
PayerService,
} from '@swagger/crm';
import { CustomerService as CustomerApiService, PayerService } from '@swagger/crm';
import { map, switchMap, catchError } from 'rxjs/operators';
import { Observable, of, combineLatest, BehaviorSubject } from 'rxjs';
import { CustomerMapping } from '../mappings/customer.mapping';
@@ -31,11 +28,7 @@ import { CustomerFilters } from '../../modules/customer';
})
export class CustomerService {
addAddressError$ = new BehaviorSubject<any>(null);
constructor(
private customerService: CustomerApiService,
private mapper: CustomerMapping,
private payerService: PayerService
) {}
constructor(private customerService: CustomerApiService, private mapper: CustomerMapping, private payerService: PayerService) {}
createCustomer(_customer: User): Observable<User> {
const customer: CustomerDTO = this.mapper.fromUser(_customer);
@@ -104,9 +97,7 @@ export class CustomerService {
filter?: CustomerFilters
): Observable<CustomerSearchResponse> {
const noFilters = filter
? isNullOrUndefined(filter.bonuscard) &&
isNullOrUndefined(filter.guestaccount) &&
isNullOrUndefined(filter.onlineshop)
? isNullOrUndefined(filter.bonuscard) && isNullOrUndefined(filter.guestaccount) && isNullOrUndefined(filter.onlineshop)
? true
: false
: false;
@@ -121,15 +112,9 @@ export class CustomerService {
filter:
filter && !noFilters
? {
['bonuscard']: !isNullOrUndefined(filter.bonuscard)
? String(filter.bonuscard)
: undefined,
['guestaccount']: !isNullOrUndefined(filter.guestaccount)
? String(filter.guestaccount)
: undefined,
['onlineshop']: !isNullOrUndefined(filter.onlineshop)
? String(filter.onlineshop)
: undefined,
['bonuscard']: !isNullOrUndefined(filter.bonuscard) ? String(filter.bonuscard) : undefined,
['guestaccount']: !isNullOrUndefined(filter.guestaccount) ? String(filter.guestaccount) : undefined,
['onlineshop']: !isNullOrUndefined(filter.onlineshop) ? String(filter.onlineshop) : undefined,
}
: undefined,
};
@@ -140,9 +125,7 @@ export class CustomerService {
throw new Error(response.message);
}
return {
customers: response.result.map((t) =>
this.mapper.customerInfoDTOtoUser(t)
),
customers: response.result.map((t) => this.mapper.customerInfoDTOtoUser(t)),
hits: response.hits,
message: response.message,
};
@@ -150,44 +133,33 @@ export class CustomerService {
);
}
getCustomer(
customer$: Observable<ResponseArgsOfCustomerDTO>
): Observable<User> {
getCustomer(customer$: Observable<ResponseArgsOfCustomerDTO>): Observable<User> {
return customer$.pipe(
map((response: ResponseArgsOfCustomerDTO) => {
if (response.error) {
throw new Error(response.message);
}
return {
shippingAddresses: response.result.shippingAddresses.map(
(addressEnity) => addressEnity.id
),
shippingAddresses: response.result.shippingAddresses.map((addressEnity) => addressEnity.id),
user: this.mapper.customerDTOtoUser(response.result),
};
}),
switchMap((customerResult) => {
const user = customerResult.user;
if (
!customerResult.shippingAddresses ||
customerResult.shippingAddresses.length === 0
) {
if (!customerResult.shippingAddresses || customerResult.shippingAddresses.length === 0) {
return of(customerResult.user);
}
const observablesOfShippingAddresses = customerResult.shippingAddresses.map(
(t) => {
return this.customerService.CustomerGetShippingaddress(t).pipe(
map((response) => {
if (response.error) {
throw new Error(response.message);
}
return response.result;
})
);
}
);
const shippingAddresses$ = combineLatest(
observablesOfShippingAddresses
);
const observablesOfShippingAddresses = customerResult.shippingAddresses.map((t) => {
return this.customerService.CustomerGetShippingaddress(t).pipe(
map((response) => {
if (response.error) {
throw new Error(response.message);
}
return response.result;
})
);
});
const shippingAddresses$ = combineLatest(observablesOfShippingAddresses);
return shippingAddresses$.pipe(
switchMap((address: ShippingAddressDTO[]) => {
const updatedUser = user;
@@ -213,39 +185,34 @@ export class CustomerService {
}),
switchMap((customer: User) => {
const updateCustomer = customer;
return this.customerService
.CustomerGetAssignedPayersByCustomerId(customer.id)
.pipe(
map((response) => {
if (response.error) {
throw new Error(response.message);
}
return { customer: customer, assignedPayers: response.result };
}),
switchMap((response) => {
if (
Array.isArray(response.assignedPayers) &&
response.assignedPayers.length > 0
) {
const invoiceAddresses = response.assignedPayers.map((t) => {
return {
...this.mapper.fromAssignedPayerDtoToAddress(t),
synced: true,
};
});
const defaultAddress = invoiceAddresses.reduce((ad1, ad2) => {
if (ad1.defaultSince >= ad2.defaultSince) {
return ad1;
}
return ad2;
});
updateCustomer.poossible_invoice_addresses = invoiceAddresses;
updateCustomer.invoice_address = defaultAddress;
}
return this.customerService.CustomerGetAssignedPayersByCustomerId(customer.id).pipe(
map((response) => {
if (response.error) {
throw new Error(response.message);
}
return { customer: customer, assignedPayers: response.result };
}),
switchMap((response) => {
if (Array.isArray(response.assignedPayers) && response.assignedPayers.length > 0) {
const invoiceAddresses = response.assignedPayers.map((t) => {
return {
...this.mapper.fromAssignedPayerDtoToAddress(t),
synced: true,
};
});
const defaultAddress = invoiceAddresses.reduce((ad1, ad2) => {
if (ad1.defaultSince >= ad2.defaultSince) {
return ad1;
}
return ad2;
});
updateCustomer.poossible_invoice_addresses = invoiceAddresses;
updateCustomer.invoice_address = defaultAddress;
}
return of(updateCustomer);
})
);
return of(updateCustomer);
})
);
})
);
}
@@ -264,9 +231,7 @@ export class CustomerService {
throw new Error(response.message);
}
return {
customers: response.result.map((t) =>
this.mapper.customerInfoDTOtoUser(t)
),
customers: response.result.map((t) => this.mapper.customerInfoDTOtoUser(t)),
hits: 0,
};
})
@@ -294,32 +259,28 @@ export class CustomerService {
isDefault: true,
};
if (shippingAddress.synced === true) {
return this.customerService
.CustomerModifyShippingAddressFlag(params)
.pipe(
map((response) => {
if (response.error) {
throw new Error(response.message);
}
return response.result;
})
);
return this.customerService.CustomerModifyShippingAddressFlag(params).pipe(
map((response) => {
if (response.error) {
throw new Error(response.message);
}
return response.result;
})
);
} else {
return this.addShippingAddress(customerId, {
...shippingAddress,
id: null,
}).pipe(
switchMap(() => {
return this.customerService
.CustomerModifyShippingAddressFlag(params)
.pipe(
map((response) => {
if (response.error) {
throw new Error(response.message);
}
return response.result;
})
);
return this.customerService.CustomerModifyShippingAddressFlag(params).pipe(
map((response) => {
if (response.error) {
throw new Error(response.message);
}
return response.result;
})
);
})
);
}
@@ -371,10 +332,7 @@ export class CustomerService {
if (!isNullOrUndefined(shippingAddress.id)) {
const params = {
shippingAddressId: shippingAddress.id,
shippingAddress: this.mapper.fromAddressToShippingAddressDTO(
shippingAddress,
!isNullOrUndefined(shippingAddress.id)
),
shippingAddress: this.mapper.fromAddressToShippingAddressDTO(shippingAddress, !isNullOrUndefined(shippingAddress.id)),
customerId: customerId,
};
return this.customerService.CustomerUpdateShippingAddress(params).pipe(
@@ -402,10 +360,7 @@ export class CustomerService {
);
} else {
const params = {
shippingAddress: this.mapper.fromAddressToShippingAddressDTO(
shippingAddress,
!isNullOrUndefined(shippingAddress.id)
),
shippingAddress: this.mapper.fromAddressToShippingAddressDTO(shippingAddress, !isNullOrUndefined(shippingAddress.id)),
customerId: customerId,
};
return this.customerService.CustomerCreateShippingAddress(params).pipe(
@@ -465,17 +420,15 @@ export class CustomerService {
payerId: payerResponse.result.id,
isDefault: true,
};
return this.customerService
.CustomerAddPayerReference(referenceParamsparams)
.pipe(
map((response) => {
if (response.error) {
throw new Error(response.message);
}
this.addAddressError$.next(undefined);
return response.result.payer.data;
})
);
return this.customerService.CustomerAddPayerReference(referenceParamsparams).pipe(
map((response) => {
if (response.error) {
throw new Error(response.message);
}
this.addAddressError$.next(undefined);
return response.result.payer.data;
})
);
})
);
} else {
@@ -513,10 +466,7 @@ export class CustomerService {
if (response.error) {
throw new Error(response.message);
}
return response.result.map(
(t, index) =>
<Country>{ index, id: t.id, key: t.isO3166_A_3, value: t.name }
);
return response.result.map((t, index) => <Country>{ index, id: t.id, key: t.isO3166_A_3, value: t.name });
})
);
}

View File

@@ -1,19 +1,7 @@
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/internal/Observable';
import {
Router,
RouterEvent,
NavigationStart,
ActivationStart,
ActivatedRoute,
} from '@angular/router';
import {
map,
distinctUntilChanged,
filter,
switchMap,
tap,
} from 'rxjs/operators';
import { Router, RouterEvent, NavigationStart, ActivationStart, ActivatedRoute } from '@angular/router';
import { map, distinctUntilChanged, filter, switchMap, tap } from 'rxjs/operators';
import { isNullOrUndefined } from 'util';
@Injectable({ providedIn: 'root' })

View File

@@ -3,7 +3,7 @@ import { Subject, Observable } from 'rxjs';
import { take, share } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
providedIn: 'root',
})
export class ModalConfirmationService {
private readonly _afterClosed = new Subject<boolean>();

View File

@@ -14,7 +14,7 @@ import { Breadcrumb } from '../models/breadcrumb.model';
import { SetBranchProcessCurrentPath } from '../store/actions/branch-process.actions';
@Injectable({
providedIn: 'root'
providedIn: 'root',
})
export class ModuleSwitcherService {
moduleSwitcher$ = new Subject<ModuleSwitcher>();
@@ -45,7 +45,7 @@ export class ModuleSwitcherService {
extras = { queryParams: currentProcess.currentRouteQueryParams };
}
}
this.router.navigate(commands, extras).then(resolve => {
this.router.navigate(commands, extras).then((resolve) => {
if (resolve) {
this.moduleSwitcher$.next(ModuleSwitcher.Customer);
this.store.dispatch(new AppSwitchModule(ModuleSwitcher.Customer));
@@ -87,7 +87,7 @@ export class ModuleSwitcherService {
new ResetBreadcrumbsTo(
<Breadcrumb>{
name: 'Remission',
path: path
path: path,
},
'remission',
true,

View File

@@ -1,7 +1,7 @@
export const NOTIFY = 'NOTIFY';
export class Notify {
static readonly type = NOTIFY;
static readonly type = NOTIFY;
constructor(public payload: number) {}
constructor(public payload: number) {}
}

View File

@@ -1,11 +1,5 @@
import { Remission } from '../../models/remission.model';
import {
RemissionProcess,
RemissionProduct,
RemissionSupplier,
ShippingDocument,
RemissionFilter,
} from '@isa/remission';
import { RemissionProcess, RemissionProduct, RemissionSupplier, ShippingDocument, RemissionFilter } from '@isa/remission';
import { RemissionResourceType } from '../../../modules/remission/models/remission-resource-type.model';
import { RemissionFinishingProcessStatus } from '../../../modules/remission/models/remission-finishing-process-status.enum';
import { RemissionActiveView } from '../../../modules/remission/models';
@@ -22,30 +16,22 @@ export const SET_REMISSION_SOURCE = '[REMISSION] Set source';
export const SET_REMISSION_TARGET = '[REMISSION] Set target';
export const SET_REMISSION_PRODUCTS = '[REMISSION] Set products';
export const SET_SHIPPING_DOCUMENT = '[REMISSION] Set shipping document';
export const COMPLETE_SHIPPING_DOCUMENT =
'[REMISSION] Complete shipping document';
export const COMPLETE_SHIPPING_DOCUMENT = '[REMISSION] Complete shipping document';
export const RESET_SHIPPING_DOCUMENT = '[REMISSION] Reset shipping document';
export const SET_REMISSION_SEARCHED_PRODUCT =
'[REMISSION] Set remission searched product';
export const SET_REMISSION_SEARCHED_PRODUCT = '[REMISSION] Set remission searched product';
export const ACTIVATE_REMISSION_REMINDER = '[REMISSION] Activate reminder';
export const SET_REMISSION_FINISHED_PROCESS_STATUS =
'[REMISSION] Set remission finished process status';
export const SET_REMISSION_SCANNED_CONTAINER_ID =
'[REMISSION] Set remission scanned container id';
export const SET_REMISSION_FINISHED_PROCESS_STATUS = '[REMISSION] Set remission finished process status';
export const SET_REMISSION_SCANNED_CONTAINER_ID = '[REMISSION] Set remission scanned container id';
export const DELETE_SHIPPING_DOCUMENT = '[REMISSION] Delete shipping document';
export const SET_ALL_OPEN_REMISSIONS = '[REMISSION] Set all open remissions';
export const SET_ALL_REMISSIONS = '[REMISSION] Set all remissions';
export const SET_REMISSION_FILTER = '[REMISSION] Set remission filter';
export const SET_REMISSION_ISLOADING = '[REMISSION] Set remission isLoading';
export const SET_REMISSION_ACTIVE_VIEW =
'[REMISSION] Set remission active view';
export const REQUEST_UPDATE_SHIPPING_DOCUMENT =
'[REMISSION] Update shipping document';
export const SET_REMISSION_ACTIVE_VIEW = '[REMISSION] Set remission active view';
export const REQUEST_UPDATE_SHIPPING_DOCUMENT = '[REMISSION] Update shipping document';
export const REQUEST_DELETE_SHIPPING_DOCUMENT =
'[REMISSION] [API] Send delete shipping document request';
export const REQUEST_UPDATE_REMISSION_FILTER =
'[REMISSION] [API] Send update remission filter request';
export const REQUEST_DELETE_SHIPPING_DOCUMENT = '[REMISSION] [API] Send delete shipping document request';
export const REQUEST_UPDATE_REMISSION_FILTER = '[REMISSION] [API] Send update remission filter request';
export class SetRemissionCreated {
static readonly type = SET_REMISSION_CREATED;
@@ -68,10 +54,7 @@ export class SetRemissionCompleted {
export class SetRemissionProcess {
static readonly type = SET_REMISSION_PROCESS;
constructor(
public remissionProcess: RemissionProcess,
public initialValue: boolean = false
) {}
constructor(public remissionProcess: RemissionProcess, public initialValue: boolean = false) {}
}
export class ReloadRemission {
@@ -101,10 +84,7 @@ export class SetRemissionSource {
export class SetRemissionTarget {
static readonly type = SET_REMISSION_TARGET;
constructor(
public target: RemissionSupplier,
public source: RemissionResourceType
) {}
constructor(public target: RemissionSupplier, public source: RemissionResourceType) {}
}
export class SetRemissionProducts {
@@ -179,10 +159,7 @@ export class RequestDeleteShippingDocument {
export class RequestUpdateRemissionFilter {
static readonly type = REQUEST_UPDATE_REMISSION_FILTER;
constructor(
public remissionProcessId: number,
public filter: Partial<RemissionFilter>
) {}
constructor(public remissionProcessId: number, public filter: Partial<RemissionFilter>) {}
}
export class UpdateShippingDocuent {
@@ -196,10 +173,7 @@ export class UpdateShippingDocuent {
export class SetRemissionFilter {
static readonly type = SET_REMISSION_FILTER;
constructor(
public remissionProcessId: number,
public filter: RemissionFilter
) {}
constructor(public remissionProcessId: number, public filter: RemissionFilter) {}
}
export class SetRemissionIsLoading {

View File

@@ -10,15 +10,7 @@ import {
SetRemissionProcess,
SetRemissionShippingDocument,
} from '../actions/remission.actions';
import {
flatMap,
filter,
map,
catchError,
switchMap,
first,
withLatestFrom,
} from 'rxjs/operators';
import { flatMap, filter, map, catchError, switchMap, first, withLatestFrom } from 'rxjs/operators';
import { RemissionService, RemissionProcess } from '@isa/remission';
import { of } from 'rxjs';
import { ResetBreadcrumbsTo } from '../actions/breadcrumb.actions';
@@ -27,12 +19,7 @@ import { Router } from '@angular/router';
@Injectable({ providedIn: 'root' })
export class RemissionStateHandler {
constructor(
private actions$: Actions,
private store: Store,
private remissionService: RemissionService,
private router: Router
) {
constructor(private actions$: Actions, private store: Store, private remissionService: RemissionService, private router: Router) {
this.registerHandlers();
}
@@ -53,14 +40,10 @@ export class RemissionStateHandler {
)
)
.subscribe((process) => {
const activeShippingDocument = process.shippingDocuments.find(
(document) => !document.isCompleted
);
const activeShippingDocument = process.shippingDocuments.find((document) => !document.isCompleted);
if (activeShippingDocument) {
this.store.dispatch(
new SetRemissionShippingDocument(activeShippingDocument)
);
this.store.dispatch(new SetRemissionShippingDocument(activeShippingDocument));
}
return this.store.dispatch(new SetRemissionProcess(process));
@@ -92,9 +75,7 @@ export class RemissionStateHandler {
})
)
.subscribe(([result, process]) => {
this.store.dispatch(
new SetRemissionFilter(result.remissionProcessId, result.filter)
);
this.store.dispatch(new SetRemissionFilter(result.remissionProcessId, result.filter));
this.store.dispatch(new SetRemissionProcess(process));
});
}
@@ -104,24 +85,16 @@ export class RemissionStateHandler {
.pipe(ofActionDispatched(RequestDeleteShippingDocument))
.pipe(
map((action: RequestDeleteShippingDocument) => action.remissionProcess),
filter(
(action) =>
!!action.shippingDocuments && !!action.shippingDocuments[0]
),
filter((action) => !!action.shippingDocuments && !!action.shippingDocuments[0]),
flatMap((action: RemissionProcess) =>
this.remissionService
.deleteShippingDocument({
remissionProcessId: action.id,
externalId: action.externalId,
shippingDocumentId:
action.shippingDocuments &&
action.shippingDocuments[0] &&
action.shippingDocuments[0].id,
shippingDocumentId: action.shippingDocuments && action.shippingDocuments[0] && action.shippingDocuments[0].id,
})
.pipe(
filter(
(response) => !!response.result && response.result.deleted
),
filter((response) => !!response.result && response.result.deleted),
map((_) => action.id),
catchError((err) => {
console.error(err);
@@ -132,9 +105,7 @@ export class RemissionStateHandler {
)
)
.subscribe((remissionProcessId) => {
this.store.dispatch(
new DeleteRemissionShippingDocument(remissionProcessId)
);
this.store.dispatch(new DeleteRemissionShippingDocument(remissionProcessId));
this.store.dispatch(new ResetRemissionState());
this.navigateToStartPage();
});
@@ -153,10 +124,6 @@ export class RemissionStateHandler {
)
);
this.router
.navigate([path])
.then((_) =>
this.store.dispatch(new SetBranchProcessCurrentPath(path, true))
);
this.router.navigate([path]).then((_) => this.store.dispatch(new SetBranchProcessCurrentPath(path, true)));
}
}

View File

@@ -22,7 +22,7 @@ export class CountrySelector {
@Selector([CountryState])
static getDeutchlandIterable(countryState: CountryStateModel): Country[] {
const countries: Country[] = mapToIterable(countryState.countries);
const deutchland = countries.filter(country => country.key === 'DEU');
const deutchland = countries.filter((country) => country.key === 'DEU');
return deutchland as Country[];
}

View File

@@ -9,7 +9,7 @@ export class CustomerSelectors {
static getUsers(processState: ProcessStateModel, customerState: CustomerStateModel) {
return (processId: number) => {
const customerIds = processState.processes[processId].customerIds;
const customers = customerIds.map(t => customerState.customers[t]);
const customers = customerIds.map((t) => customerState.customers[t]);
return customers;
};
}

View File

@@ -25,18 +25,12 @@ export class ProcessSelectors {
}
@Selector([AppState, ProcessState])
static getCurrentProcess(
state: AppStateModel,
processState: ProcessStateModel
): Process {
static getCurrentProcess(state: AppStateModel, processState: ProcessStateModel): Process {
return processState.processes[state.currentProcesssId];
}
@Selector([AppState, ProcessState])
static getCurrentProcessId(
state: AppStateModel,
processState: ProcessStateModel
): number {
static getCurrentProcessId(state: AppStateModel, processState: ProcessStateModel): number {
return processState.processes[state.currentProcesssId].id;
}
@@ -46,10 +40,7 @@ export class ProcessSelectors {
}
@Selector([AppState, ProcessState])
static getSelectedProduct(
state: AppStateModel,
processState: ProcessStateModel
) {
static getSelectedProduct(state: AppStateModel, processState: ProcessStateModel) {
const currentProcess = processState.processes[state.currentProcesssId];
if (currentProcess) {
return currentProcess.selectedItem;
@@ -57,10 +48,7 @@ export class ProcessSelectors {
}
@Selector([AppState, ProcessState])
static getCurrentProcessCustomerNotificationFlag(
state: AppStateModel,
processState: ProcessStateModel
) {
static getCurrentProcessCustomerNotificationFlag(state: AppStateModel, processState: ProcessStateModel) {
const currentProcess = processState.processes[state.currentProcesssId];
if (currentProcess) {
return currentProcess.customerNotificationFlag;
@@ -68,10 +56,7 @@ export class ProcessSelectors {
}
@Selector([AppState, ProcessState])
static getScrollPositionForProduct(
state: AppStateModel,
processState: ProcessStateModel
) {
static getScrollPositionForProduct(state: AppStateModel, processState: ProcessStateModel) {
const currentProcess = processState.processes[state.currentProcesssId];
if (currentProcess) {
return currentProcess.productScrollTo;
@@ -79,10 +64,7 @@ export class ProcessSelectors {
}
@Selector([AppState, ProcessState])
static getActiveUserId(
state: AppStateModel,
processState: ProcessStateModel
) {
static getActiveUserId(state: AppStateModel, processState: ProcessStateModel) {
const currentProcess = processState.processes[state.currentProcesssId];
if (currentProcess) {
return currentProcess.activeCustomer;
@@ -90,25 +72,15 @@ export class ProcessSelectors {
}
@Selector([AppState, ProcessState])
static getDetailsUserId(
state: AppStateModel,
processState: ProcessStateModel
) {
static getDetailsUserId(state: AppStateModel, processState: ProcessStateModel) {
const currentProcess = processState.processes[state.currentProcesssId];
if (
currentProcess &&
(!currentProcess.onlineCustomerCreationError ||
currentProcess.onlineCustomerCreationError.error === false)
) {
if (currentProcess && (!currentProcess.onlineCustomerCreationError || currentProcess.onlineCustomerCreationError.error === false)) {
return currentProcess.detailsCustomer;
}
}
@Selector([AppState, ProcessState])
static getUniqueIdentifier(
state: AppStateModel,
processState: ProcessStateModel
) {
static getUniqueIdentifier(state: AppStateModel, processState: ProcessStateModel) {
const currentProcess = processState.processes[state.currentProcesssId];
if (currentProcess) {
return currentProcess.uniqueIdentifier;
@@ -116,10 +88,7 @@ export class ProcessSelectors {
}
@Selector([AppState, ProcessState])
static getCustomerSearch(
state: AppStateModel,
processState: ProcessStateModel
) {
static getCustomerSearch(state: AppStateModel, processState: ProcessStateModel) {
return processState.processes[state.currentProcesssId].customerSearch;
}
@@ -134,46 +103,27 @@ export class ProcessSelectors {
}
@Selector([AppState, ProcessState])
static getFinishedOrders(
state: AppStateModel,
processState: ProcessStateModel
) {
static getFinishedOrders(state: AppStateModel, processState: ProcessStateModel) {
return processState.processes[state.currentProcesssId].finishedOrder;
}
@Selector([AppState, ProcessState])
static getArticleSearchErrorStatus(
state: AppStateModel,
processState: ProcessStateModel
) {
return processState.processes[state.currentProcesssId]
.articleSearchErrorStatus;
static getArticleSearchErrorStatus(state: AppStateModel, processState: ProcessStateModel) {
return processState.processes[state.currentProcesssId].articleSearchErrorStatus;
}
@Selector([AppState, ProcessState])
static getPreviousRoute(
state: AppStateModel,
processState: ProcessStateModel
) {
static getPreviousRoute(state: AppStateModel, processState: ProcessStateModel) {
return processState.processes[state.currentProcesssId].previousRoute;
}
@Selector([AppState, ProcessState])
static getCurrentRoute(
state: AppStateModel,
processState: ProcessStateModel
) {
return getProperty(
processState,
`processes.${state.currentProcesssId}.currentRoute`
);
static getCurrentRoute(state: AppStateModel, processState: ProcessStateModel) {
return getProperty(processState, `processes.${state.currentProcesssId}.currentRoute`);
}
@Selector([AppState, ProcessState])
static getProductFilters(
state: AppStateModel,
processState: ProcessStateModel
) {
static getProductFilters(state: AppStateModel, processState: ProcessStateModel) {
return processState.processes[state.currentProcesssId].productSearchFilters;
}

View File

@@ -44,9 +44,7 @@ export class RemissionSelectors {
}
@Selector([RemissionState])
static getRemissionFinishingProcessStatus(
remissionState: RemissionStateModel
) {
static getRemissionFinishingProcessStatus(remissionState: RemissionStateModel) {
const remission = remissionState.remission;
return remission.remissionFinishingProcessStatus;
}
@@ -64,27 +62,20 @@ export class RemissionSelectors {
remission.remissionProcessStarted &&
!remission.remissionProcessCompleted &&
!remission.blockReminder &&
remission.remissionFinishingProcessStatus !==
RemissionFinishingProcessStatus.containerScanned
remission.remissionFinishingProcessStatus !== RemissionFinishingProcessStatus.containerScanned
);
}
@Selector([RemissionState])
static getRemissionShippingDocumentstatus(
remissionState: RemissionStateModel
) {
static getRemissionShippingDocumentstatus(remissionState: RemissionStateModel) {
const remission = remissionState.remission;
return remission.shippingDocumentCreated;
}
@Selector([RemissionState])
static getRemissionShippingDocumentProductCount(
remissionState: RemissionStateModel
) {
static getRemissionShippingDocumentProductCount(remissionState: RemissionStateModel) {
const remission = remissionState.remission;
return remission.shippingDocument
? remission.shippingDocument.products.length
: 0;
return remission.shippingDocument ? remission.shippingDocument.products.length : 0;
}
@Selector([RemissionState])
@@ -94,16 +85,13 @@ export class RemissionSelectors {
if (remission && remission.remissionProcess) {
const source = remission.source;
const target = remission.target;
return remission.remissionProcess[source][target][filterId]
.filterGroups;
return remission.remissionProcess[source][target][filterId].filterGroups;
}
};
}
@Selector([RemissionState])
static getRemissionSelectedOptions(
remissionState: RemissionStateModel
): string[] {
static getRemissionSelectedOptions(remissionState: RemissionStateModel): string[] {
const remission = remissionState.remission;
if (remission && remission.remissionProcess) {
const filter = remission.remissionProcess.filter;
@@ -227,10 +215,7 @@ export class RemissionSelectors {
@Selector([RemissionState])
static getRemissionSupplierId(remissionState: RemissionStateModel) {
const remission = remissionState.remission;
const supplier =
remission.remissionProcess &&
remission.remissionProcess.filter &&
remission.remissionProcess.filter.target;
const supplier = remission.remissionProcess && remission.remissionProcess.filter && remission.remissionProcess.filter.target;
return supplier && supplier.id;
}

View File

@@ -1,9 +1,6 @@
import { Selector, StateContext, createSelector } from '@ngxs/store';
import { CustomerState, CustomerStateModel } from '../state/customer.state';
import {
BreadcrumbsState,
BreadcrumbsStateModel,
} from '../state/breadcrumbs.state';
import { BreadcrumbsState, BreadcrumbsStateModel } from '../state/breadcrumbs.state';
import { ProcessStateModel, ProcessState } from '../state/process.state';
import { EditCustomerData } from '../../models/edit-customer.model';
import { CartState, CartStateModel } from '../state/cart.state';
@@ -19,31 +16,19 @@ import { CartEntryStateModel, CartEntryState } from '../state/cart-entry.state';
import { BranchesStateModel, BranchState } from '../state/branches.state';
import { Cart } from '../../models/cart.model';
import { DisplayOrderDTO, DisplayOrderItemDTO } from '@swagger/oms';
import {
DeliveryType,
DeliveryOption,
} from '../../models/delivery-option.model';
import { DeliveryType, DeliveryOption } from '../../models/delivery-option.model';
import { OrderItem } from '../../models/order-item';
import { ProcessCartConfirmed } from '../../models/process-cart-confirmed.model';
import { User } from '../../models/user.model';
import { FilterItem } from '../../models/filter-item.model';
import {
CollectingShelfState,
CollectingShelfStateModel,
} from '../state/collecting-shelf.state';
import {
mapToIterable,
undefinedToEmptyStringOrValue,
} from '../../utils/app.utils';
import { CollectingShelfState, CollectingShelfStateModel } from '../state/collecting-shelf.state';
import { mapToIterable, undefinedToEmptyStringOrValue } from '../../utils/app.utils';
import { CollectingShelfOrder } from '../../models/collecting-shelf-order.model';
import { ItemDTO } from '@swagger/cat';
import { Process } from '../../models/process.model';
import { isNullOrUndefined } from 'util';
import { FilterType } from '../../models/filter-type.enum';
import {
BranchProcessState,
BranchProcessStateModel,
} from '../state/branch-process.state';
import { BranchProcessState, BranchProcessStateModel } from '../state/branch-process.state';
import { ModuleSwitcher } from '../../models/app-switcher.enum';
import { BranchProcess } from '../../models/branch-process.model';
@@ -71,18 +56,10 @@ export class SharedSelectors {
const currentProcessId = state.currentProcesssId;
const currentProcess = process.processes[currentProcessId];
if (
currentProcess &&
currentProcessId &&
breadcrumbs.activeCrumbs &&
breadcrumbs.activeCrumbs[currentProcessId]
) {
if (currentProcess && currentProcessId && breadcrumbs.activeCrumbs && breadcrumbs.activeCrumbs[currentProcessId]) {
const activeCrumbs = breadcrumbs.activeCrumbs[currentProcessId];
const currentBreadcrumbs = breadcrumbs.processesBreadcrumbs[
activeCrumbs
].find((t) => t.processId === currentProcessId);
const detailsCustomer =
customer.customers[currentProcess.detailsCustomer];
const currentBreadcrumbs = breadcrumbs.processesBreadcrumbs[activeCrumbs].find((t) => t.processId === currentProcessId);
const detailsCustomer = customer.customers[currentProcess.detailsCustomer];
return {
processId: currentProcessId,
customer: detailsCustomer,
@@ -94,11 +71,7 @@ export class SharedSelectors {
}
@Selector([AppState, ProcessState, CustomerState])
static getActiveCustomer(
state: AppStateModel,
process: ProcessStateModel,
customer: CustomerStateModel
): User {
static getActiveCustomer(state: AppStateModel, process: ProcessStateModel, customer: CustomerStateModel): User {
const currentProcessId = state.currentProcesssId;
const currentProcess = process.processes[currentProcessId];
@@ -110,11 +83,7 @@ export class SharedSelectors {
}
@Selector([AppState, ProcessState, CustomerState])
static getFinishedOrderCustomer(
state: AppStateModel,
process: ProcessStateModel,
customer: CustomerStateModel
): User {
static getFinishedOrderCustomer(state: AppStateModel, process: ProcessStateModel, customer: CustomerStateModel): User {
const currentProcessId = state.currentProcesssId;
const currentProcess = process.processes[currentProcessId];
@@ -126,11 +95,7 @@ export class SharedSelectors {
}
@Selector([ProcessState, CartState, CartEntryState])
static getCartTabData(
process: ProcessStateModel,
cartState: CartStateModel,
cartEntriesState: CartEntryStateModel
) {
static getCartTabData(process: ProcessStateModel, cartState: CartStateModel, cartEntriesState: CartEntryStateModel) {
return (processId: number) => {
if (process && processId) {
const currentProcess = process.processes[processId];
@@ -156,12 +121,7 @@ export class SharedSelectors {
}
@Selector([AppState, ProcessState, CartState, CartEntryState])
static cartHasItemsFor(
state: AppStateModel,
process: ProcessStateModel,
cart: CartStateModel,
cartEntry: CartEntryStateModel
) {
static cartHasItemsFor(state: AppStateModel, process: ProcessStateModel, cart: CartStateModel, cartEntry: CartEntryStateModel) {
return (option: DeliveryOption) => {
let found = false;
const currentProcessId = state.currentProcesssId;
@@ -187,12 +147,7 @@ export class SharedSelectors {
}
@Selector([AppState, ProcessState, CartState, CartEntryState])
static cartHasDownloadForProcess(
state: AppStateModel,
process: ProcessStateModel,
cart: CartStateModel,
cartEntry: CartEntryStateModel
) {
static cartHasDownloadForProcess(state: AppStateModel, process: ProcessStateModel, cart: CartStateModel, cartEntry: CartEntryStateModel) {
let found = false;
const currentProcessId = state.currentProcesssId;
if (currentProcessId && process && process.processes) {
@@ -216,11 +171,7 @@ export class SharedSelectors {
}
@Selector([AppState, ProcessState, CartState])
static cartEntriesOfCurrentProcessCart(
state: AppStateModel,
process: ProcessStateModel,
cart: CartStateModel
) {
static cartEntriesOfCurrentProcessCart(state: AppStateModel, process: ProcessStateModel, cart: CartStateModel) {
const currentProcessId = state.currentProcesssId;
if (currentProcessId) {
const currentProcess = process.processes[currentProcessId];
@@ -250,19 +201,12 @@ export class SharedSelectors {
if (entryId) {
const entry = cartEntry.cartEntries[entryId];
if (entry && entry.bookId) {
const currentProcessArticles =
product.products[currentProcessId];
const currentProcessArticles = product.products[currentProcessId];
if (currentProcessArticles) {
if (
currentProcessArticles &&
currentProcessArticles[entry.bookId]
) {
if (currentProcessArticles && currentProcessArticles[entry.bookId]) {
const article = currentProcessArticles[entry.bookId];
if (article && article.product && article.product.format) {
if (
article.product.format === 'EB' ||
article.product.format === 'DL'
) {
if (article.product.format === 'EB' || article.product.format === 'DL') {
response.push(article.id);
}
}
@@ -278,12 +222,7 @@ export class SharedSelectors {
}
@Selector([AppState, ProcessState, CartState, CartEntryState, ProductState])
static cartHasItems(
state: AppStateModel,
process: ProcessStateModel,
cart: CartStateModel,
cartEntry: CartEntryStateModel
): boolean {
static cartHasItems(state: AppStateModel, process: ProcessStateModel, cart: CartStateModel, cartEntry: CartEntryStateModel): boolean {
const currentProcessId = state.currentProcesssId;
let response = false;
if (currentProcessId) {
@@ -305,15 +244,7 @@ export class SharedSelectors {
return response;
}
@Selector([
AppState,
ProcessState,
CartState,
CustomerState,
ProductState,
CartEntryState,
BranchState,
])
@Selector([AppState, ProcessState, CartState, CustomerState, ProductState, CartEntryState, BranchState])
static getCart(
state: AppStateModel,
process: ProcessStateModel,
@@ -340,9 +271,7 @@ export class SharedSelectors {
cartEntries.forEach((cartEntryId: number) => {
const cartEntry = cartEntriesState.cartEntries[cartEntryId];
const book = products[cartEntry.bookId];
const branch = branches[cartEntry.branch]
? branches[cartEntry.branch]
: null;
const branch = branches[cartEntry.branch] ? branches[cartEntry.branch] : null;
promotionPoints += book.promoPoints * cartEntry.quantity;
cartData.push({
cartId: cartId,
@@ -372,11 +301,7 @@ export class SharedSelectors {
}
@Selector([AppState, ProcessState, CustomerState])
static currentCustomer(
state: AppStateModel,
process: ProcessStateModel,
customer: CustomerStateModel
): User {
static currentCustomer(state: AppStateModel, process: ProcessStateModel, customer: CustomerStateModel): User {
const currentProcess = process.processes[state.currentProcesssId];
if (!currentProcess) {
return;
@@ -385,10 +310,7 @@ export class SharedSelectors {
}
@Selector([AppState, ProcessState])
static getCurrentCartId(
appState: AppStateModel,
processState: ProcessStateModel
) {
static getCurrentCartId(appState: AppStateModel, processState: ProcessStateModel) {
const processId = appState.currentProcesssId;
if (processId) {
const currentProcess = processState.processes[processId];
@@ -400,28 +322,17 @@ export class SharedSelectors {
}
@Selector([AppState, FilterState])
static getSelectedFilterItems(
state: AppStateModel,
filterState: FilterStateModel
): Filter[] {
static getSelectedFilterItems(state: AppStateModel, filterState: FilterStateModel): Filter[] {
const currentProcessId = state.currentProcesssId;
if (currentProcessId) {
const filterType = filterState.filterType[currentProcessId];
const processesSelectedFilters =
filterType === FilterType.Negative
? filterState.negativeProcessesSelectedFilters
: filterState.processesSelectedFilters;
const currentProcessSelectedFilters = processesSelectedFilters.find(
(f) => f.processId === currentProcessId
);
filterType === FilterType.Negative ? filterState.negativeProcessesSelectedFilters : filterState.processesSelectedFilters;
const currentProcessSelectedFilters = processesSelectedFilters.find((f) => f.processId === currentProcessId);
if (currentProcessSelectedFilters) {
const filter: Filter[] = [];
currentProcessSelectedFilters.selectedFilters.map((f) => {
if (
f.items &&
f.items.filter((t) => t.selected === true) &&
f.items.filter((t) => t.selected === true).length > 0
) {
if (f.items && f.items.filter((t) => t.selected === true) && f.items.filter((t) => t.selected === true).length > 0) {
filter.push(f);
}
});
@@ -434,24 +345,15 @@ export class SharedSelectors {
}
@Selector([AppState, FilterState])
static getProcessFilters(
state: AppStateModel,
filterState: FilterStateModel
): Filter[] {
static getProcessFilters(state: AppStateModel, filterState: FilterStateModel): Filter[] {
const currentProcessId = state.currentProcesssId;
if (currentProcessId) {
const filterType = filterState.filterType[currentProcessId];
const processesSelectedFilters =
filterType === FilterType.Negative
? filterState.negativeProcessesSelectedFilters
: filterState.processesSelectedFilters;
const currentProcessSelectedFilters = processesSelectedFilters.find(
(f) => f.processId === currentProcessId
);
return currentProcessSelectedFilters
? currentProcessSelectedFilters.selectedFilters
: null;
filterType === FilterType.Negative ? filterState.negativeProcessesSelectedFilters : filterState.processesSelectedFilters;
const currentProcessSelectedFilters = processesSelectedFilters.find((f) => f.processId === currentProcessId);
return currentProcessSelectedFilters ? currentProcessSelectedFilters.selectedFilters : null;
}
}
@@ -466,11 +368,7 @@ export class SharedSelectors {
}
@Selector([AppState, ProcessState, CustomerState, BreadcrumbsState])
static getSearchedCustomers(
state: AppStateModel,
process: ProcessStateModel,
customer: CustomerStateModel
): CustomerSearchResult {
static getSearchedCustomers(state: AppStateModel, process: ProcessStateModel, customer: CustomerStateModel): CustomerSearchResult {
const processId = state.currentProcesssId;
const currentProcess = process.processes[processId];
@@ -489,10 +387,7 @@ export class SharedSelectors {
}
@Selector([AppState, ProductState])
static getSearchedProducts(
state: AppStateModel,
products: ProductStateModel
): ProductSearchResult {
static getSearchedProducts(state: AppStateModel, products: ProductStateModel): ProductSearchResult {
const currentProcessId = state.currentProcesssId;
if (currentProcessId) {
@@ -507,23 +402,13 @@ export class SharedSelectors {
}
@Selector([AppState, BreadcrumbsState])
static getBreadcrumbs(
state: AppStateModel,
breadcrumbs: BreadcrumbsStateModel
): Breadcrumb[] {
static getBreadcrumbs(state: AppStateModel, breadcrumbs: BreadcrumbsStateModel): Breadcrumb[] {
const activeModule = state.activeModule;
const currentProcessId =
activeModule === ModuleSwitcher.Customer ? state.currentProcesssId : -1;
const currentProcessId = activeModule === ModuleSwitcher.Customer ? state.currentProcesssId : -1;
if (
currentProcessId &&
breadcrumbs.activeCrumbs &&
breadcrumbs.activeCrumbs[currentProcessId]
) {
if (currentProcessId && breadcrumbs.activeCrumbs && breadcrumbs.activeCrumbs[currentProcessId]) {
const activeCrumbs = breadcrumbs.activeCrumbs[currentProcessId];
const currentBreadcrumbs = breadcrumbs.processesBreadcrumbs[
activeCrumbs
].find((t) => t.processId === currentProcessId);
const currentBreadcrumbs = breadcrumbs.processesBreadcrumbs[activeCrumbs].find((t) => t.processId === currentProcessId);
return currentBreadcrumbs ? currentBreadcrumbs.breadcrumbs : null;
}
@@ -531,19 +416,11 @@ export class SharedSelectors {
}
@Selector([AppState, BreadcrumbsState])
static getPreviousRoute(
state: AppStateModel,
breadcrumbs: BreadcrumbsStateModel
): { crumb: string; path: string } {
static getPreviousRoute(state: AppStateModel, breadcrumbs: BreadcrumbsStateModel): { crumb: string; path: string } {
const activeModule = state.activeModule;
const currentProcessId =
activeModule === ModuleSwitcher.Customer ? state.currentProcesssId : -1;
const currentProcessId = activeModule === ModuleSwitcher.Customer ? state.currentProcesssId : -1;
if (
currentProcessId &&
breadcrumbs.previusMenuPath &&
breadcrumbs.previusMenuPath[currentProcessId]
) {
if (currentProcessId && breadcrumbs.previusMenuPath && breadcrumbs.previusMenuPath[currentProcessId]) {
const previousPath = breadcrumbs.previusMenuPath[currentProcessId];
if (previousPath && previousPath[previousPath.length - 1]) {
return previousPath[previousPath.length - 1];
@@ -554,10 +431,7 @@ export class SharedSelectors {
}
@Selector([AppState, ProcessState])
static getConfirmedCart(
state: AppStateModel,
process: ProcessStateModel
): ProcessCartConfirmed {
static getConfirmedCart(state: AppStateModel, process: ProcessStateModel): ProcessCartConfirmed {
const processId = state.currentProcesssId;
const currentProcess = process.processes[processId];
@@ -580,13 +454,9 @@ export class SharedSelectors {
if (order.orderType === DeliveryType['Branch']) {
targetBranchName = order.targetBranch.name;
// tslint:disable-next-line: max-line-length
targetBranchAddress = `${undefinedToEmptyStringOrValue(
order.targetBranch.address.street
)} ${undefinedToEmptyStringOrValue(
targetBranchAddress = `${undefinedToEmptyStringOrValue(order.targetBranch.address.street)} ${undefinedToEmptyStringOrValue(
order.targetBranch.address.streetNumber
)}, ${undefinedToEmptyStringOrValue(
order.targetBranch.address.zipCode
)} ${undefinedToEmptyStringOrValue(
)}, ${undefinedToEmptyStringOrValue(order.targetBranch.address.zipCode)} ${undefinedToEmptyStringOrValue(
order.targetBranch.address.city
)}`;
}
@@ -596,8 +466,7 @@ export class SharedSelectors {
if (item.promotion) {
promotionPoints += item.quantity * item.promotion.points;
}
const isDownload =
item.product.format === 'EB' || item.product.format === 'DL';
const isDownload = item.product.format === 'EB' || item.product.format === 'DL';
const orderItem: OrderItem = {
id: +item.product.catalogProductNumber,
orderId: order.id,
@@ -608,8 +477,7 @@ export class SharedSelectors {
currency: item.price.value.currency,
price: item.price.value.value,
imgUrl: item.product.ean,
isTakeNow:
item.subsetItems[0].supplierLabel === 'F' ? true : false,
isTakeNow: item.subsetItems[0].supplierLabel === 'F' ? true : false,
isDownload: isDownload,
orderDate: item.orderDate,
targetBranchName: targetBranchName,
@@ -617,26 +485,19 @@ export class SharedSelectors {
};
if (order.orderType === DeliveryType['ShippingAddress']) {
orderItem.deliveryDate =
item.subsetItems[0].estimatedShippingDate;
orderItem.deliveryDate = item.subsetItems[0].estimatedShippingDate;
}
if (order.orderType === DeliveryType['Branch']) {
orderItem.pickUpDate =
item.subsetItems[0].estimatedShippingDate;
orderItem.pickUpDate = item.subsetItems[0].estimatedShippingDate;
}
cartData.push(orderItem);
});
});
const takeNowItems = cartData.filter(
(item: OrderItem) => item.isTakeNow
);
const pickUpItems = cartData.filter(
(item: OrderItem) =>
!item.isTakeNow && item.orderType === DeliveryType['Branch']
);
const takeNowItems = cartData.filter((item: OrderItem) => item.isTakeNow);
const pickUpItems = cartData.filter((item: OrderItem) => !item.isTakeNow && item.orderType === DeliveryType['Branch']);
// Prepare object for components
return {
@@ -646,16 +507,8 @@ export class SharedSelectors {
totalQuantity: totalQuantity,
cartId: currentProcess.cartId,
orderIds: orderIds,
isTakeNowOnly:
takeNowItems &&
cartData &&
takeNowItems.length === cartData.length
? true
: false,
isPickUpOnly:
pickUpItems && cartData && pickUpItems.length === cartData.length
? true
: false,
isTakeNowOnly: takeNowItems && cartData && takeNowItems.length === cartData.length ? true : false,
isPickUpOnly: pickUpItems && cartData && pickUpItems.length === cartData.length ? true : false,
promotionPoints: promotionPoints,
};
}
@@ -679,29 +532,20 @@ export class SharedSelectors {
}
@Selector([AppState, FilterState])
static getFilters(
appState: AppStateModel,
state: FilterStateModel
): Filter[] {
static getFilters(appState: AppStateModel, state: FilterStateModel): Filter[] {
const currenProcessId = appState.currentProcesssId;
const filterType = state.filterType[currenProcessId];
const processesSelectedFilters =
filterType === FilterType.Negative
? state.negativeProcessesSelectedFilters
: state.processesSelectedFilters;
filterType === FilterType.Negative ? state.negativeProcessesSelectedFilters : state.processesSelectedFilters;
const processFilters = processesSelectedFilters[currenProcessId];
return state.filters.map((filter) => {
return <Filter>{
...filter,
items: filter.items.map((item) => {
if (processFilters) {
const selectedFilter = processFilters.selectedFilters.find(
(f) => f.id === filter.id
);
const selectedFilter = processFilters.selectedFilters.find((f) => f.id === filter.id);
if (selectedFilter) {
const selectedItem = selectedFilter.items.find(
(i) => i.id === item.id
);
const selectedItem = selectedFilter.items.find((i) => i.id === item.id);
if (selectedItem) {
return <FilterItem>{ ...item, selected: selectedItem.selected };
} else {
@@ -759,10 +603,7 @@ export class SharedSelectors {
}
@Selector([AppState, CollectingShelfState])
static getIterableOrderForCurrentProcess(
appState: AppStateModel,
orderState: CollectingShelfStateModel
): CollectingShelfOrder[] {
static getIterableOrderForCurrentProcess(appState: AppStateModel, orderState: CollectingShelfStateModel): CollectingShelfOrder[] {
const currenProcessId = appState.currentProcesssId;
if (!currenProcessId) {
return [];
@@ -780,10 +621,7 @@ export class SharedSelectors {
}
@Selector([AppState, ProcessState])
static getProcessSelectedItem(
appState: AppStateModel,
process: ProcessStateModel
): ItemDTO {
static getProcessSelectedItem(appState: AppStateModel, process: ProcessStateModel): ItemDTO {
const currenProcessId = appState.currentProcesssId;
if (!currenProcessId) {
return;
@@ -792,11 +630,7 @@ export class SharedSelectors {
}
@Selector([AppState, ProcessState, CustomerState])
static getCurrentProcessDetailsCustomer(
appState: AppStateModel,
processes: ProcessStateModel,
customers: CustomerStateModel
) {
static getCurrentProcessDetailsCustomer(appState: AppStateModel, processes: ProcessStateModel, customers: CustomerStateModel) {
const currentProcessId = appState.currentProcesssId;
if (!currentProcessId) {
return;

View File

@@ -10,10 +10,7 @@ import {
import { LoadBranches, LoadUserBranch } from '../actions/branch.actions';
import { BranchSelectors } from '../selectors/branch.selector';
import { isNullOrUndefined } from 'util';
import {
RemoveProcessNewState,
ReloadProcessData,
} from '../actions/process.actions';
import { RemoveProcessNewState, ReloadProcessData } from '../actions/process.actions';
import { UserStateService } from '../../services/user-state.service';
import { UserStateSyncData } from '../../models/user-state-sync.model';
import { ReloadCustomersData } from '../actions/customer.actions';
@@ -104,13 +101,9 @@ export class AppState {
}
@Action(AppSetCurrentProcess)
appSetCurrentProcess(
ctx: StateContext<AppStateModel>,
{ payload }: AppSetCurrentProcess
) {
appSetCurrentProcess(ctx: StateContext<AppStateModel>, { payload }: AppSetCurrentProcess) {
const state = ctx.getState();
const processExists =
state.processIds.findIndex((t) => t === payload) !== -1;
const processExists = state.processIds.findIndex((t) => t === payload) !== -1;
if (processExists) {
ctx.patchState({
currentProcesssId: payload,
@@ -122,23 +115,18 @@ export class AppState {
@Action(AppAddProcess)
appAddProcess(ctx: StateContext<AppStateModel>, { payload }: AppAddProcess) {
const state = ctx.getState();
const processExists =
state.processIds.findIndex((t) => t === payload) !== -1;
const processExists = state.processIds.findIndex((t) => t === payload) !== -1;
if (!processExists) {
const processIds = [...state.processIds, payload];
const currentProcesssId = payload;
ctx.patchState({ currentProcesssId, processIds });
const branchesLoaded = this.store.selectSnapshot(
BranchSelectors.getBranches
);
const branchesLoaded = this.store.selectSnapshot(BranchSelectors.getBranches);
if (!branchesLoaded || Object.keys(branchesLoaded).length === 0) {
this.store.dispatch(new LoadBranches());
}
const userBranch = this.store.selectSnapshot(
BranchSelectors.getUserBranch
);
const userBranch = this.store.selectSnapshot(BranchSelectors.getUserBranch);
if (isNullOrUndefined(userBranch)) {
this.store.dispatch(new LoadUserBranch());
}
@@ -148,10 +136,7 @@ export class AppState {
}
@Action(AppDeleteProcess)
appDeleteProcess(
ctx: StateContext<AppStateModel>,
{ payload }: AppDeleteProcess
) {
appDeleteProcess(ctx: StateContext<AppStateModel>, { payload }: AppDeleteProcess) {
const state = ctx.getState();
const currentIds = state.processIds;
if (currentIds) {
@@ -162,10 +147,7 @@ export class AppState {
}
@Action(AppSwitchModule)
appSwitchModule(
ctx: StateContext<AppStateModel>,
{ payload }: AppSwitchModule
) {
appSwitchModule(ctx: StateContext<AppStateModel>, { payload }: AppSwitchModule) {
const state = ctx.getState();
ctx.patchState({ activeModule: payload });
this.syncApiState(state.processIds, payload);
@@ -175,10 +157,7 @@ export class AppState {
* Save store data on backend
*/
@Action(AppUserDataSync)
appUserDataSynced(
ctx: StateContext<AppStateModel>,
{ data, sync }: AppUserDataSync
) {
appUserDataSynced(ctx: StateContext<AppStateModel>, { data, sync }: AppUserDataSync) {
const state = ctx.getState();
let currentUserData: UserStateSyncData = {};
@@ -205,10 +184,7 @@ export class AppState {
* Initial store loading from API, triggered once on page load
*/
@Action(ReloadSavedState)
reloadSavedState(
ctx: StateContext<AppStateModel>,
{ data, sync }: ReloadSavedState
) {
reloadSavedState(ctx: StateContext<AppStateModel>, { data, sync }: ReloadSavedState) {
const state = ctx.getState();
let currentUserData: UserStateSyncData = {};
@@ -232,10 +208,7 @@ export class AppState {
if (sync && syncedData.version === SYNC_DATA_VERSION) {
this.reloadDataFromAPI(syncedData);
if (
syncedData.currentProcesssId ||
syncedData.activeModule === ModuleSwitcher.Branch
) {
if (syncedData.currentProcesssId || syncedData.activeModule === ModuleSwitcher.Branch) {
ctx.patchState({
...state,
synced: true,
@@ -262,19 +235,11 @@ export class AppState {
return;
}
if (data.customers) {
this.store.dispatch(
new ReloadCustomersData(
data.customers,
data.lastCreatedCustomerId,
data.cachedCustomerSearch
)
);
this.store.dispatch(new ReloadCustomersData(data.customers, data.lastCreatedCustomerId, data.cachedCustomerSearch));
}
if (data.products) {
this.store.dispatch(
new ReloadProductsData(data.products, data.cachedProductResults)
);
this.store.dispatch(new ReloadProductsData(data.products, data.cachedProductResults));
}
if (data.carts) {
@@ -294,9 +259,7 @@ export class AppState {
}
if (data.processes) {
this.store.dispatch(
new ReloadProcessData(data.processes, data.recentArticles)
);
this.store.dispatch(new ReloadProcessData(data.processes, data.recentArticles));
}
if (data.formsState) {
@@ -304,20 +267,11 @@ export class AppState {
}
if (data.activeModule === ModuleSwitcher.Customer) {
if (
data.processes &&
data.currentProcesssId &&
data.processes[data.currentProcesssId]
) {
if (data.processes && data.currentProcesssId && data.processes[data.currentProcesssId]) {
const currentProcesssId = data.currentProcesssId;
const currentRoute = data.processes[currentProcesssId].currentRoute;
if (currentRoute && currentRoute.length > 0) {
this.routingAvailableAction(
data,
currentProcesssId,
currentRoute,
data.activeModule
);
this.routingAvailableAction(data, currentProcesssId, currentRoute, data.activeModule);
} else {
this.router.navigate(['/dashboard']);
}
@@ -329,12 +283,7 @@ export class AppState {
const currentProcesssId = -1;
const currentRoute = data.branchProcess.currentRoute;
if (currentRoute && currentRoute.length > 0) {
this.routingAvailableAction(
data,
currentProcesssId,
currentRoute,
data.activeModule
);
this.routingAvailableAction(data, currentProcesssId, currentRoute, data.activeModule);
} else {
this.router.navigate([FILIALE_LANDING_PAGE]);
}
@@ -348,24 +297,11 @@ export class AppState {
}
if (data.activeModule === ModuleSwitcher.Branch) {
this.moduleSwitcherService.switch(
ModuleSwitcher.Branch,
data.branchProcess
);
this.moduleSwitcherService.switch(ModuleSwitcher.Branch, data.branchProcess);
}
if (
data.processesBreadcrumbs &&
data.activeCrumbs &&
(data.currentProcesssId || data.activeModule === ModuleSwitcher.Branch)
) {
this.store.dispatch(
new ReloadBreadcrumbsData(
data.processesBreadcrumbs,
data.activeCrumbs,
data.previusMenuPath
)
);
if (data.processesBreadcrumbs && data.activeCrumbs && (data.currentProcesssId || data.activeModule === ModuleSwitcher.Branch)) {
this.store.dispatch(new ReloadBreadcrumbsData(data.processesBreadcrumbs, data.activeCrumbs, data.previusMenuPath));
}
if (data.filters && data.processesSelectedFilters && data.dropdownFilters) {
@@ -391,28 +327,16 @@ export class AppState {
);
}
private routingAvailableAction(
data: UserStateSyncData,
currentProcesssId: number,
currentRoute: string,
module: ModuleSwitcher
) {
const hasActiveCrumbsAvailableForProcess =
data.activeCrumbs && data.activeCrumbs[currentProcesssId];
private routingAvailableAction(data: UserStateSyncData, currentProcesssId: number, currentRoute: string, module: ModuleSwitcher) {
const hasActiveCrumbsAvailableForProcess = data.activeCrumbs && data.activeCrumbs[currentProcesssId];
const activeCrumbs = data.activeCrumbs[currentProcesssId];
const hasProcessBreadcrumbsAvailableForProcess =
data.processesBreadcrumbs && data.processesBreadcrumbs[activeCrumbs];
const hasProcessBreadcrumbsAvailableForProcess = data.processesBreadcrumbs && data.processesBreadcrumbs[activeCrumbs];
const breadcrumb = hasProcessBreadcrumbsAvailableForProcess
? data.processesBreadcrumbs[activeCrumbs].find(
(t) => t.processId === currentProcesssId
)
? data.processesBreadcrumbs[activeCrumbs].find((t) => t.processId === currentProcesssId)
: null;
const breadcrumbPath =
breadcrumb && breadcrumb.breadcrumbs
? breadcrumb.breadcrumbs.find((t) => t && t.path === currentRoute)
: null;
const breadcrumbPath = breadcrumb && breadcrumb.breadcrumbs ? breadcrumb.breadcrumbs.find((t) => t && t.path === currentRoute) : null;
if (
hasActiveCrumbsAvailableForProcess &&

View File

@@ -13,8 +13,8 @@ export class BranchProcessStateModel {
@State<BranchProcessStateModel>({
name: 'branchprocess',
defaults: {
branchProcess: { id: -1, currentRoute: undefined }
}
branchProcess: { id: -1, currentRoute: undefined },
},
})
export class BranchProcessState {
constructor(private store: Store) {}
@@ -45,7 +45,7 @@ export class BranchProcessState {
private syncApiState(branchProcess: BranchProcess) {
const userSyncData: UserStateSyncData = {
branchProcess
branchProcess,
};
const userData = JSON.stringify(userSyncData);
this.store.dispatch(new AppUserDataSync(userData));

View File

@@ -3,10 +3,7 @@ import * as actions from '../actions/cart-entry.actions';
import { CartEntry } from '../../models/cart-entry.model';
import { SetCartData } from '../actions/cart.actions';
import { BranchSelectors } from '../selectors/branch.selector';
import {
DeliveryOption,
DeliveryType,
} from '../../models/delivery-option.model';
import { DeliveryOption, DeliveryType } from '../../models/delivery-option.model';
import {
ShippingTarget,
BranchDTO,
@@ -46,29 +43,16 @@ export class CartEntryStateModel {
},
})
export class CartEntryState {
constructor(
private store: Store,
private checkoutService: CheckoutService,
private customerMapping: CustomerMapping
) {}
constructor(private store: Store, private checkoutService: CheckoutService, private customerMapping: CustomerMapping) {}
@Action(actions.SetCartEntry)
setCartEntryData(
ctx: StateContext<CartEntryStateModel>,
{
quantity,
deliveryType,
bookId,
availability,
branch,
promoPoints,
}: actions.SetCartEntry
{ quantity, deliveryType, bookId, availability, branch, promoPoints }: actions.SetCartEntry
) {
const products = this.store.selectSnapshot(ProductSelectors.getProducts);
const branches = this.store.selectSnapshot(BranchSelectors.getBranches);
const currentProcess = this.store.selectSnapshot(
ProcessSelectors.getCurrentProcess
);
const currentProcess = this.store.selectSnapshot(ProcessSelectors.getCurrentProcess);
const state = ctx.getState();
if (!currentProcess || !currentProcess.cartId) {
@@ -76,22 +60,11 @@ export class CartEntryState {
}
const cartId = currentProcess.cartId;
const existingItemId = this.itemExistInCart(
state.cartEntries,
bookId,
deliveryType,
branch,
cartId
);
const existingItemId = this.itemExistInCart(state.cartEntries, bookId, deliveryType, branch, cartId);
if (existingItemId) {
this.store.dispatch(
new actions.UpdateCartEntryQuantity(
state.cartEntries[existingItemId].quantity + quantity,
existingItemId,
availability,
''
)
new actions.UpdateCartEntryQuantity(state.cartEntries[existingItemId].quantity + quantity, existingItemId, availability, '')
);
} else {
return this.addItemToCart$(
@@ -110,43 +83,21 @@ export class CartEntryState {
@Action(actions.UpdateCartEntryType)
updateCartEntryData(
ctx: StateContext<CartEntryStateModel>,
{
deliveryType,
bookId,
availability,
branch,
oldDeliveryType,
oldBranch,
}: actions.UpdateCartEntryType
{ deliveryType, bookId, availability, branch, oldDeliveryType, oldBranch }: actions.UpdateCartEntryType
) {
const branches = this.store.selectSnapshot(BranchSelectors.getBranches);
const currentProcess = this.store.selectSnapshot(
ProcessSelectors.getCurrentProcess
);
const currentProcess = this.store.selectSnapshot(ProcessSelectors.getCurrentProcess);
if (!currentProcess) {
return;
}
const state = ctx.getState();
const existingItemId = this.itemExistInCart(
state.cartEntries,
bookId,
oldDeliveryType,
oldBranch,
currentProcess.cartId
);
const existingItemId = this.itemExistInCart(state.cartEntries, bookId, oldDeliveryType, oldBranch, currentProcess.cartId);
const newBranch = branches[branch];
const itemToUpdate = { ...state.cartEntries[existingItemId] };
const cartEntries = { ...state.cartEntries };
const destination = this.createDestinationObject(
deliveryType,
newBranch,
availability as any
);
const ava: UpdateDestinationAvailability = this.availibilityObjectForUpdate(
availability as any,
deliveryType
);
const destination = this.createDestinationObject(deliveryType, newBranch, availability as any);
const ava: UpdateDestinationAvailability = this.availibilityObjectForUpdate(availability as any, deliveryType);
itemToUpdate.quantity = itemToUpdate.quantity;
itemToUpdate.deliveryType = deliveryType;
@@ -178,33 +129,20 @@ export class CartEntryState {
: undefined;
cartEntries[existingItemId] = itemToUpdate;
return this.checkoutService
.updateItemInCart(
currentProcess.cartId,
existingItemId,
destination,
itemToUpdate.quantity,
ava
)
.pipe(
tap(() => {
ctx.patchState({
cartEntries,
});
this.syncApiState(cartEntries);
})
);
return this.checkoutService.updateItemInCart(currentProcess.cartId, existingItemId, destination, itemToUpdate.quantity, ava).pipe(
tap(() => {
ctx.patchState({
cartEntries,
});
this.syncApiState(cartEntries);
})
);
}
@Action(actions.SetShippingForDownloadCart)
setShippingForDownloadCart(
ctx: StateContext<CartEntryStateModel>,
{ address, cartEntriesIds }: actions.SetShippingForDownloadCart
) {
setShippingForDownloadCart(ctx: StateContext<CartEntryStateModel>, { address, cartEntriesIds }: actions.SetShippingForDownloadCart) {
const state = ctx.getState();
const currentProcess = this.store.selectSnapshot(
ProcessSelectors.getCurrentProcess
);
const currentProcess = this.store.selectSnapshot(ProcessSelectors.getCurrentProcess);
if (currentProcess) {
const cartEntries = { ...state.cartEntries };
@@ -212,13 +150,9 @@ export class CartEntryState {
return from(cartEntriesIds).pipe(
concatMap((cartEntryId) =>
this.checkoutService
.updateDestinationForItemInCart(
currentProcess.cartId,
cartEntryId,
<EntityDTOContainerOfDestinationDTO>{
data: <DestinationDTO>{ shippingAddress: address },
}
)
.updateDestinationForItemInCart(currentProcess.cartId, cartEntryId, <EntityDTOContainerOfDestinationDTO>{
data: <DestinationDTO>{ shippingAddress: address },
})
.pipe(
tap(() => {
const cartEntry = {
@@ -243,17 +177,10 @@ export class CartEntryState {
@Action(actions.UpdateCartEntryQuantity)
updateCartEntryQuantity(
ctx: StateContext<CartEntryStateModel>,
{
quantity,
cartEntryId,
availabilityMsg,
availability,
}: actions.UpdateCartEntryQuantity
{ quantity, cartEntryId, availabilityMsg, availability }: actions.UpdateCartEntryQuantity
) {
const state = ctx.getState();
const currentProcess = this.store.selectSnapshot(
ProcessSelectors.getCurrentProcess
);
const currentProcess = this.store.selectSnapshot(ProcessSelectors.getCurrentProcess);
const cartEntries = { ...state.cartEntries };
const updateEntry = { ...cartEntries[cartEntryId] };
@@ -277,18 +204,10 @@ export class CartEntryState {
products[updateEntry.bookId],
quantity,
branches[updateEntry.branch],
(updateEntry.availability
? updateEntry.availability
: products[updateEntry.bookId].catalogAvailability) as any, // TODO: Typisierung
(updateEntry.availability ? updateEntry.availability : products[updateEntry.bookId].catalogAvailability) as any, // TODO: Typisierung
products[updateEntry.bookId].promoPoints
).pipe(
switchMap((updatedItem) =>
this.checkoutService.updateQuantityForItemInCart(
currentProcess.cartId,
cartEntryId,
updatedItem
)
),
switchMap((updatedItem) => this.checkoutService.updateQuantityForItemInCart(currentProcess.cartId, cartEntryId, updatedItem)),
tap(() => {
this.syncApiState(cartEntries);
})
@@ -296,14 +215,9 @@ export class CartEntryState {
}
@Action(actions.DeleteCartEntry)
deleteCartItem(
ctx: StateContext<CartEntryStateModel>,
{ cartEntryId, hardDelete }: actions.DeleteCartEntry
) {
deleteCartItem(ctx: StateContext<CartEntryStateModel>, { cartEntryId, hardDelete }: actions.DeleteCartEntry) {
const state = ctx.getState();
const currentProcess = this.store.selectSnapshot(
ProcessSelectors.getCurrentProcess
);
const currentProcess = this.store.selectSnapshot(ProcessSelectors.getCurrentProcess);
const cartEntries = { ...state.cartEntries };
const cartEntry = cartEntries[cartEntryId];
@@ -315,18 +229,10 @@ export class CartEntryState {
products[cartEntry.bookId],
0,
branches[cartEntry.branch],
(cartEntry.availability
? cartEntry.availability
: products[cartEntry.bookId].catalogAvailability) as any, // TODO: Typisierung
(cartEntry.availability ? cartEntry.availability : products[cartEntry.bookId].catalogAvailability) as any, // TODO: Typisierung
products[cartEntry.bookId].promoPoints
).pipe(
switchMap((updatedItem) =>
this.checkoutService.updateQuantityForItemInCart(
currentProcess.cartId,
cartEntryId,
updatedItem
)
),
switchMap((updatedItem) => this.checkoutService.updateQuantityForItemInCart(currentProcess.cartId, cartEntryId, updatedItem)),
tap(() => {
delete cartEntries[cartEntryId];
@@ -340,17 +246,11 @@ export class CartEntryState {
}
@Action(actions.ReloadCartEntryData)
reloadCartEntries(
ctx: StateContext<CartEntryStateModel>,
{ cartEntries }: actions.ReloadCartEntryData
) {
reloadCartEntries(ctx: StateContext<CartEntryStateModel>, { cartEntries }: actions.ReloadCartEntryData) {
ctx.setState({ cartEntries: { ...cartEntries } });
}
private availibilityObjectForUpdate(
ava: AvailabilityDTO,
deliveryType: string
): UpdateDestinationAvailability {
private availibilityObjectForUpdate(ava: AvailabilityDTO, deliveryType: string): UpdateDestinationAvailability {
let data: UpdateDestinationAvailability = { availabilityType: ava.status };
if (deliveryType === DeliveryOption.DELIVERY) {
@@ -403,15 +303,10 @@ export class CartEntryState {
branch: number,
cartId: number
): null | number {
const existingCartEntriesIds = this.store.selectSnapshot(
CartState.getCartEntries
)(cartId);
const existingCartEntriesIds = this.store.selectSnapshot(CartState.getCartEntries)(cartId);
const existingEntries = existingCartEntriesIds.map((id) => cartEntries[id]);
const updateItem = existingEntries.find(
(cartitem: CartEntry) =>
cartitem.bookId === bookId &&
cartitem.deliveryType === deliveryType &&
cartitem.branch === branch
(cartitem: CartEntry) => cartitem.bookId === bookId && cartitem.deliveryType === deliveryType && cartitem.branch === branch
);
if (updateItem) {
@@ -419,11 +314,7 @@ export class CartEntryState {
for (const key of existingCartEntriesIds) {
const currentItem = cartEntries[key];
if (
currentItem.bookId === bookId &&
currentItem.deliveryType === deliveryType &&
currentItem.branch === branch
) {
if (currentItem.bookId === bookId && currentItem.deliveryType === deliveryType && currentItem.branch === branch) {
itemId = key;
break;
}
@@ -450,12 +341,7 @@ export class CartEntryState {
if (deliveryType === DeliveryOption.TAKE_NOW) {
getBranchSupplierId$ = this.checkoutService
.getSuppliers()
.pipe(
map(
(suppliers) =>
suppliers.find((supplier) => supplier.supplierNumber === 'F').id
)
);
.pipe(map((suppliers) => suppliers.find((supplier) => supplier.supplierNumber === 'F').id));
}
const addItemToCart$ = (item: AddToShoppingCartDTO) =>
@@ -463,10 +349,8 @@ export class CartEntryState {
tap((shoppingCart: ShoppingCartDTO) => {
const newItemIndex = Object.keys(shoppingCart.items).length - 1;
const newItemId = shoppingCart.items[newItemIndex].id;
const deliveryDate = shoppingCart.items[newItemIndex].data
.availability.estimatedShippingDate
? shoppingCart.items[newItemIndex].data.availability
.estimatedShippingDate
const deliveryDate = shoppingCart.items[newItemIndex].data.availability.estimatedShippingDate
? shoppingCart.items[newItemIndex].data.availability.estimatedShippingDate
: null;
const pickUpDate = availability.at ? availability.at : null;
@@ -522,13 +406,9 @@ export class CartEntryState {
);
if (deliveryType === DeliveryOption.DOWNLOAD) {
const customer = this.store.selectSnapshot(
CustomerSelectors.getCurrentProcessActiveUser
);
const customer = this.store.selectSnapshot(CustomerSelectors.getCurrentProcessActiveUser);
return this.checkoutService.getSuppliers().pipe(
map((suppliers) =>
suppliers.find((supplier) => supplier.supplierNumber === 'DIG')
),
map((suppliers) => suppliers.find((supplier) => supplier.supplierNumber === 'DIG')),
map((supplier) =>
this.createObjectForDonwload(
deliveryType,
@@ -545,17 +425,7 @@ export class CartEntryState {
);
} else {
return getBranchSupplierId$.pipe(
map((supplierId) =>
this.createObjectForAPI(
deliveryType,
book,
quantity,
availability,
supplierId,
branch,
promoPoints
)
),
map((supplierId) => this.createObjectForAPI(deliveryType, book, quantity, availability, supplierId, branch, promoPoints)),
flatMap((item) => addItemToCart$(item))
);
}
@@ -570,11 +440,7 @@ export class CartEntryState {
branch: BranchDTO,
promoPoints: number
): AddToShoppingCartDTO {
const destination: EntityDTOContainerOfDestinationDTO = this.createDestinationObject(
deliveryType,
branch,
availability
);
const destination: EntityDTOContainerOfDestinationDTO = this.createDestinationObject(deliveryType, branch, availability);
const item: AddToShoppingCartDTO = {
product: {
@@ -590,9 +456,7 @@ export class CartEntryState {
ssc: availability.ssc ? availability.ssc : null,
sscText: availability.sscText ? availability.sscText : null,
estimatedShippingDate: availability.at ? availability.at : null,
supplierProductNumber: availability.supplierProductNumber
? availability.supplierProductNumber
: null,
supplierProductNumber: availability.supplierProductNumber ? availability.supplierProductNumber : null,
isPrebooked: availability.isPrebooked,
},
promotion: { points: promoPoints },
@@ -611,12 +475,7 @@ export class CartEntryState {
promoPoints: number,
customer?: User
): AddToShoppingCartDTO {
const destination: EntityDTOContainerOfDestinationDTO = this.createDestinationObject(
deliveryType,
branch,
availability,
customer
);
const destination: EntityDTOContainerOfDestinationDTO = this.createDestinationObject(deliveryType, branch, availability, customer);
const item: AddToShoppingCartDTO = {
product: {
@@ -632,9 +491,7 @@ export class CartEntryState {
ssc: availability.ssc ? availability.ssc : null,
sscText: availability.sscText ? availability.sscText : null,
estimatedShippingDate: availability.at ? availability.at : null,
supplierProductNumber: availability.supplierProductNumber
? availability.supplierProductNumber
: null,
supplierProductNumber: availability.supplierProductNumber ? availability.supplierProductNumber : null,
isPrebooked: availability.isPrebooked,
},
promotion: { points: promoPoints },
@@ -668,14 +525,8 @@ export class CartEntryState {
},
};
} else if (targetType === DeliveryType['Download']) {
const address = customer
? customer.delivery_addres
? customer.delivery_addres
: customer.invoice_address
: null;
const addressDto: AddressDTO = address
? this.customerMapping.fromAddressToAddressDTO(address)
: null;
const address = customer ? (customer.delivery_addres ? customer.delivery_addres : customer.invoice_address) : null;
const addressDto: AddressDTO = address ? this.customerMapping.fromAddressToAddressDTO(address) : null;
destination = {
data: {
target: targetType,
@@ -713,13 +564,9 @@ export class CartEntryState {
let item$: Observable<AddToShoppingCartDTO>;
if (deliveryType === DeliveryOption.DOWNLOAD) {
item$ = this.checkoutService.getSuppliers().pipe(
map((suppliers) =>
suppliers.find((supplier) => supplier.supplierNumber === 'DIG')
),
map((suppliers) => suppliers.find((supplier) => supplier.supplierNumber === 'DIG')),
flatMap((supplier) => {
const customer = this.store.selectSnapshot(
CustomerSelectors.getCurrentProcessActiveUser
);
const customer = this.store.selectSnapshot(CustomerSelectors.getCurrentProcessActiveUser);
return of(
this.createObjectForDonwload(
deliveryType,
@@ -736,36 +583,13 @@ export class CartEntryState {
);
} else if (deliveryType === DeliveryOption.TAKE_NOW) {
item$ = this.checkoutService.getSuppliers().pipe(
map(
(suppliers) =>
suppliers.find((supplier) => supplier.supplierNumber === 'F').id
),
map((suppliers) => suppliers.find((supplier) => supplier.supplierNumber === 'F').id),
flatMap((supplierId) => {
return of(
this.createObjectForAPI(
deliveryType,
book,
quantity,
availability,
supplierId,
branch,
promoPoints
)
);
return of(this.createObjectForAPI(deliveryType, book, quantity, availability, supplierId, branch, promoPoints));
})
);
} else {
return of(
this.createObjectForAPI(
deliveryType,
book,
quantity,
availability,
availability.supplierId,
branch,
promoPoints
)
);
return of(this.createObjectForAPI(deliveryType, book, quantity, availability, availability.supplierId, branch, promoPoints));
}
return item$.pipe(
map((it) => {

View File

@@ -1,22 +1,11 @@
import { State, Action, StateContext, Store, Selector } from '@ngxs/store';
import * as actions from '../actions/cart.actions';
import {
AddCartToProcess,
SetFinishedOrderData,
ChangeCurrentRoute,
} from '../actions/process.actions';
import { AddCartToProcess, SetFinishedOrderData, ChangeCurrentRoute } from '../actions/process.actions';
import { DeleteCartEntry } from '../actions/cart-entry.actions';
import { ProcessSelectors } from '../selectors/process.selectors';
import { CheckoutService } from '../../services/checkout.service';
import { tap, catchError } from 'rxjs/operators';
import {
ShoppingCartDTO,
PaymentDTO,
CheckoutDTO,
BuyerDTO,
PayerDTO,
DestinationDTO,
} from '@swagger/checkout';
import { ShoppingCartDTO, PaymentDTO, CheckoutDTO, BuyerDTO, PayerDTO, DestinationDTO } from '@swagger/checkout';
import { DisplayOrderDTO, EnvironmentChannel } from '@swagger/oms';
import { User } from '../../models/user.model';
import { CustomerMapping } from '../../mappings/customer.mapping';
@@ -58,10 +47,7 @@ export class CartState {
}
@Action(actions.SetCartToProcess)
setCartToProcess(
ctx: StateContext<CartStateModel>,
{}: actions.SetCartToProcess
) {
setCartToProcess(ctx: StateContext<CartStateModel>, {}: actions.SetCartToProcess) {
return this.checkoutService.createCart().pipe(
tap((cart: ShoppingCartDTO) => {
const state = ctx.getState();
@@ -75,41 +61,28 @@ export class CartState {
}
@Action(actions.SetCartData)
addItemToCart(
ctx: StateContext<CartStateModel>,
{ cartEntryId }: actions.SetCartData
) {
addItemToCart(ctx: StateContext<CartStateModel>, { cartEntryId }: actions.SetCartData) {
const state = ctx.getState();
const currentProcess = this.store.selectSnapshot(
ProcessSelectors.getCurrentProcess
);
const currentProcess = this.store.selectSnapshot(ProcessSelectors.getCurrentProcess);
if (!currentProcess) {
return;
}
const carts = { ...state.carts };
carts[currentProcess.cartId] = [
...carts[currentProcess.cartId],
cartEntryId,
];
carts[currentProcess.cartId] = [...carts[currentProcess.cartId], cartEntryId];
ctx.patchState({ carts });
this.syncApiState(carts);
}
@Action(actions.DeleteProductFromCart)
deleteProductFromCart(
ctx: StateContext<CartStateModel>,
{ cartId, cartEntryId }: actions.DeleteProductFromCart
) {
deleteProductFromCart(ctx: StateContext<CartStateModel>, { cartId, cartEntryId }: actions.DeleteProductFromCart) {
const state = ctx.getState();
const allCarts = { ...state.carts };
const cartEntries = allCarts[cartId];
// Remove product from
const productToDelete = cartEntries.find(
(entryId: number) => entryId === cartEntryId
);
const productToDelete = cartEntries.find((entryId: number) => entryId === cartEntryId);
if (productToDelete) {
this.store.dispatch(new DeleteCartEntry(cartEntryId, true));
}
@@ -125,10 +98,7 @@ export class CartState {
}
@Action(actions.DeleteCart)
deleteCart(
ctx: StateContext<CartStateModel>,
{ cartId }: actions.DeleteCart
) {
deleteCart(ctx: StateContext<CartStateModel>, { cartId }: actions.DeleteCart) {
const state = ctx.getState();
const carts = { ...state.carts };
const cartEntries = carts[cartId];
@@ -151,26 +121,16 @@ export class CartState {
}
@Action(actions.CreateOrder)
createOrder(
ctx: StateContext<CartStateModel>,
{ checkoutId }: actions.CreateOrder
) {
createOrder(ctx: StateContext<CartStateModel>, { checkoutId }: actions.CreateOrder) {
return this.checkoutService.createOrder(checkoutId).pipe(
tap(
(order: {
failedItemIds: { id: number; type: number }[];
displayOrder: DisplayOrderDTO[];
}) => {
this.store.dispatch(new SetFinishedOrderData(order));
}
),
tap((order: { failedItemIds: { id: number; type: number }[]; displayOrder: DisplayOrderDTO[] }) => {
this.store.dispatch(new SetFinishedOrderData(order));
}),
catchError((error) => {
const status = error.status;
const message = error && error.error ? error.error.message : undefined;
const invalidProperties =
error && error.error && error.error.invalidProperties
? JSON.stringify(error.error.invalidProperties)
: undefined;
error && error.error && error.error.invalidProperties ? JSON.stringify(error.error.invalidProperties) : undefined;
this.errorService.addErrors(status, message, invalidProperties);
this.openCart();
return of(undefined);
@@ -190,104 +150,63 @@ export class CartState {
}
@Action(actions.SetPaymentTypeToCheckout)
getPaymentToCheckout(
ctx: StateContext<CartStateModel>,
{ checkoutId, customer, isDelivery }: actions.SetPaymentTypeToCheckout
) {
getPaymentToCheckout(ctx: StateContext<CartStateModel>, { checkoutId, customer, isDelivery }: actions.SetPaymentTypeToCheckout) {
return this.checkoutService.getPayments(checkoutId).pipe(
tap((payment: PaymentDTO) => {
const type = payment.availablePaymentTypes[0].key;
this.store.dispatch(
new actions.SetPaymentToCheckout(
checkoutId,
type,
customer,
isDelivery
)
);
this.store.dispatch(new actions.SetPaymentToCheckout(checkoutId, type, customer, isDelivery));
})
);
}
@Action(actions.SetPaymentToCheckout)
setPaymentToCheckout(
ctx: StateContext<CartStateModel>,
{ checkoutId, type, customer, isDelivery }: actions.SetPaymentToCheckout
) {
setPaymentToCheckout(ctx: StateContext<CartStateModel>, { checkoutId, type, customer, isDelivery }: actions.SetPaymentToCheckout) {
return this.checkoutService.setPaymentType(checkoutId, type).pipe(
tap((checkout: CheckoutDTO) => {
this.store.dispatch(
new actions.SetBuyerToCheckout(checkout.id, customer, isDelivery)
);
this.store.dispatch(new actions.SetBuyerToCheckout(checkout.id, customer, isDelivery));
})
);
}
@Action(actions.SetBuyerToCheckout)
setBuyerToCheckout(
ctx: StateContext<CartStateModel>,
{ checkoutId, customer, isDelivery }: actions.SetBuyerToCheckout
) {
return this.checkoutService
.setBuyer(checkoutId, this.buyerObject(customer))
.pipe(
tap((checkout: CheckoutDTO) => {
if (!isDelivery) {
this.store.dispatch(new actions.CreateOrder(checkout.id));
} else {
this.store.dispatch(
new actions.SetPayerToCheckout(checkout.id, customer)
);
}
})
);
setBuyerToCheckout(ctx: StateContext<CartStateModel>, { checkoutId, customer, isDelivery }: actions.SetBuyerToCheckout) {
return this.checkoutService.setBuyer(checkoutId, this.buyerObject(customer)).pipe(
tap((checkout: CheckoutDTO) => {
if (!isDelivery) {
this.store.dispatch(new actions.CreateOrder(checkout.id));
} else {
this.store.dispatch(new actions.SetPayerToCheckout(checkout.id, customer));
}
})
);
}
@Action(actions.SetPayerToCheckout)
setPayerToCheckout(
ctx: StateContext<CartStateModel>,
{ checkoutId, customer }: actions.SetPayerToCheckout
) {
return this.checkoutService
.setPayer(checkoutId, this.payerObject(customer))
.pipe(
tap((checkout: CheckoutDTO) => {
this.store.dispatch(new actions.CreateOrder(checkout.id));
})
);
setPayerToCheckout(ctx: StateContext<CartStateModel>, { checkoutId, customer }: actions.SetPayerToCheckout) {
return this.checkoutService.setPayer(checkoutId, this.payerObject(customer)).pipe(
tap((checkout: CheckoutDTO) => {
this.store.dispatch(new actions.CreateOrder(checkout.id));
})
);
}
@Action(actions.SetDestinationToCheckout)
setDestinationToCheckout(
ctx: StateContext<CartStateModel>,
{
checkoutId,
destinationId,
customer,
target,
}: actions.SetDestinationToCheckout
{ checkoutId, destinationId, customer, target }: actions.SetDestinationToCheckout
) {
const dest = this.destinationObject(customer, destinationId, target);
return this.checkoutService.setDestination(checkoutId, destinationId, dest);
}
@Action(actions.ReloadCartData)
reloadCarts(
ctx: StateContext<CartStateModel>,
{ carts }: actions.ReloadCartData
) {
reloadCarts(ctx: StateContext<CartStateModel>, { carts }: actions.ReloadCartData) {
ctx.setState({ carts: { ...carts } });
}
@Action(actions.SetNotificationChannel)
setNotificationChannel(
ctx: StateContext<CartStateModel>,
{ checkoutId, notificationChannel }: actions.SetNotificationChannel
) {
return this.checkoutService.setNotificationChannel(
checkoutId,
notificationChannel
);
setNotificationChannel(ctx: StateContext<CartStateModel>, { checkoutId, notificationChannel }: actions.SetNotificationChannel) {
return this.checkoutService.setNotificationChannel(checkoutId, notificationChannel);
}
private syncApiState(carts: { [key: number]: number[] }) {
@@ -319,9 +238,7 @@ export class CartState {
}
private payerObject(customer: User) {
const invoice = customer.invoice_address
? customer.invoice_address
: customer.delivery_addres;
const invoice = customer.invoice_address ? customer.invoice_address : customer.delivery_addres;
const transformed = this.customerMapper.fromUser(customer);
let organisation: OrganisationDTO = {};
@@ -356,24 +273,16 @@ export class CartState {
return payerDTO;
}
private destinationObject(
customer: User,
destinationId: number,
target?: EnvironmentChannel
) {
private destinationObject(customer: User, destinationId: number, target?: EnvironmentChannel) {
const delivery = customer.delivery_addres;
if (!delivery) {
this.cartService.addOrderErrorEvent();
throw new Error(
`Delvery address is missing for customer: ${
customer.first_name + ' ' + customer.last_name
} when trying to set destination object.
`Delvery address is missing for customer: ${customer.first_name + ' ' + customer.last_name} when trying to set destination object.
Source => cart.state.ts.destinationObject. Line 238`
);
}
const shippingAddress = this.customerMapper.fromUserToShippingAddressDTO(
customer
);
const shippingAddress = this.customerMapper.fromUserToShippingAddressDTO(customer);
const destinationDTO: DestinationDTO = {
shippingAddress,

View File

@@ -18,7 +18,7 @@ export class CountryState {
constructor(private customerService: CustomerService) {}
@Action(LoadCountries)
loadCountries(ctx: StateContext<CountryStateModel>, { }: LoadCountries) {
loadCountries(ctx: StateContext<CountryStateModel>, {}: LoadCountries) {
return this.customerService.getCountries().pipe(
tap((_countries: Country[]) => {
const state = ctx.getState();

View File

@@ -40,10 +40,7 @@ export class CustomerState {
constructor(private store: Store, private customerService: CustomerService) {}
@Action(actions.SearchUser)
searchUser(
ctx: StateContext<CustomerStateModel>,
{ payload }: actions.SearchUser
): Observable<User[]> {
searchUser(ctx: StateContext<CustomerStateModel>, { payload }: actions.SearchUser): Observable<User[]> {
return this.customerService.searchCustomer(payload).pipe(
map((response: CustomerSearchResponse) => response.customers),
tap((_customers: User[]) => {
@@ -58,30 +55,21 @@ export class CustomerState {
customers = { ...customers, [t.id]: t };
});
ctx.patchState({ customers });
this.syncApiState(
customers,
state.lastCreatedCustomerId,
state.cachedCustomerSearch
);
this.syncApiState(customers, state.lastCreatedCustomerId, state.cachedCustomerSearch);
this.store.dispatch(new AddCustomerIds(customerIds));
})
);
}
@Action(actions.AddCustomers)
addCustomers(
ctx: StateContext<CustomerStateModel>,
{ payload }: actions.AddCustomers
) {
addCustomers(ctx: StateContext<CustomerStateModel>, { payload }: actions.AddCustomers) {
const state = ctx.getState();
if (!state) {
return;
}
const currentCustomers = state.customers;
const newCustomers = payload.filter((t) => t !== undefined);
const currentCustomerIds = this.store.selectSnapshot(
ProcessSelectors.getCustomerIds
);
const currentCustomerIds = this.store.selectSnapshot(ProcessSelectors.getCustomerIds);
const customerIds = [];
let customers = currentCustomers;
if (!!currentCustomerIds) {
@@ -96,19 +84,12 @@ export class CustomerState {
}
});
ctx.patchState({ customers });
this.syncApiState(
customers,
state.lastCreatedCustomerId,
state.cachedCustomerSearch
);
this.syncApiState(customers, state.lastCreatedCustomerId, state.cachedCustomerSearch);
this.store.dispatch(new AddCustomerIds(customerIds));
}
@Action(actions.SetActiveUser)
setActiveUser(
ctx: StateContext<CustomerStateModel>,
{ payload, cartHasItemForDownload, cartEntriesIds }: actions.SetActiveUser
) {
setActiveUser(ctx: StateContext<CustomerStateModel>, { payload, cartHasItemForDownload, cartEntriesIds }: actions.SetActiveUser) {
const state = ctx.getState();
if (!state) {
return;
@@ -120,21 +101,14 @@ export class CustomerState {
ctx.patchState({ customers });
this.store.dispatch(new SetActiveCustomer(_customer.id));
this.store.dispatch(new UpdateProcessName(_customer.last_name));
this.syncApiState(
customers,
state.lastCreatedCustomerId,
state.cachedCustomerSearch
);
this.syncApiState(customers, state.lastCreatedCustomerId, state.cachedCustomerSearch);
}
})
);
}
@Action(actions.AddUser)
addUser(
ctx: StateContext<CustomerStateModel>,
{ payload, setActiveUser }: actions.AddUser
) {
addUser(ctx: StateContext<CustomerStateModel>, { payload, setActiveUser }: actions.AddUser) {
const state = ctx.getState();
let customerApi$: Observable<User>;
let isOnline = false;
@@ -190,8 +164,7 @@ export class CustomerState {
this.store.dispatch(
new SetOnlineCustomerCreationStatus({
error: true,
invalidProperties:
error && error.error ? error.error.invalidProperties : undefined,
invalidProperties: error && error.error ? error.error.invalidProperties : undefined,
})
);
console.error(error);
@@ -201,30 +174,20 @@ export class CustomerState {
}
@Action(actions.SetUserDetails)
editUser(
ctx: StateContext<CustomerStateModel>,
{ payload, addBreadcrumb }: actions.SetUserDetails
) {
editUser(ctx: StateContext<CustomerStateModel>, { payload, addBreadcrumb }: actions.SetUserDetails) {
const state = ctx.getState();
const id = +payload.id;
if (!state) {
return;
}
if (
payload.features &&
payload.features.findIndex((v) => v.key === 'onlineshop') >= 0
) {
if (payload.features && payload.features.findIndex((v) => v.key === 'onlineshop') >= 0) {
const customers = {
...state.customers,
[id]: { ...payload, id: id, error: null },
};
ctx.patchState({ customers });
this.syncApiState(
customers,
state.lastCreatedCustomerId,
state.cachedCustomerSearch
);
this.syncApiState(customers, state.lastCreatedCustomerId, state.cachedCustomerSearch);
return;
}
@@ -258,20 +221,13 @@ export class CustomerState {
)
);
}
this.syncApiState(
customers,
state.lastCreatedCustomerId,
state.cachedCustomerSearch
);
this.syncApiState(customers, state.lastCreatedCustomerId, state.cachedCustomerSearch);
})
);
}
@Action(actions.SetUserDetailsById)
getUserDetails(
ctx: StateContext<CustomerStateModel>,
{ payload, addBreadcrumb }: actions.SetUserDetailsById
) {
getUserDetails(ctx: StateContext<CustomerStateModel>, { payload, addBreadcrumb }: actions.SetUserDetailsById) {
const state = ctx.getState();
if (!state) {
return;
@@ -279,12 +235,7 @@ export class CustomerState {
return this.customerService.getCustomerById(payload).pipe(
tap((user: User) => {
if (user) {
ctx.setState(
this.updateCustomer(
{ ...user, id: +payload },
state.lastCreatedCustomerId
)
);
ctx.setState(this.updateCustomer({ ...user, id: +payload }, state.lastCreatedCustomerId));
}
})
);
@@ -298,10 +249,7 @@ export class CustomerState {
}
@Action(actions.DeleteCustomerForProcess)
deleteCustomerForProcess(
ctx: StateContext<CustomerStateModel>,
{ payload }: actions.DeleteCustomerForProcess
) {
deleteCustomerForProcess(ctx: StateContext<CustomerStateModel>, { payload }: actions.DeleteCustomerForProcess) {
const state = ctx.getState();
if (!state) {
return;
@@ -310,29 +258,19 @@ export class CustomerState {
delete customers[payload];
ctx.patchState({ customers });
this.store.dispatch(new RemoveCustomerId(payload));
this.syncApiState(
customers,
state.lastCreatedCustomerId,
state.cachedCustomerSearch
);
this.syncApiState(customers, state.lastCreatedCustomerId, state.cachedCustomerSearch);
return this.customerService.deleteCustomer(payload);
}
@Action(actions.SetDefaultShippingAddress)
setDefaultShippingAddress(
ctx: StateContext<CustomerStateModel>,
{ customerId, shippingAddress }: actions.SetDefaultShippingAddress
) {
setDefaultShippingAddress(ctx: StateContext<CustomerStateModel>, { customerId, shippingAddress }: actions.SetDefaultShippingAddress) {
const state = ctx.getState();
if (!state) {
return;
}
const currentCustomers = state.customers;
const shipping$ = this.customerService.setShippingAddressAsDefault(
shippingAddress,
customerId
);
const shipping$ = this.customerService.setShippingAddressAsDefault(shippingAddress, customerId);
if (!shipping$) {
return;
}
@@ -341,38 +279,26 @@ export class CustomerState {
const customer = currentCustomers[customerId];
const updatedCustomer = {
...customer,
delivery_addres: customer.poossible_delivery_addresses.find(
(t) => t.id === shippingAddress.id
),
delivery_addres: customer.poossible_delivery_addresses.find((t) => t.id === shippingAddress.id),
};
const customers = {
...currentCustomers,
[updatedCustomer.id]: updatedCustomer,
};
ctx.patchState({ customers });
this.syncApiState(
customers,
state.lastCreatedCustomerId,
state.cachedCustomerSearch
);
this.syncApiState(customers, state.lastCreatedCustomerId, state.cachedCustomerSearch);
})
);
}
@Action(actions.SetDefaultInvoiceAddress)
setDefaultInvoiceAddress(
ctx: StateContext<CustomerStateModel>,
{ customerId, invoiceAddress }: actions.SetDefaultInvoiceAddress
) {
setDefaultInvoiceAddress(ctx: StateContext<CustomerStateModel>, { customerId, invoiceAddress }: actions.SetDefaultInvoiceAddress) {
const state = ctx.getState();
if (!state) {
return;
}
const currentCustomers = state.customers;
const invoice$ = this.customerService.setInvoiceAddressAsDefault(
invoiceAddress,
customerId
);
const invoice$ = this.customerService.setInvoiceAddressAsDefault(invoiceAddress, customerId);
if (!invoice$) {
return;
}
@@ -381,29 +307,20 @@ export class CustomerState {
const customer = currentCustomers[customerId];
const updatedCustomer = {
...customer,
invoice_address: customer.poossible_invoice_addresses.find(
(t) => t.id === invoiceAddress.id
),
invoice_address: customer.poossible_invoice_addresses.find((t) => t.id === invoiceAddress.id),
};
const customers = {
...currentCustomers,
[updatedCustomer.id]: updatedCustomer,
};
ctx.patchState({ customers });
this.syncApiState(
customers,
state.lastCreatedCustomerId,
state.cachedCustomerSearch
);
this.syncApiState(customers, state.lastCreatedCustomerId, state.cachedCustomerSearch);
})
);
}
@Action(actions.AddNewShippingAddress)
addNewShippingAddress(
ctx: StateContext<CustomerStateModel>,
{ customerId, shippingAddress }: actions.AddNewShippingAddress
) {
addNewShippingAddress(ctx: StateContext<CustomerStateModel>, { customerId, shippingAddress }: actions.AddNewShippingAddress) {
const state = ctx.getState();
if (!state) {
return;
@@ -419,31 +336,15 @@ export class CustomerState {
updatedCustomer = <User>{
...customer,
delivery_addres: address,
poossible_delivery_addresses: [
...(customer.poossible_delivery_addresses.filter(
(t) => t.id !== address.id
) || []),
address,
],
poossible_invoice_addresses: [
...(customer.poossible_invoice_addresses.filter(
(t) => t.id !== address.id
) || []),
address,
],
poossible_delivery_addresses: [...(customer.poossible_delivery_addresses.filter((t) => t.id !== address.id) || []), address],
poossible_invoice_addresses: [...(customer.poossible_invoice_addresses.filter((t) => t.id !== address.id) || []), address],
};
} else {
updatedCustomer = <User>{
...customer,
delivery_addres: address,
poossible_delivery_addresses: [
...(customer.poossible_delivery_addresses || []),
address,
],
poossible_invoice_addresses: [
...(customer.poossible_invoice_addresses || []),
address,
],
poossible_delivery_addresses: [...(customer.poossible_delivery_addresses || []), address],
poossible_invoice_addresses: [...(customer.poossible_invoice_addresses || []), address],
};
}
this.store.dispatch(new actions.SetUserDetailsById(customerId));
@@ -452,20 +353,13 @@ export class CustomerState {
[updatedCustomer.id]: updatedCustomer,
};
ctx.patchState({ customers });
this.syncApiState(
customers,
state.lastCreatedCustomerId,
state.cachedCustomerSearch
);
this.syncApiState(customers, state.lastCreatedCustomerId, state.cachedCustomerSearch);
})
);
}
@Action(actions.AddNewInvoiceAddress)
addNewInvoiceAddress(
ctx: StateContext<CustomerStateModel>,
{ customerId, invoiceAddress }: actions.AddNewInvoiceAddress
) {
addNewInvoiceAddress(ctx: StateContext<CustomerStateModel>, { customerId, invoiceAddress }: actions.AddNewInvoiceAddress) {
const state = ctx.getState();
if (!state) {
return;
@@ -482,30 +376,17 @@ export class CustomerState {
...customer,
invoice_address: address,
poossible_delivery_addresses: [
...(customer.poossible_delivery_addresses.filter(
(t) => t && t.id !== address.id
) || []),
address,
],
poossible_invoice_addresses: [
...(customer.poossible_invoice_addresses.filter(
(t) => t && t.id !== address.id
) || []),
...(customer.poossible_delivery_addresses.filter((t) => t && t.id !== address.id) || []),
address,
],
poossible_invoice_addresses: [...(customer.poossible_invoice_addresses.filter((t) => t && t.id !== address.id) || []), address],
};
} else {
updatedCustomer = <User>{
...customer,
invoice_address: address,
poossible_delivery_addresses: [
...(customer.poossible_delivery_addresses || []),
address,
],
poossible_invoice_addresses: [
...(customer.poossible_invoice_addresses || []),
address,
],
poossible_delivery_addresses: [...(customer.poossible_delivery_addresses || []), address],
poossible_invoice_addresses: [...(customer.poossible_invoice_addresses || []), address],
};
}
this.store.dispatch(new actions.SetUserDetailsById(customerId));
@@ -514,20 +395,13 @@ export class CustomerState {
[updatedCustomer.id]: updatedCustomer,
};
ctx.patchState({ customers });
this.syncApiState(
customers,
state.lastCreatedCustomerId,
state.cachedCustomerSearch
);
this.syncApiState(customers, state.lastCreatedCustomerId, state.cachedCustomerSearch);
})
);
}
@Action(actions.SetLastCreatedCustomerId)
setLastCreatedCustomerId(
ctx: StateContext<CustomerStateModel>,
{ customerId }: actions.SetLastCreatedCustomerId
) {
setLastCreatedCustomerId(ctx: StateContext<CustomerStateModel>, { customerId }: actions.SetLastCreatedCustomerId) {
const state = ctx.getState();
if (!state) {
return;
@@ -537,45 +411,30 @@ export class CustomerState {
}
@Action(actions.SetCachedCustomers)
setCachedCustomers(
ctx: StateContext<CustomerStateModel>,
{ cachedCustomerSearch }: actions.SetCachedCustomers
) {
setCachedCustomers(ctx: StateContext<CustomerStateModel>, { cachedCustomerSearch }: actions.SetCachedCustomers) {
const state = ctx.getState();
const currentProcessId = this.store.selectSnapshot(
AppState.getCurrentProcessId
);
const currentProcessId = this.store.selectSnapshot(AppState.getCurrentProcessId);
if (currentProcessId) {
const cachedCustomers = { ...state.cachedCustomerSearch };
cachedCustomers[currentProcessId] = cachedCustomerSearch;
ctx.patchState({ cachedCustomerSearch: cachedCustomers });
this.syncApiState(
state.customers,
state.lastCreatedCustomerId,
cachedCustomers
);
this.syncApiState(state.customers, state.lastCreatedCustomerId, cachedCustomers);
}
}
@Action(actions.ClearCachedCustomers)
clearCachedCustomers(ctx: StateContext<CustomerStateModel>) {
const state = ctx.getState();
const currentProcessId = this.store.selectSnapshot(
AppState.getCurrentProcessId
);
const currentProcessId = this.store.selectSnapshot(AppState.getCurrentProcessId);
if (currentProcessId) {
const cachedCustomers = { ...state.cachedCustomerSearch };
cachedCustomers[currentProcessId] = undefined;
ctx.patchState({ cachedCustomerSearch: cachedCustomers });
this.syncApiState(
state.customers,
state.lastCreatedCustomerId,
cachedCustomers
);
this.syncApiState(state.customers, state.lastCreatedCustomerId, cachedCustomers);
}
}
@@ -590,11 +449,7 @@ export class CustomerState {
@Action(actions.ReloadCustomersData)
reloadProcesses(
ctx: StateContext<CustomerStateModel>,
{
customers,
lastCreatedCustomerId,
cachedCustomerSearch,
}: actions.ReloadCustomersData
{ customers, lastCreatedCustomerId, cachedCustomerSearch }: actions.ReloadCustomersData
) {
ctx.patchState({ customers, lastCreatedCustomerId, cachedCustomerSearch });
}

View File

@@ -38,10 +38,7 @@ export class FilterState {
constructor(private filterService: FilterService, private store: Store) {}
@Action(actions.LoadFilters)
load(
ctx: StateContext<FilterStateModel>,
{ filterType }: actions.LoadFilters
) {
load(ctx: StateContext<FilterStateModel>, { filterType }: actions.LoadFilters) {
let filter$: Observable<Filter[]>;
if (filterType === FilterType.Default) {
filter$ = this.filterService.getFilters();
@@ -52,45 +49,23 @@ export class FilterState {
if (filterType === FilterType.Negative) {
filter$ = this.filterService.getNegativeFilters();
}
return filter$.pipe(
tap((filters: Filter[]) =>
this.loadFilterEffects(filters, ctx, filterType)
)
);
return filter$.pipe(tap((filters: Filter[]) => this.loadFilterEffects(filters, ctx, filterType)));
}
loadFilterEffects(
filters: Filter[],
ctx: StateContext<FilterStateModel>,
filterType: FilterType
) {
loadFilterEffects(filters: Filter[], ctx: StateContext<FilterStateModel>, filterType: FilterType) {
const state = ctx.getState();
const currentProcessId = this.store.selectSnapshot(
AppState.getCurrentProcessId
);
const dropdownFilters =
filterType === FilterType.Negative
? state.negativeDropdownFilters
: state.dropdownFilters;
const currentProcessId = this.store.selectSnapshot(AppState.getCurrentProcessId);
const dropdownFilters = filterType === FilterType.Negative ? state.negativeDropdownFilters : state.dropdownFilters;
const existingFilterState = dropdownFilters[currentProcessId];
let newFilterState = filters;
if (
existingFilterState &&
existingFilterState.length > 0 &&
newFilterState &&
newFilterState.length > 0
) {
if (existingFilterState && existingFilterState.length > 0 && newFilterState && newFilterState.length > 0) {
newFilterState = newFilterState.map((t) => {
const filterExistingState = existingFilterState.find(
(ex) => ex.id === t.id
);
const filterExistingState = existingFilterState.find((ex) => ex.id === t.id);
if (filterExistingState) {
return <Filter>{
...t,
items: t.items.map((eit) => {
const filterItemExistingState = filterExistingState.items.find(
(it) => it.id === eit.id
);
const filterItemExistingState = filterExistingState.items.find((it) => it.id === eit.id);
if (filterItemExistingState) {
return <FilterItem>{
...eit,
@@ -112,41 +87,29 @@ export class FilterState {
if (!itemExists) {
items = {
...dropdownFilters,
[currentProcessId]: [
...newFilterState.filter((fil: Filter) => fil.id !== 'cattype'),
],
[currentProcessId]: [...newFilterState.filter((fil: Filter) => fil.id !== 'cattype')],
};
} else {
items[currentProcessId] = [
...newFilterState.filter((fil: Filter) => fil.id !== 'cattype'),
];
items[currentProcessId] = [...newFilterState.filter((fil: Filter) => fil.id !== 'cattype')];
}
ctx.patchState({
filters: [...newFilterState],
dropdownFilters:
filterType === FilterType.Negative ? state.dropdownFilters : items,
negativeDropdownFilters:
filterType === FilterType.Negative
? items
: state.negativeDropdownFilters,
dropdownFilters: filterType === FilterType.Negative ? state.dropdownFilters : items,
negativeDropdownFilters: filterType === FilterType.Negative ? items : state.negativeDropdownFilters,
});
this.syncApiState(
[...newFilterState],
state.processesSelectedFilters,
state.negativeProcessesSelectedFilters,
filterType === FilterType.Negative ? state.dropdownFilters : items,
filterType === FilterType.Negative
? items
: state.negativeDropdownFilters,
filterType === FilterType.Negative ? items : state.negativeDropdownFilters,
state.filterType
);
}
@Action(actions.ResetFilters)
resetFilters(ctx: StateContext<FilterStateModel>) {
const currentProcessId = this.store.selectSnapshot(
AppState.getCurrentProcessId
);
const currentProcessId = this.store.selectSnapshot(AppState.getCurrentProcessId);
return this.filterService.getFilters().pipe(
tap((filters: Filter[]) => {
const dropdownFilters = ctx.getState().dropdownFilters;
@@ -206,8 +169,7 @@ export class FilterState {
}),
];
const negativeProcessSelectedFilters = ctx.getState()
.negativeProcessesSelectedFilters;
const negativeProcessSelectedFilters = ctx.getState().negativeProcessesSelectedFilters;
const updatedNegativeProcessesSelectedFilters = [
...negativeProcessSelectedFilters.map((processFilter) => {
if (processFilter.processId === currentProcessId) {
@@ -240,25 +202,15 @@ export class FilterState {
}
@Action(actions.SelectFilterById)
selectFilterById(
ctx: StateContext<FilterStateModel>,
{ id }: actions.SelectFilterById
) {
selectFilterById(ctx: StateContext<FilterStateModel>, { id }: actions.SelectFilterById) {
const state = ctx.getState();
const currentProcessId = this.store.selectSnapshot(
AppState.getCurrentProcessId
);
const currentProcessId = this.store.selectSnapshot(AppState.getCurrentProcessId);
const filterType = state.filterType[currentProcessId];
const filters =
filterType === FilterType.Negative
? state.negativeDropdownFilters[currentProcessId]
: state.dropdownFilters[currentProcessId];
filterType === FilterType.Negative ? state.negativeDropdownFilters[currentProcessId] : state.dropdownFilters[currentProcessId];
return this.filterService.selectFilterById(filters, id).pipe(
tap((f: Filter[]) => {
const dropdownFilters =
filterType === FilterType.Negative
? state.negativeDropdownFilters
: state.dropdownFilters;
const dropdownFilters = filterType === FilterType.Negative ? state.negativeDropdownFilters : state.dropdownFilters;
let items = <{ [id: number]: Filter[] }>{};
if (dropdownFilters) {
items = { ...dropdownFilters };
@@ -270,21 +222,15 @@ export class FilterState {
items[currentProcessId] = f;
}
ctx.patchState({
dropdownFilters:
filterType === FilterType.Negative ? state.dropdownFilters : items,
negativeDropdownFilters:
filterType === FilterType.Negative
? items
: state.negativeDropdownFilters,
dropdownFilters: filterType === FilterType.Negative ? state.dropdownFilters : items,
negativeDropdownFilters: filterType === FilterType.Negative ? items : state.negativeDropdownFilters,
});
this.syncApiState(
state.filters,
state.processesSelectedFilters,
state.negativeProcessesSelectedFilters,
filterType === FilterType.Negative ? state.dropdownFilters : items,
filterType === FilterType.Negative
? items
: state.negativeDropdownFilters,
filterType === FilterType.Negative ? items : state.negativeDropdownFilters,
state.filterType
);
})
@@ -292,25 +238,15 @@ export class FilterState {
}
@Action(actions.UnselectFilterById)
unselectFilterById(
ctx: StateContext<FilterStateModel>,
{ id }: actions.UnselectFilterById
) {
unselectFilterById(ctx: StateContext<FilterStateModel>, { id }: actions.UnselectFilterById) {
const state = ctx.getState();
const currentProcessId = this.store.selectSnapshot(
AppState.getCurrentProcessId
);
const currentProcessId = this.store.selectSnapshot(AppState.getCurrentProcessId);
const filterType = state.filterType[currentProcessId];
const filters =
filterType === FilterType.Negative
? state.negativeDropdownFilters[currentProcessId]
: state.dropdownFilters[currentProcessId];
filterType === FilterType.Negative ? state.negativeDropdownFilters[currentProcessId] : state.dropdownFilters[currentProcessId];
return this.filterService.unselectFilterById(filters, id).pipe(
tap((f: Filter[]) => {
const dropdownFilters =
filterType === FilterType.Negative
? state.negativeDropdownFilters
: state.dropdownFilters;
const dropdownFilters = filterType === FilterType.Negative ? state.negativeDropdownFilters : state.dropdownFilters;
let items = <{ [id: number]: Filter[] }>{};
if (dropdownFilters) {
items = { ...dropdownFilters };
@@ -322,21 +258,15 @@ export class FilterState {
items[currentProcessId] = f;
}
ctx.patchState({
dropdownFilters:
filterType === FilterType.Negative ? state.dropdownFilters : items,
negativeDropdownFilters:
filterType === FilterType.Negative
? items
: state.negativeDropdownFilters,
dropdownFilters: filterType === FilterType.Negative ? state.dropdownFilters : items,
negativeDropdownFilters: filterType === FilterType.Negative ? items : state.negativeDropdownFilters,
});
this.syncApiState(
state.filters,
state.processesSelectedFilters,
state.negativeProcessesSelectedFilters,
filterType === FilterType.Negative ? state.dropdownFilters : items,
filterType === FilterType.Negative
? items
: state.negativeDropdownFilters,
filterType === FilterType.Negative ? items : state.negativeDropdownFilters,
state.filterType
);
})
@@ -344,25 +274,15 @@ export class FilterState {
}
@Action(actions.ToggleFilterItemById)
toggleItemById(
ctx: StateContext<FilterStateModel>,
{ id }: actions.ToggleFilterItemById
) {
toggleItemById(ctx: StateContext<FilterStateModel>, { id }: actions.ToggleFilterItemById) {
const state = ctx.getState();
const currentProcessId = this.store.selectSnapshot(
AppState.getCurrentProcessId
);
const currentProcessId = this.store.selectSnapshot(AppState.getCurrentProcessId);
const filterType = state.filterType[currentProcessId];
const filters =
filterType === FilterType.Negative
? state.negativeDropdownFilters[currentProcessId]
: state.dropdownFilters[currentProcessId];
filterType === FilterType.Negative ? state.negativeDropdownFilters[currentProcessId] : state.dropdownFilters[currentProcessId];
return this.filterService.toggleFilterItemsById(filters, id).pipe(
tap((f: Filter[]) => {
const dropdownFilters =
filterType === FilterType.Negative
? state.negativeDropdownFilters
: state.dropdownFilters;
const dropdownFilters = filterType === FilterType.Negative ? state.negativeDropdownFilters : state.dropdownFilters;
let items = <{ [id: number]: Filter[] }>{};
if (dropdownFilters) {
items = { ...dropdownFilters };
@@ -374,21 +294,15 @@ export class FilterState {
items[currentProcessId] = f;
}
ctx.patchState({
dropdownFilters:
filterType === FilterType.Negative ? state.dropdownFilters : items,
negativeDropdownFilters:
filterType === FilterType.Negative
? items
: state.negativeDropdownFilters,
dropdownFilters: filterType === FilterType.Negative ? state.dropdownFilters : items,
negativeDropdownFilters: filterType === FilterType.Negative ? items : state.negativeDropdownFilters,
});
this.syncApiState(
state.filters,
state.processesSelectedFilters,
state.negativeProcessesSelectedFilters,
filterType === FilterType.Negative ? state.dropdownFilters : items,
filterType === FilterType.Negative
? items
: state.negativeDropdownFilters,
filterType === FilterType.Negative ? items : state.negativeDropdownFilters,
state.filterType
);
})
@@ -396,19 +310,12 @@ export class FilterState {
}
@Action(actions.ToggleFilterItemByName)
toggleItemByName(
ctx: StateContext<FilterStateModel>,
{ name }: actions.ToggleFilterItemByName
) {
toggleItemByName(ctx: StateContext<FilterStateModel>, { name }: actions.ToggleFilterItemByName) {
const state = ctx.getState();
const currentProcessId = this.store.selectSnapshot(
AppState.getCurrentProcessId
);
const currentProcessId = this.store.selectSnapshot(AppState.getCurrentProcessId);
const filterType = state.filterType[currentProcessId];
const filters =
filterType === FilterType.Negative
? state.negativeDropdownFilters[currentProcessId]
: state.dropdownFilters[currentProcessId];
filterType === FilterType.Negative ? state.negativeDropdownFilters[currentProcessId] : state.dropdownFilters[currentProcessId];
return this.filterService.toggleFilterItemsByName(filters, name).pipe(
tap((f: Filter[]) => {
let search = this.store.selectSnapshot(ProcessSelectors.getSearch);
@@ -416,10 +323,7 @@ export class FilterState {
search = { ...search, fitlers: f };
this.store.dispatch(new AddSearch(search));
}
const dropdownFilters =
filterType === FilterType.Negative
? state.negativeDropdownFilters
: state.dropdownFilters;
const dropdownFilters = filterType === FilterType.Negative ? state.negativeDropdownFilters : state.dropdownFilters;
let items = <{ [id: number]: Filter[] }>{};
if (dropdownFilters) {
items = { ...dropdownFilters };
@@ -430,12 +334,8 @@ export class FilterState {
} else {
items[currentProcessId] = f;
}
const updatedDropDownFilter =
filterType === FilterType.Negative ? state.dropdownFilters : items;
const updatedNegativeDropdownFilters =
filterType === FilterType.Negative
? items
: state.negativeDropdownFilters;
const updatedDropDownFilter = filterType === FilterType.Negative ? state.dropdownFilters : items;
const updatedNegativeDropdownFilters = filterType === FilterType.Negative ? items : state.negativeDropdownFilters;
ctx.patchState({
dropdownFilters: updatedDropDownFilter,
negativeDropdownFilters: updatedNegativeDropdownFilters,
@@ -453,30 +353,18 @@ export class FilterState {
}
@Action(actions.AddSelectedFilter)
addSelectedFilterToCurrentProcess(
ctx: StateContext<FilterStateModel>,
{ payload }: actions.AddSelectedFilter
) {
const currenProcessId = this.store.selectSnapshot(
AppState.getCurrentProcessId
);
addSelectedFilterToCurrentProcess(ctx: StateContext<FilterStateModel>, { payload }: actions.AddSelectedFilter) {
const currenProcessId = this.store.selectSnapshot(AppState.getCurrentProcessId);
const state = ctx.getState();
const filterType = state.filterType[currenProcessId];
const currentProcessSelectedFilters =
filterType === FilterType.Negative
? state.negativeProcessesSelectedFilters
: state.processesSelectedFilters;
const processExists = currentProcessSelectedFilters.find(
(t) => t.processId === currenProcessId
);
filterType === FilterType.Negative ? state.negativeProcessesSelectedFilters : state.processesSelectedFilters;
const processExists = currentProcessSelectedFilters.find((t) => t.processId === currenProcessId);
const updatedSelectedFilters = currentProcessSelectedFilters.map((item) => {
if (item.processId === currenProcessId) {
let filters = [];
if (item.selectedFilters) {
filters = [
...item.selectedFilters.filter((f) => f.id !== payload.id),
payload,
];
filters = [...item.selectedFilters.filter((f) => f.id !== payload.id), payload];
} else {
filters.push(payload);
}
@@ -491,25 +379,15 @@ export class FilterState {
let updatedProcessesSelectedFilters: ProcessSelectedFilters[];
let updatedNegativeProcessesSelectedFilters: ProcessSelectedFilters[];
if (processExists) {
updatedProcessesSelectedFilters =
filterType === FilterType.Negative
? state.processesSelectedFilters
: updatedSelectedFilters;
updatedProcessesSelectedFilters = filterType === FilterType.Negative ? state.processesSelectedFilters : updatedSelectedFilters;
updatedNegativeProcessesSelectedFilters =
filterType === FilterType.Negative
? updatedSelectedFilters
: state.negativeProcessesSelectedFilters;
filterType === FilterType.Negative ? updatedSelectedFilters : state.negativeProcessesSelectedFilters;
} else {
updatedProcessesSelectedFilters =
filterType === FilterType.Negative
? state.processesSelectedFilters
: [...state.processesSelectedFilters, processesSelectedFilters];
filterType === FilterType.Negative ? state.processesSelectedFilters : [...state.processesSelectedFilters, processesSelectedFilters];
updatedNegativeProcessesSelectedFilters =
filterType === FilterType.Negative
? [
...state.negativeProcessesSelectedFilters,
processesSelectedFilters,
]
? [...state.negativeProcessesSelectedFilters, processesSelectedFilters]
: state.negativeProcessesSelectedFilters;
}
ctx.patchState({
@@ -527,58 +405,38 @@ export class FilterState {
}
@Action(actions.RemoveSelectedFilter)
removeSelectedFilterFromCurrentProcess(
ctx: StateContext<FilterStateModel>,
{ payload }: actions.RemoveSelectedFilter
) {
removeSelectedFilterFromCurrentProcess(ctx: StateContext<FilterStateModel>, { payload }: actions.RemoveSelectedFilter) {
const state = ctx.getState();
const currenProcessId = this.store.selectSnapshot(
AppState.getCurrentProcessId
);
const currenProcessId = this.store.selectSnapshot(AppState.getCurrentProcessId);
const filterType = state.filterType[currenProcessId];
const currentProcessSelectedFilters =
filterType === FilterType.Negative
? state.negativeProcessesSelectedFilters
: state.processesSelectedFilters;
const updatedProcessesSelectedFilters = currentProcessSelectedFilters.map(
(processSelectedFilters) => {
if (processSelectedFilters.processId === currenProcessId) {
const updatedFilters = processSelectedFilters.selectedFilters.map(
(f) => {
return {
...f,
items: f.items.map((i) => {
if (i.id === payload.id && i.selected === true) {
return <FilterItem>{ ...i, selected: false };
}
return i;
}),
};
}
);
return { ...processSelectedFilters, selectedFilters: updatedFilters };
}
return processSelectedFilters;
filterType === FilterType.Negative ? state.negativeProcessesSelectedFilters : state.processesSelectedFilters;
const updatedProcessesSelectedFilters = currentProcessSelectedFilters.map((processSelectedFilters) => {
if (processSelectedFilters.processId === currenProcessId) {
const updatedFilters = processSelectedFilters.selectedFilters.map((f) => {
return {
...f,
items: f.items.map((i) => {
if (i.id === payload.id && i.selected === true) {
return <FilterItem>{ ...i, selected: false };
}
return i;
}),
};
});
return { ...processSelectedFilters, selectedFilters: updatedFilters };
}
);
return processSelectedFilters;
});
ctx.patchState({
processesSelectedFilters:
filterType === FilterType.Negative
? state.processesSelectedFilters
: updatedProcessesSelectedFilters,
processesSelectedFilters: filterType === FilterType.Negative ? state.processesSelectedFilters : updatedProcessesSelectedFilters,
negativeProcessesSelectedFilters:
filterType === FilterType.Negative
? updatedProcessesSelectedFilters
: state.negativeProcessesSelectedFilters,
filterType === FilterType.Negative ? updatedProcessesSelectedFilters : state.negativeProcessesSelectedFilters,
});
this.syncApiState(
state.filters,
filterType === FilterType.Negative
? state.processesSelectedFilters
: updatedProcessesSelectedFilters,
filterType === FilterType.Negative
? updatedProcessesSelectedFilters
: state.negativeProcessesSelectedFilters,
filterType === FilterType.Negative ? state.processesSelectedFilters : updatedProcessesSelectedFilters,
filterType === FilterType.Negative ? updatedProcessesSelectedFilters : state.negativeProcessesSelectedFilters,
state.dropdownFilters,
state.negativeDropdownFilters,
state.filterType
@@ -586,20 +444,14 @@ export class FilterState {
}
@Action(actions.DeleteSelectedFiltersForProcess)
deleteSelectedFiltersForProcess(
ctx: StateContext<FilterStateModel>,
{ payload }: actions.DeleteSelectedFiltersForProcess
) {
deleteSelectedFiltersForProcess(ctx: StateContext<FilterStateModel>, { payload }: actions.DeleteSelectedFiltersForProcess) {
const state = ctx.getState();
const currentProcessFilters = state.processesSelectedFilters;
const currentNegativeProcessFilters =
state.negativeProcessesSelectedFilters;
const processesSelectedFilters = removeItem<ProcessSelectedFilters>(
(item) => item.processId === payload
)(currentProcessFilters);
const negativeProcessesSelectedFilters = removeItem<ProcessSelectedFilters>(
(item) => item.processId === payload
)(currentNegativeProcessFilters);
const currentNegativeProcessFilters = state.negativeProcessesSelectedFilters;
const processesSelectedFilters = removeItem<ProcessSelectedFilters>((item) => item.processId === payload)(currentProcessFilters);
const negativeProcessesSelectedFilters = removeItem<ProcessSelectedFilters>((item) => item.processId === payload)(
currentNegativeProcessFilters
);
const dropdownFilters = ctx.getState().dropdownFilters;
let items = <{ [id: number]: Filter[] }>{};
if (dropdownFilters) {
@@ -635,15 +487,10 @@ export class FilterState {
}
@Action(actions.SetFilterType)
setFilterType(
ctx: StateContext<FilterStateModel>,
{ filterType }: actions.SetFilterType
) {
setFilterType(ctx: StateContext<FilterStateModel>, { filterType }: actions.SetFilterType) {
const state = ctx.getState();
const filterTypes = state.filterType;
const currenProcessId = this.store.selectSnapshot(
AppState.getCurrentProcessId
);
const currenProcessId = this.store.selectSnapshot(AppState.getCurrentProcessId);
const updatedFilterTypes = {
...filterTypes,
[currenProcessId]: filterType,
@@ -662,15 +509,10 @@ export class FilterState {
@Action(actions.ClearNegativeFilters)
clearNegativeFilters(ctx: StateContext<FilterStateModel>) {
const state = ctx.getState();
const negativeProcessesSelectedFilters =
state.negativeProcessesSelectedFilters;
const negativeProcessesSelectedFilters = state.negativeProcessesSelectedFilters;
const negativeDropdownFilters = state.negativeDropdownFilters;
const currenProcessId = this.store.selectSnapshot(
AppState.getCurrentProcessId
);
const updatedNegativeProcessesSelectedFilters = removeItem<
ProcessSelectedFilters
>((item) => item.processId === currenProcessId)(
const currenProcessId = this.store.selectSnapshot(AppState.getCurrentProcessId);
const updatedNegativeProcessesSelectedFilters = removeItem<ProcessSelectedFilters>((item) => item.processId === currenProcessId)(
negativeProcessesSelectedFilters
);
const updatedNegativeDropdownFilters = {

View File

@@ -11,8 +11,8 @@ export interface FormsStateModel {
@State<FormsStateModel>({
name: 'forms',
defaults: {
form: []
}
form: [],
},
})
export class FormsState {
constructor(private store: Store) {}
@@ -44,7 +44,7 @@ export class FormsState {
private syncApiState(formsState: { [id: number]: { [key: string]: string } }) {
const userSyncData: UserStateSyncData = {
formsState
formsState,
};
const userData = JSON.stringify(userSyncData);
this.store.dispatch(new AppUserDataSync(userData));

View File

@@ -30,7 +30,7 @@ export class GoodsInState {
if (!orders) {
return;
}
orders.forEach(order => {
orders.forEach((order) => {
const orderIsAlreadyAdded = updatedOrders.includes(order);
if (!orderIsAlreadyAdded) {
updatedOrders.push(order);

View File

@@ -2,27 +2,27 @@ import { State, Selector, Action, StateContext } from '@ngxs/store';
import { Notify } from '../actions/notifier.actions';
export class NotifierStateModel {
processId: number;
processId: number;
}
@State<NotifierStateModel> ({
name: 'notifier',
defaults: {
processId: null
}
@State<NotifierStateModel>({
name: 'notifier',
defaults: {
processId: null,
},
})
export class NotifierState {
@Selector()
static getNotifier(state: NotifierStateModel) {
return state.processId;
}
@Selector()
static getNotifier(state: NotifierStateModel) {
return state.processId;
}
@Action(Notify)
notify(ctx: StateContext<NotifierStateModel>, { payload }: Notify) {
const state = ctx.getState();
ctx.patchState({
...state,
processId: payload
});
}
@Action(Notify)
notify(ctx: StateContext<NotifierStateModel>, { payload }: Notify) {
const state = ctx.getState();
ctx.patchState({
...state,
processId: payload,
});
}
}

View File

@@ -29,8 +29,8 @@ export interface ProcessStateModel {
name: 'processes',
defaults: {
processes: [],
recentArticles: []
}
recentArticles: [],
},
})
export class ProcessState {
constructor(protected productService: ProductService, private store: Store) {}
@@ -71,24 +71,24 @@ export class ProcessState {
id: 1,
name: 'Autor',
key: 'author',
selected: false
selected: false,
},
<RadioButton>{
id: 2,
name: 'Titel',
key: 'title',
selected: false
selected: false,
},
<RadioButton>{
id: 3,
name: 'Verlag',
key: 'publisher',
selected: false
}
]
}
}
}
selected: false,
},
],
},
},
},
};
ctx.patchState({ processes });
this.store
@@ -221,7 +221,7 @@ export class ProcessState {
previousRoute: previousRoute,
currentRoute: payload,
new: false,
currentRouteQueryParams: queryParams
currentRouteQueryParams: queryParams,
};
ctx.setState(this.updateProcess(process));
@@ -246,7 +246,7 @@ export class ProcessState {
if (products) {
ctx.patchState({
...state,
recentArticles: products.reverse().slice(0, 5)
recentArticles: products.reverse().slice(0, 5),
});
}
})
@@ -416,7 +416,7 @@ export class ProcessState {
if (onlineCustomerCreationError && onlineCustomerCreationError.error) {
const updatedOnlineCustomerCreationError = {
...onlineCustomerCreationError,
invalidProperties: { ...onlineCustomerCreationError.invalidProperties, [field]: undefined }
invalidProperties: { ...onlineCustomerCreationError.invalidProperties, [field]: undefined },
};
if (Object.keys(updatedOnlineCustomerCreationError.invalidProperties).length < 1) {
updatedOnlineCustomerCreationError.error = false;
@@ -531,7 +531,7 @@ export class ProcessState {
const recentArticles = state.recentArticles;
const currentProcessId = this.store.selectSnapshot(AppState.getCurrentProcessId);
const currentCustomerIds = currentProcesses[currentProcessId].customerIds;
const customerIds = currentCustomerIds.filter(t => t !== payload);
const customerIds = currentCustomerIds.filter((t) => t !== payload);
const process = { ...currentProcesses[currentProcessId], customerIds };
ctx.setState(this.updateProcess(process));
@@ -593,7 +593,7 @@ export class ProcessState {
ordersOpenend: oldProcess.ordersOpenend,
articleSearchErrorStatus: oldProcess.articleSearchErrorStatus,
productSearchFilters: oldProcess.productSearchFilters,
customerNotificationFlag: false
customerNotificationFlag: false,
};
const processes = { ...currentProcesses };
processes[oldProcess.id] = newProcess;
@@ -681,23 +681,23 @@ export class ProcessState {
id: 1,
name: 'Autor',
key: 'author',
selected: false
selected: false,
},
<RadioButton>{
id: 2,
name: 'Titel',
key: 'title',
selected: false
selected: false,
},
<RadioButton>{
id: 3,
name: 'Verlag',
key: 'publisher',
selected: false
}
]
}
}
selected: false,
},
],
},
},
};
ctx.setState(this.updateProcess(process));
} catch (error) {
@@ -753,7 +753,7 @@ export class ProcessState {
return;
}
return patch({
processes: patch({ [process.id]: process })
processes: patch({ [process.id]: process }),
});
}
@@ -761,7 +761,7 @@ export class ProcessState {
const userSyncData: UserStateSyncData = {
currentProcesssId,
processes,
recentArticles
recentArticles,
};
const userData = JSON.stringify(userSyncData);
this.store.dispatch(new AppUserDataSync(userData));

View File

@@ -5,10 +5,7 @@ import * as actions from '../actions/remission.actions';
import { UserStateSyncData } from '../../models/user-state-sync.model';
import { AppUserDataSync } from '../actions/app.actions';
import { isNullOrUndefined } from 'util';
import {
RemissionResourceType,
RemissionTargetType,
} from '../../../modules/remission/models/remission-resource-type.model';
import { RemissionResourceType, RemissionTargetType } from '../../../modules/remission/models/remission-resource-type.model';
import { RemissionService, RemissionProcess } from '@isa/remission';
import { RemissionFinishingProcessStatus } from '../../../modules/remission/models/remission-finishing-process-status.enum';
import get from 'lodash/get';
@@ -32,10 +29,7 @@ export class RemissionState {
constructor(private store: Store) {}
@Action(actions.SetRemissionCreated)
setRemissionCreated(
ctx: StateContext<RemissionStateModel>,
{ status }: actions.SetRemissionCreated
) {
setRemissionCreated(ctx: StateContext<RemissionStateModel>, { status }: actions.SetRemissionCreated) {
const state = ctx.getState();
const currentRemission = state.remission;
const remission: Remission = {
@@ -48,10 +42,7 @@ export class RemissionState {
}
@Action(actions.SetRemissionStarted)
setRemissionStarted(
ctx: StateContext<RemissionStateModel>,
{ status }: actions.SetRemissionStarted
) {
setRemissionStarted(ctx: StateContext<RemissionStateModel>, { status }: actions.SetRemissionStarted) {
const state = ctx.getState();
const currentRemission = state.remission;
const remission: Remission = {
@@ -63,10 +54,7 @@ export class RemissionState {
}
@Action(actions.SetRemissionCompleted)
setRemissionCompleted(
ctx: StateContext<RemissionStateModel>,
{ status }: actions.SetRemissionCompleted
) {
setRemissionCompleted(ctx: StateContext<RemissionStateModel>, { status }: actions.SetRemissionCompleted) {
const state = ctx.getState();
const currentRemission = state.remission;
const remission: Remission = {
@@ -78,19 +66,14 @@ export class RemissionState {
}
@Action(actions.SetRemissionProcess)
setRemissionProcess(
ctx: StateContext<RemissionStateModel>,
{ remissionProcess, initialValue }: actions.SetRemissionProcess
) {
setRemissionProcess(ctx: StateContext<RemissionStateModel>, { remissionProcess, initialValue }: actions.SetRemissionProcess) {
const state = ctx.getState();
const currentRemission = state.remission;
const filter = get(remissionProcess, 'filter.filter', null);
const remissionWithEmptyFilters =
filter === null ||
Object.keys(filter).every((sourceKey) =>
Object.keys(filter[sourceKey]).every(
(targetKey) => Object.keys(filter[sourceKey][targetKey]).length === 0
)
Object.keys(filter[sourceKey]).every((targetKey) => Object.keys(filter[sourceKey][targetKey]).length === 0)
);
const remission: Remission = {
...currentRemission,
@@ -118,10 +101,7 @@ export class RemissionState {
}
@Action(actions.SetRemissionFinishedProcessStatus)
setRemissionFinishedProcessStatus(
ctx: StateContext<RemissionStateModel>,
{ status }: actions.SetRemissionFinishedProcessStatus
) {
setRemissionFinishedProcessStatus(ctx: StateContext<RemissionStateModel>, { status }: actions.SetRemissionFinishedProcessStatus) {
const state = ctx.getState();
const currentRemission = state.remission;
const remission: Remission = {
@@ -133,10 +113,7 @@ export class RemissionState {
}
@Action(actions.SetRemissionScannedContainerId)
setRemissionScannedContainerId(
ctx: StateContext<RemissionStateModel>,
{ containerId }: actions.SetRemissionScannedContainerId
) {
setRemissionScannedContainerId(ctx: StateContext<RemissionStateModel>, { containerId }: actions.SetRemissionScannedContainerId) {
const state = ctx.getState();
const currentRemission = state.remission;
const remission: Remission = {
@@ -148,10 +125,7 @@ export class RemissionState {
}
@Action(actions.SetRemissionTarget)
setRemissionTarget(
ctx: StateContext<RemissionStateModel>,
{ target, source }: actions.SetRemissionTarget
) {
setRemissionTarget(ctx: StateContext<RemissionStateModel>, { target, source }: actions.SetRemissionTarget) {
const state = ctx.getState();
const currentRemission = state.remission;
let remission: Remission;
@@ -164,10 +138,7 @@ export class RemissionState {
}
@Action(actions.SetRemissionSource)
setRemissionSource(
ctx: StateContext<RemissionStateModel>,
{ source }: actions.SetRemissionSource
) {
setRemissionSource(ctx: StateContext<RemissionStateModel>, { source }: actions.SetRemissionSource) {
const state = ctx.getState();
const currentRemission = state.remission;
const remission: Remission = {
@@ -186,10 +157,7 @@ export class RemissionState {
}
@Action(actions.SetRemissionProducts)
setRemissionProducts(
ctx: StateContext<RemissionStateModel>,
{ products }: actions.SetRemissionProducts
) {
setRemissionProducts(ctx: StateContext<RemissionStateModel>, { products }: actions.SetRemissionProducts) {
const state = ctx.getState();
const currentRemission = state.remission;
const remission: Remission = {
@@ -201,10 +169,7 @@ export class RemissionState {
}
@Action(actions.SetRemissionSearchedProduct)
setRemissionSearchedProduct(
ctx: StateContext<RemissionStateModel>,
{ product }: actions.SetRemissionSearchedProduct
) {
setRemissionSearchedProduct(ctx: StateContext<RemissionStateModel>, { product }: actions.SetRemissionSearchedProduct) {
const state = ctx.getState();
const currentRemission = state.remission;
const remission: Remission = {
@@ -242,10 +207,7 @@ export class RemissionState {
}
@Action(actions.CompleteRemissionShippingDocument)
completeRemissionShippingDocument(
ctx: StateContext<RemissionStateModel>,
{ shippingDocument }: actions.SetRemissionShippingDocument
) {
completeRemissionShippingDocument(ctx: StateContext<RemissionStateModel>, { shippingDocument }: actions.SetRemissionShippingDocument) {
const state = ctx.getState();
const currentRemission = state.remission;
const currentRemissionProcess = currentRemission.remissionProcess;
@@ -255,9 +217,7 @@ export class RemissionState {
if (currentRemissionProcess.shippingDocuments) {
const shippingDocumentAlreadyExists =
currentRemissionProcess.shippingDocuments.findIndex(
(sd) => sd.id === shippingDocument.id
) !== -1;
currentRemissionProcess.shippingDocuments.findIndex((sd) => sd.id === shippingDocument.id) !== -1;
if (shippingDocumentAlreadyExists) {
updatedRemissionProcess = {
...updatedRemissionProcess,
@@ -277,8 +237,7 @@ export class RemissionState {
}
const remission: Remission = {
...currentRemission,
remissionFinishingProcessStatus:
RemissionFinishingProcessStatus.containerScanned,
remissionFinishingProcessStatus: RemissionFinishingProcessStatus.containerScanned,
remissionProcess: updatedRemissionProcess,
};
ctx.patchState({ remission });
@@ -286,10 +245,7 @@ export class RemissionState {
}
@Action(actions.DeleteRemissionShippingDocument)
deleteShippingDocument(
ctx: StateContext<RemissionStateModel>,
{ remissionProcessId }: actions.DeleteRemissionShippingDocument
) {
deleteShippingDocument(ctx: StateContext<RemissionStateModel>, { remissionProcessId }: actions.DeleteRemissionShippingDocument) {
const state = ctx.getState();
const currentRemission = state.remission;
@@ -305,10 +261,7 @@ export class RemissionState {
}
@Action(actions.SetRemissionShippingDocument)
setRemissionShippingDocument(
ctx: StateContext<RemissionStateModel>,
{ shippingDocument }: actions.SetRemissionShippingDocument
) {
setRemissionShippingDocument(ctx: StateContext<RemissionStateModel>, { shippingDocument }: actions.SetRemissionShippingDocument) {
const state = ctx.getState();
const currentRemission = state.remission;
const currentRemissionProcess = currentRemission.remissionProcess;
@@ -316,9 +269,7 @@ export class RemissionState {
if (currentRemissionProcess.shippingDocuments) {
const shippingDocumentAlreadyExists =
currentRemissionProcess.shippingDocuments.findIndex(
(sd) => sd.id === shippingDocument.id
) !== -1;
currentRemissionProcess.shippingDocuments.findIndex((sd) => sd.id === shippingDocument.id) !== -1;
if (shippingDocumentAlreadyExists) {
updatedRemissionProcess = {
...currentRemission.remissionProcess,
@@ -334,19 +285,13 @@ export class RemissionState {
} else {
updatedRemissionProcess = {
...currentRemission.remissionProcess,
shippingDocuments: [
...currentRemission.remissionProcess.shippingDocuments,
shippingDocument,
],
shippingDocuments: [...currentRemission.remissionProcess.shippingDocuments, shippingDocument],
};
}
} else {
updatedRemissionProcess = {
...currentRemission.remissionProcess,
shippingDocuments: [
...currentRemission.remissionProcess.shippingDocuments,
shippingDocument,
],
shippingDocuments: [...currentRemission.remissionProcess.shippingDocuments, shippingDocument],
};
}
const remission: Remission = {
@@ -419,10 +364,7 @@ export class RemissionState {
}
@Action(actions.ReloadRemission)
reload(
ctx: StateContext<RemissionStateModel>,
{ remission }: actions.ReloadRemission
) {
reload(ctx: StateContext<RemissionStateModel>, { remission }: actions.ReloadRemission) {
ctx.patchState({
remission: {
...remission,
@@ -434,10 +376,7 @@ export class RemissionState {
}
@Action(actions.SetAllOpenExistingRemissions)
setAllOpenExistingRemissions(
ctx: StateContext<RemissionStateModel>,
{ remissionProcesses }: actions.SetAllOpenExistingRemissions
) {
setAllOpenExistingRemissions(ctx: StateContext<RemissionStateModel>, { remissionProcesses }: actions.SetAllOpenExistingRemissions) {
const state = ctx.getState();
const currentExistingRemissions = state.existingRemissions;
const existingRemissions: RemissionExistingOverview = {
@@ -449,10 +388,7 @@ export class RemissionState {
}
@Action(actions.SetAllExistingRemissions)
setAllExistingRemissions(
ctx: StateContext<RemissionStateModel>,
{ remissionProcesses }: actions.SetAllExistingRemissions
) {
setAllExistingRemissions(ctx: StateContext<RemissionStateModel>, { remissionProcesses }: actions.SetAllExistingRemissions) {
const state = ctx.getState();
const currentExistingRemissions = state.existingRemissions;
const existingRemissions: RemissionExistingOverview = {
@@ -472,10 +408,7 @@ export class RemissionState {
}
@Action(actions.SetRemissionFilter)
setRemissionFilter(
ctx: StateContext<RemissionStateModel>,
{ filter }: actions.SetRemissionFilter
) {
setRemissionFilter(ctx: StateContext<RemissionStateModel>, { filter }: actions.SetRemissionFilter) {
const state = ctx.getState();
const remissionState = state.remission;
@@ -496,10 +429,7 @@ export class RemissionState {
}
@Action(actions.RequestUpdateRemissionFilter)
setIsLoadingFilters(
ctx: StateContext<RemissionStateModel>,
{ filter }: actions.RequestUpdateRemissionFilter
) {
setIsLoadingFilters(ctx: StateContext<RemissionStateModel>, { filter }: actions.RequestUpdateRemissionFilter) {
const state = ctx.getState();
const remissionState = state.remission;
@@ -511,10 +441,8 @@ export class RemissionState {
...remissionState.remissionProcess,
filter: {
...remissionState.remissionProcess.filter,
source:
filter.source || remissionState.remissionProcess.filter.source,
target:
filter.target || remissionState.remissionProcess.filter.target,
source: filter.source || remissionState.remissionProcess.filter.source,
target: filter.target || remissionState.remissionProcess.filter.target,
},
},
};
@@ -527,10 +455,7 @@ export class RemissionState {
}
@Action(actions.SetRemissionIsLoading)
setIsLoading(
ctx: StateContext<RemissionStateModel>,
{ isLoading }: actions.SetRemissionIsLoading
) {
setIsLoading(ctx: StateContext<RemissionStateModel>, { isLoading }: actions.SetRemissionIsLoading) {
const state = ctx.getState();
ctx.patchState({
@@ -540,10 +465,7 @@ export class RemissionState {
}
@Action(actions.SetRemissionActiveView)
setActiveView(
ctx: StateContext<RemissionStateModel>,
{ activeView }: actions.SetRemissionActiveView
) {
setActiveView(ctx: StateContext<RemissionStateModel>, { activeView }: actions.SetRemissionActiveView) {
const state = ctx.getState();
const remissionState = state.remission;

View File

@@ -12,22 +12,22 @@ declare global {
}
}
Array.prototype.lengthChecked = function() {
Array.prototype.lengthChecked = function () {
return this && this[0] ? this.length : 0;
};
Array.prototype.hasItems = function() {
Array.prototype.hasItems = function () {
return this && this.length > 0;
};
Boolean.prototype.ifTrue = function(callback) {
Boolean.prototype.ifTrue = function (callback) {
if (this && this.valueOf() === true) {
callback();
return false;
}
};
Boolean.prototype.ifFalse = function(callback) {
Boolean.prototype.ifFalse = function (callback) {
if (this && this.valueOf() === false) {
callback();
return true;

View File

@@ -5,7 +5,7 @@ import { isNullOrUndefined } from 'util';
*/
export function mapToIterable<T>(associativeArray: any, callback?: (param: T, index?: number) => T): T[] {
let index = -1;
return Object.keys(associativeArray).map(t => {
return Object.keys(associativeArray).map((t) => {
if (callback) {
return callback(associativeArray[t], index++);
}
@@ -159,7 +159,7 @@ export function areArraysEqual(value, other) {
}
// Compare two items
const compare = function(item1, item2) {
const compare = function (item1, item2) {
// Get the object type
const itemType = Object.prototype.toString.call(item1);

View File

@@ -1,5 +1,5 @@
import { COUNTRIES } from '../../modules/customer/dropdown-values';
export function getCountryCode(name: string) {
return COUNTRIES.find(t => t.display === name).value;
return COUNTRIES.find((t) => t.display === name).value;
}

View File

@@ -3,47 +3,11 @@ const errorWhiteList: { url: string; codes: number[] }[] = [
{ url: '/isa/userstate', codes: [404] },
{
url: '/availability/',
codes: [
401,
403,
404,
406,
407,
410,
412,
416,
418,
451,
500,
501,
502,
503,
504,
0,
-1,
],
codes: [401, 403, 404, 406, 407, 410, 412, 416, 418, 451, 500, 501, 502, 503, 504, 0, -1],
},
{
url: '/userstate',
codes: [
401,
403,
404,
406,
407,
410,
412,
416,
418,
451,
500,
501,
502,
503,
504,
0,
-1,
],
codes: [401, 403, 404, 406, 407, 410, 412, 416, 418, 451, 500, 501, 502, 503, 504, 0, -1],
},
{ url: '/customer', codes: [400, 409, 500] },
{ url: '/bonuscard', codes: [404] },
@@ -51,89 +15,27 @@ const errorWhiteList: { url: string; codes: number[] }[] = [
{ url: '/store/customer/emailexists', codes: [400, 409, 500] },
{
url: '/receipt/order/',
codes: [
401,
403,
404,
406,
407,
410,
412,
416,
418,
451,
500,
501,
502,
503,
504,
0,
-1,
],
codes: [401, 403, 404, 406, 407, 410, 412, 416, 418, 451, 500, 501, 502, 503, 504, 0, -1],
},
{
url: '/customer/address/validate',
codes: [
401,
403,
404,
406,
407,
410,
412,
416,
418,
451,
500,
501,
502,
503,
504,
0,
-1,
],
codes: [401, 403, 404, 406, 407, 410, 412, 416, 418, 451, 500, 501, 502, 503, 504, 0, -1],
},
{ url: '/5d1e00a230000080a4d72461', codes: [503] }, // test call
{ url: '/customer/online', codes: [400] },
{
url: '/printers',
codes: [
401,
403,
404,
406,
407,
410,
412,
416,
418,
451,
500,
501,
502,
503,
504,
0,
-1,
],
codes: [401, 403, 404, 406, 407, 410, 412, 416, 418, 451, 500, 501, 502, 503, 504, 0, -1],
},
{ url: '/payer', codes: [400] },
{ url: '/shippingaddress', codes: [400] },
{ url: '/inventory', codes: [400] },
];
const errorBlackList: { url: string; codes: number[] }[] = [
{ url: '/order/checkout', codes: [400] },
];
const errorBlackList: { url: string; codes: number[] }[] = [{ url: '/order/checkout', codes: [400] }];
export function isWhiteList(url: string, code: number = -1) {
const whiteListed =
errorWhiteList.findIndex(
(t) => url.includes(t.url) && t.codes.includes(code)
) !== -1;
const blackListed =
errorBlackList.findIndex(
(t) => url.includes(t.url) && t.codes.includes(code)
) !== -1;
const whiteListed = errorWhiteList.findIndex((t) => url.includes(t.url) && t.codes.includes(code)) !== -1;
const blackListed = errorBlackList.findIndex((t) => url.includes(t.url) && t.codes.includes(code)) !== -1;
return whiteListed && !blackListed;
}

View File

@@ -1,6 +1,3 @@
export function toDecimalPlaces(
value: number,
decimalPlaces: number = 2
): string {
export function toDecimalPlaces(value: number, decimalPlaces: number = 2): string {
return Number(value).toFixed(decimalPlaces);
}

View File

@@ -33,9 +33,5 @@ export function getFormatedPublicationDate(publicationDate: Date): string {
}
export function allowedAvailabilityStatusCodes(code: number): boolean {
return (
[2, 32, 256, 1024, 2048, 4096].findIndex(
(allowedCode) => allowedCode === code
) !== -1
);
return [2, 32, 256, 1024, 2048, 4096].findIndex((allowedCode) => allowedCode === code) !== -1;
}

View File

@@ -14,7 +14,6 @@ import { CustomerCardManualEntryComponent } from './components/customer-card-man
import { CustomerCardSearchEmptyModalComponent } from './components/customer-card-search-empty-modal/customer-card-search-empty-modal.component';
import { CustomerCardSearchErrorModalComponent } from './components/customer-card-search-error-modal/customer-card-search-error-modal.component';
@NgModule({
imports: [
ZXingScannerModule,
@@ -28,14 +27,14 @@ import { CustomerCardSearchErrorModalComponent } from './components/customer-car
ButtonModule,
IconModule,
ModalModule,
FormsModule
FormsModule,
],
exports: [
BarcodeSearchComponent,
CustomerCardBarcodeSearchComponent,
CustomerCardManualEntryComponent,
BarcodeScannerModule,
BarcodeScannerComponent
BarcodeScannerComponent,
],
declarations: [
BarcodeSearchComponent,
@@ -43,7 +42,7 @@ import { CustomerCardSearchErrorModalComponent } from './components/customer-car
CustomerCardBarcodeSearchComponent,
CustomerCardManualEntryComponent,
CustomerCardSearchEmptyModalComponent,
CustomerCardSearchErrorModalComponent
]
CustomerCardSearchErrorModalComponent,
],
})
export class BarcodeSearchModule {}

View File

@@ -1,11 +1,4 @@
import {
Component,
EventEmitter,
OnInit,
ViewChild,
OnDestroy,
Output,
} from '@angular/core';
import { Component, EventEmitter, OnInit, ViewChild, OnDestroy, Output } from '@angular/core';
import { BarcodeFormat, Result } from '@zxing/library';
import { ZXingScannerComponent } from '@zxing/ngx-scanner';
import { Subject } from 'rxjs';
@@ -20,12 +13,7 @@ export class BarcodeScannerComponent implements OnInit, OnDestroy {
@Output() scan: EventEmitter<string> = new EventEmitter();
@ViewChild('scanner', { static: true }) scanner: ZXingScannerComponent;
allowedFormats = [
BarcodeFormat.QR_CODE,
BarcodeFormat.EAN_13,
BarcodeFormat.CODE_128,
BarcodeFormat.UPC_A,
];
allowedFormats = [BarcodeFormat.QR_CODE, BarcodeFormat.EAN_13, BarcodeFormat.CODE_128, BarcodeFormat.UPC_A];
enabled = false;
debugMode = true;
code = '';
@@ -36,17 +24,11 @@ export class BarcodeScannerComponent implements OnInit, OnDestroy {
destroy$ = new Subject();
ngOnInit() {
this.scanner.camerasNotFound
.pipe(takeUntil(this.destroy$))
.subscribe(() => (this.hasDevices = false));
this.scanner.scanComplete
.pipe(takeUntil(this.destroy$))
.subscribe((result) => this.scanSuccess(result));
this.scanner.permissionResponse
.pipe(takeUntil(this.destroy$))
.subscribe((perm: boolean) => {
this.hasPermission = perm;
});
this.scanner.camerasNotFound.pipe(takeUntil(this.destroy$)).subscribe(() => (this.hasDevices = false));
this.scanner.scanComplete.pipe(takeUntil(this.destroy$)).subscribe((result) => this.scanSuccess(result));
this.scanner.permissionResponse.pipe(takeUntil(this.destroy$)).subscribe((perm: boolean) => {
this.hasPermission = perm;
});
}
scanSuccess(result: Result) {

View File

@@ -8,7 +8,7 @@ describe('CustomerCardManualEntryComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [CustomerCardManualEntryComponent]
declarations: [CustomerCardManualEntryComponent],
}).compileComponents();
}));

View File

@@ -11,7 +11,7 @@ import { isNullOrUndefined } from 'util';
})
export class CustomerCardManualEntryComponent implements OnInit, AfterViewInit, OnDestroy {
id = 'customer-card-manual-entry-modal';
constructor(private modalService: ModalService) { }
constructor(private modalService: ModalService) {}
focusManager$ = new Subject<number>();
destroy$ = new Subject();
@Output() scanner = new EventEmitter();
@@ -21,7 +21,7 @@ export class CustomerCardManualEntryComponent implements OnInit, AfterViewInit,
get disabled() {
let status = false;
this.code.forEach(entry => {
this.code.forEach((entry) => {
if (isNullOrUndefined(entry) || entry === '' || entry === ' ') {
status = true;
}
@@ -29,10 +29,10 @@ export class CustomerCardManualEntryComponent implements OnInit, AfterViewInit,
return status;
}
ngOnInit() { }
ngOnInit() {}
ngAfterViewInit() {
this.focusManager$.pipe(takeUntil(this.destroy$)).subscribe(codeIndex => {
this.focusManager$.pipe(takeUntil(this.destroy$)).subscribe((codeIndex) => {
document.getElementById('code-' + codeIndex).focus();
});
}

View File

@@ -4,15 +4,14 @@
<div class="modal-wrapper">
<div class="header">Kundenkarte keiner Person zugeordnet</div>
<div class="content">Diese Kundenkarte konnte keiner Person zugeordnet werden. Hier handelt es sich entweder um eine
anonyme Karte oder Ihre Karte wurde noch nicht mit dem Onlinekonto verknüpft. Dies können Sie jederzeit auf
unserer Website nachholen. Dann finden wir Sie beim nächsten mal.
<div class="content">
Diese Kundenkarte konnte keiner Person zugeordnet werden. Hier handelt es sich entweder um eine anonyme Karte oder Ihre Karte wurde
noch nicht mit dem Onlinekonto verknüpft. Dies können Sie jederzeit auf unserer Website nachholen. Dann finden wir Sie beim nächsten
mal.
</div>
<div class="actions">
<app-button [primary]="true"
(action)="closeDialog()">Zur Kundensuche
</app-button>
<app-button [primary]="true" (action)="closeDialog()">Zur Kundensuche </app-button>
</div>
</div>
</app-modal>

View File

@@ -11,8 +11,7 @@ describe('CustomerSearchEmptyModalComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [CommonModule, BarcodeSearchModule, IconModule],
})
.compileComponents();
}).compileComponents();
}));
beforeEach(() => {

View File

@@ -4,14 +4,12 @@ import { ModalService } from '@libs/ui';
@Component({
selector: 'app-customer-card-search-empty-modal',
templateUrl: './customer-card-search-empty-modal.component.html',
styleUrls: ['./customer-card-search-empty-modal.component.scss']
styleUrls: ['./customer-card-search-empty-modal.component.scss'],
})
export class CustomerCardSearchEmptyModalComponent implements OnInit {
id = 'customer-card-search-empty-modal';
constructor(
private modalService: ModalService
) {}
constructor(private modalService: ModalService) {}
ngOnInit() {}

View File

@@ -2,14 +2,12 @@
<lib-icon (click)="closeDialog()" class="close-icon" height="21px" name="close" alt="close"></lib-icon>
<div class="modal-wrapper">
<div class="header">{{title}}</div>
<div class="header">{{ title }}</div>
<div class="content">{{message}}</div>
<div class="content">{{ message }}</div>
<div class="actions">
<app-button [primary]="true"
(action)="closeDialog()">Zur Kundensuche
</app-button>
<app-button [primary]="true" (action)="closeDialog()">Zur Kundensuche </app-button>
</div>
</div>
</app-modal>

View File

@@ -11,9 +11,8 @@ describe('CustomerCardSearchErrorModalComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [CommonModule, BarcodeSearchModule, IconModule]
})
.compileComponents();
imports: [CommonModule, BarcodeSearchModule, IconModule],
}).compileComponents();
}));
beforeEach(() => {

View File

@@ -4,16 +4,14 @@ import { ModalService } from '@libs/ui';
@Component({
selector: 'app-customer-card-search-error-modal',
templateUrl: './customer-card-search-error-modal.component.html',
styleUrls: ['./customer-card-search-error-modal.component.scss']
styleUrls: ['./customer-card-search-error-modal.component.scss'],
})
export class CustomerCardSearchErrorModalComponent implements OnInit {
id = 'customer-card-search-error-modal';
title: string;
message: string;
constructor(
private modalService: ModalService
) {}
constructor(private modalService: ModalService) {}
ngOnInit() {}

View File

@@ -5,4 +5,4 @@
</caption>
<lib-barcode-scanner #scanner (scan)="triggerSearch($event)"></lib-barcode-scanner>
</div>
</div>

View File

@@ -42,7 +42,7 @@ export class CustomerCardBarcodeSearchComponent implements OnInit, OnDestroy, Af
private cdrf: ChangeDetectorRef,
private windowRef: WindowRef,
private errorService: ErrorService
) { }
) {}
ngOnInit() {
this.processes$.pipe(takeUntil(this.destroy$)).subscribe((p: Process[]) => (this.processes = p));

View File

@@ -8,7 +8,7 @@ describe('BranchMainComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [BranchMainComponent]
declarations: [BranchMainComponent],
}).compileComponents();
}));

View File

@@ -8,7 +8,7 @@ describe('ChangeOrderTypeComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ChangeOrderTypeComponent]
declarations: [ChangeOrderTypeComponent],
}).compileComponents();
}));

View File

@@ -32,7 +32,6 @@ import { SearchDropdownComponent } from '@libs/ui/lib/search-dropdown';
import { ItemDTO } from '@swagger/cat';
import { allowedAvailabilityStatusCodes } from '../../../../core/utils/product.util';
export interface ProcessAvailibilityMapper {
branchId: number;
type: CheckoutType;
@@ -144,7 +143,7 @@ export class ChangeOrderTypeComponent implements OnInit, OnDestroy {
private cdr: ChangeDetectorRef,
private branchService: BranchService,
private checkoutService: CheckoutService
) { }
) {}
ngOnInit() {
this.currency = this.book.catalogAvailability.price.value.currency;

Some files were not shown because too many files have changed in this diff Show More