parameters-customization.component.ts 10.1 KB
Newer Older
1
2
3
4
import { Component, OnInit, OnDestroy } from '@angular/core';
import { FormBuilder, FormGroup, Validators, ValidatorFn } from '@angular/forms';
import { TranslateService } from '@ngx-translate/core';
import { DomSanitizer } from '@angular/platform-browser';
5
import { NotificationService } from '@service/notification/notification.service';
6
7
8
import { ScanPipe } from 'ngx-pipes';
import { debounceTime, tap, catchError, exhaustMap } from 'rxjs/operators';
import { HttpClient } from '@angular/common/http';
9
import { of } from 'rxjs';
10

11
declare let tinymce: any;
12
13
14
15
16
17
18
19
20
21
22
23
24
25

@Component({
    selector: 'app-parameters-customization',
    templateUrl: './parameters-customization.component.html',
    styleUrls: ['./parameters-customization.component.scss'],
    providers: [ScanPipe]
})
export class ParametersCustomizationComponent implements OnInit, OnDestroy {
    stepFormGroup: FormGroup;
    readonlyState: boolean = false;

    backgroundList: any[] = [];

    constructor(
26
        public translate: TranslateService,
27
28
29
30
31
32
33
34
35
        private _formBuilder: FormBuilder,
        private notify: NotificationService,
        private sanitizer: DomSanitizer,
        private scanPipe: ScanPipe,
        public http: HttpClient,
    ) {
        const valIdentifier: ValidatorFn[] = [Validators.pattern(/^[a-zA-Z0-9_\-]*$/), Validators.required];

        this.stepFormGroup = this._formBuilder.group({
36
            applicationName: ['', Validators.required],
37
            maarchUrl: ['', Validators.required],
38
39
            loginpage_message: [''],
            homepage_message: [''],
40
            traffic_record_summary_sheet: [''],
41
42
            bodyImage: ['../rest/images?image=loginPage'],
            logo: ['../rest/images?image=logo'],
43
44
        });

45
        this.backgroundList = Array.from({ length: 17 }).map((_, i) => ({
46
47
48
            filename: `${i + 1}.jpg`,
            url: `assets/${i + 1}.jpg`,
        }));
49
50
51
52
53
54
55
    }

    async ngOnInit(): Promise<void> {
        await this.getParameters();
    }

    getParameters() {
56
        return new Promise(() => {
57
58
59
60
            this.http.get('../rest/parameters').pipe(
                tap((data: any) => {
                    this.stepFormGroup.controls['homepage_message'].setValue(data.parameters.filter((item: any) => item.id === 'homepage_message')[0].value);
                    this.stepFormGroup.controls['loginpage_message'].setValue(data.parameters.filter((item: any) => item.id === 'loginpage_message')[0].value);
61
                    this.stepFormGroup.controls['traffic_record_summary_sheet'].setValue(data.parameters.filter((item: any) => item.id === 'traffic_record_summary_sheet')[0].value);
62
63
64
                }),
                exhaustMap(() => this.http.get('../rest/authenticationInformations')),
                tap((data: any) => {
65
                    this.stepFormGroup.controls['applicationName'].setValue(data.applicationName);
66
                    this.stepFormGroup.controls['maarchUrl'].setValue(data.maarchUrl);
67
68
                    setTimeout(() => {

69
                        this.stepFormGroup.controls['applicationName'].valueChanges.pipe(
70
                            debounceTime(1000),
71
                            tap(() => this.saveParameter('applicationName'))
72
73
                        ).subscribe();

74
75
76
77
                        this.stepFormGroup.controls['maarchUrl'].valueChanges.pipe(
                            debounceTime(1000),
                            tap(() => this.saveParameter('maarchUrl'))
                        ).subscribe();
78
79

                        this.stepFormGroup.controls['homepage_message'].valueChanges.pipe(
80
                            debounceTime(100),
81
82
83
84
                            tap(() => this.saveParameter('homepage_message'))
                        ).subscribe();

                        this.stepFormGroup.controls['loginpage_message'].valueChanges.pipe(
85
                            debounceTime(100),
86
87
                            tap(() => this.saveParameter('loginpage_message'))
                        ).subscribe();
88
89

                        this.stepFormGroup.controls['traffic_record_summary_sheet'].valueChanges.pipe(
90
                            debounceTime(100),
91
92
                            tap(() => this.saveParameter('traffic_record_summary_sheet'))
                        ).subscribe();
93
                        this.initMce();
94
                    }, 100);
95
96
97
98
99
100
101
102
103
104
                }),
                catchError((err: any) => {
                    this.notify.handleSoftErrors(err);
                    return of(false);
                })
            ).subscribe();
        });
    }

    initMce(readonly = false) {
105
        const param = {
106
            selector: '#loginpage_message',
107
108
109
            setup: (editor: any) => {
                editor.on('Blur', (e) => {
                    this.stepFormGroup.controls[e.target.id].setValue(tinymce.get(e.target.id).getContent());
110
111
112
                });
            },
            base_url: '../node_modules/tinymce/',
113
            convert_urls: false,
114
            height: '200',
115
116
117
118
119
120
121
            suffix: '.min',
            language: this.translate.instant('lang.langISO').replace('-', '_'),
            language_url: `../node_modules/tinymce-i18n/langs/${this.translate.instant('lang.langISO').replace('-', '_')}.js`,
            menubar: false,
            statusbar: false,
            readonly: readonly,
            plugins: [
122
                'autolink', 'table', 'code'
123
124
125
126
            ],
            external_plugins: {
                'maarch_b64image': '../../src/frontend/plugins/tinymce/maarch_b64image/plugin.min.js'
            },
127
            table_toolbar: '',
128
            table_sizing_mode: 'relative',
129
            table_resize_bars: false,
130
131
            toolbar_sticky: true,
            toolbar_drawer: 'floating',
132
            table_style_by_css: true,
133
            content_style: 'table td { padding: 1px; vertical-align: top; }',
134
            forced_root_block : false,
135
            toolbar: !readonly ? 'undo redo | fontselect fontsizeselect | bold italic underline strikethrough forecolor | table maarch_b64image | \
136
        alignleft aligncenter alignright alignjustify \
137
        bullist numlist outdent indent | removeformat code' : ''
138
139
140
141
142
143
144
        };
        tinymce.init(param);
        param.selector = '#homepage_message';
        tinymce.init(param);
        param.selector = '#traffic_record_summary_sheet';
        param.height = '500';
        tinymce.init(param);
145
146
147
148
149
150
151
152
153
154
155
    }

    uploadTrigger(fileInput: any, mode: string) {
        if (fileInput.target.files && fileInput.target.files[0]) {
            const res = this.canUploadFile(fileInput.target.files[0], mode);
            if (res === true) {
                const reader = new FileReader();

                reader.readAsDataURL(fileInput.target.files[0]);
                reader.onload = (value: any) => {
                    if (mode === 'logo') {
156
157
                        this.stepFormGroup.controls['logo'].setValue(value.target.result);
                        this.saveParameter('logo');
158
159
160
161
                    } else {
                        const img = new Image();
                        img.onload = (imgDim: any) => {
                            if (imgDim.target.width < 1920 || imgDim.target.height < 1080) {
162
                                this.notify.error(this.translate.instant('lang.badImageResolution', {value1: '1920x1080'}));
163
164
165
166
167
                            } else {
                                this.backgroundList.push({
                                    filename: value.target.result,
                                    url: value.target.result,
                                });
168
169
                                this.stepFormGroup.controls['bodyImage'].setValue(value.target.result);
                                this.saveParameter('bodyImage');
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
                            }
                        };
                        img.src = value.target.result;
                    }
                };
            } else {
                this.notify.error(res);
            }
        }
    }

    canUploadFile(file: any, mode: string) {
        const allowedExtension = mode !== 'logo' ? ['image/jpg', 'image/jpeg'] : ['image/svg+xml'];

        if (mode === 'logo') {
            if (file.size > 5000000) {
186
                return this.translate.instant('lang.maxFileSizeExceeded', {value1: '5mo'});
187
            } else if (allowedExtension.indexOf(file.type) === -1) {
188
                return this.translate.instant('lang.onlyExtensionsAllowed', {value1: allowedExtension.join(', ')});
189
190
191
            }
        } else {
            if (file.size > 10000000) {
192
                return this.translate.instant('lang.maxFileSizeExceeded', {value1: '10mo'});
193
            } else if (allowedExtension.indexOf(file.type) === -1) {
194
                return this.translate.instant('lang.onlyExtensionsAllowed', {value1: allowedExtension.join(', ')});
195
196
197
198
199
200
            }
        }
        return true;
    }

    selectBg(content: string) {
201
202
203
        if (!this.stepFormGroup.controls['bodyImage'].disabled) {
            this.stepFormGroup.controls['bodyImage'].setValue(content);
            this.saveParameter('bodyImage');
204
205
206
207
        }
    }

    clickLogoButton(uploadLogo: any) {
208
        if (!this.stepFormGroup.controls['logo'].disabled) {
209
210
211
212
213
            uploadLogo.click();
        }
    }

    saveParameter(parameterId: string) {
214
215
216
        let param = {};
        if (parameterId === 'logo' || parameterId === 'bodyImage') {
            param['image'] = this.stepFormGroup.controls[parameterId].value;
217
218
        } else if (parameterId === 'applicationName' || parameterId === 'maarchUrl') {
            param[parameterId] = this.stepFormGroup.controls[parameterId].value;
219
220
221
222
223
        } else {
            param = {
                param_value_string: this.stepFormGroup.controls[parameterId].value
            };
        }
224
225
226
        this.http.put('../rest/parameters/' + parameterId, param)
            .subscribe(() => {
                this.notify.success(this.translate.instant('lang.parameterUpdated'));
227
228
229
230
231
                if (parameterId === 'logo') {
                    setTimeout(() => {
                        window.location.reload();
                    }, 500);
                }
232
233
234
235
236
237
238
239
240
            }, (err) => {
                this.notify.error(err.error.errors);
            });
    }

    ngOnDestroy(): void {
        tinymce.remove();
    }
}