Project

General

Profile

1
import { Component, EventEmitter, Input, OnInit, Output, ViewChild } from '@angular/core';
2
import {
3
  formErrorRequiredFields,
4
  formErrorWasntSaved,
5
  formSubmitting,
6
  formSuccessUpdatedRepo, loadingRepoError, loadingRepoMessage,
7
  noServiceMessage
8
} from '../../../domain/shared-messages';
9
import { RepositoryService } from "../../../services/repository.service";
10
import { AbstractControl, FormBuilder, FormGroup, Validators } from '@angular/forms';
11
import { Country, Repository, Timezone, Typology } from '../../../domain/typeScriptClasses';
12
import {
13
  Description,
14
  softwarePlatformDesc,
15
  platformNameDesc,
16
  officialNameDesc,
17
  repoDescriptionDesc,
18
  countryDesc,
19
  longtitudeDesc,
20
  latitudeDesc,
21
  websiteUrlDesc,
22
  institutionNameDesc,
23
  englishNameDesc,
24
  logoUrlDesc,
25
  timezoneDesc,
26
  datasourceTypeDesc,
27
  journalTypeDesc,
28
  aggregatorTypeDesc,
29
  adminEmailDesc, lissnDesc, eissnDesc, issnDesc
30
} from '../../../domain/oa-description';
31
import { ConfirmationDialogComponent } from '../../../shared/reusablecomponents/confirmation-dialog.component';
32
import {AuthenticationService} from "../../../services/authentication.service";
33

    
34
@Component ({
35
  selector: 'datasource-update-form',
36
  templateUrl: './datasource-update-form.component.html'
37
})
38

    
39
export class DatasourceUpdateFormComponent implements OnInit {
40

    
41
  errorMessage: string;
42
  successMessage: string;
43
  loadingMessage: string;
44

    
45
  typologies: Typology[] = [];
46
  timezones: Timezone[] = [];
47
  countries: Country[] = [];
48
  datasourceClasses: Map<string,string> = new Map<string,string>();
49
  classCodes: string[] = [];
50

    
51
  isModalShown: boolean;
52
  @ViewChild('updateLogoUrlModal')
53
  public updateLogoUrlModal: ConfirmationDialogComponent;
54

    
55
  /* in sources/update emits the new logUrl */
56
  @Output() emittedUrl: EventEmitter<string> = new EventEmitter();
57

    
58
  /*  in sources/register (of literature or data repository) emits the updated repository */
59
  @Output() emittedInfo: EventEmitter<Repository> = new EventEmitter();
60

    
61
  @Input() selectedRepo: Repository;
62

    
63
  @Input() showButton: boolean;
64

    
65
  updateGroup: FormGroup;
66
  readonly updateGroupDefinition = {
67
    softwarePlatform : '',
68
    platformName : '',
69
    officialName : ['', Validators.required],
70
    issn : ['', [Validators.pattern('^\\d\\d\\d\\d[-]\\d\\d\\d\\d$')] ],
71
    eissn : ['', Validators.pattern('^\\d\\d\\d\\d[-]\\d\\d\\d\\d$') ],
72
    lissn : ['', Validators.pattern('^\\d\\d\\d\\d[-]\\d\\d\\d\\d$') ],
73
    repoDescription : ['', Validators.required],
74
    country : ['', Validators.required],
75
    longtitude : ['', [Validators.required, Validators.min(-180), Validators.max(180)] ],
76
    latitude : ['', [Validators.required, Validators.min(-90), Validators.max(90)] ],
77
    websiteUrl : ['', [Validators.required] ],
78
    institutionName : ['', Validators.required],
79
    englishName: ['', Validators.required],
80
    logoUrl: [''],
81
    timezone: ['', Validators.required],
82
    datasourceType: ['', Validators.required],
83
    adminEmail: ['', [Validators.required, Validators.email]]
84
  };
85

    
86
  softwarePlatformDesc : Description = softwarePlatformDesc;
87
  platformNameDesc : Description = platformNameDesc;
88
  officialNameDesc : Description = officialNameDesc;
89
  issnDesc : Description = issnDesc;
90
  eissnDesc : Description = eissnDesc;
91
  lissnDesc : Description = lissnDesc;
92
  repoDescriptionDesc : Description = repoDescriptionDesc;
93
  countryDesc : Description = countryDesc;
94
  longtitudeDesc : Description = longtitudeDesc;
95
  latitudeDesc : Description = latitudeDesc;
96
  websiteUrlDesc : Description = websiteUrlDesc;
97
  institutionNameDesc : Description = institutionNameDesc;
98
  englishNameDesc : Description = englishNameDesc;
99
  logoUrlDesc : Description = logoUrlDesc;
100
  timezoneDesc : Description = timezoneDesc;
101
  datasourceTypeDesc : Description;
102
  adminEmailDesc : Description = adminEmailDesc;
103

    
104
  constructor(
105
    private fb: FormBuilder,
106
    private repoService: RepositoryService,
107
    private authService: AuthenticationService
108
  ) {}
109

    
110
  ngOnInit(){
111
    this.loadForm();
112
  }
113

    
114
  loadForm() {
115
    if (this.selectedRepo) {
116
      this.loadingMessage = loadingRepoMessage;
117
      this.updateGroup = this.fb.group(this.updateGroupDefinition, {validator: checkPlatform});
118
      this.setupUpdateForm();
119
      //this.getDatasourceClasses();
120
      //this.getCountries();
121
      this.getTypologies();
122
      this.getTimezones();
123
    } else {
124
      this.errorMessage = loadingRepoError;
125
    }
126
  }
127

    
128
  setupUpdateForm(){
129
    if (this.selectedRepo) {
130
      if (this.selectedRepo.datasourceType == 'journal') {
131
        this.datasourceTypeDesc = journalTypeDesc;
132
      } else if (this.selectedRepo.datasourceType == 'aggregator') {
133
        this.datasourceTypeDesc = aggregatorTypeDesc;
134
      } else {
135
        this.datasourceTypeDesc = datasourceTypeDesc;
136
      }
137
      this.updateGroup.setValue({
138
        softwarePlatform: this.selectedRepo.typology,
139
        platformName: '',
140
        officialName: this.selectedRepo.officialName,
141
        issn: '',
142
        eissn: '',
143
        lissn: '',
144
        repoDescription: this.selectedRepo.description,
145
        country: this.selectedRepo.countryCode,
146
        longtitude: this.selectedRepo.longitude,
147
        latitude: this.selectedRepo.latitude,
148
        websiteUrl: this.selectedRepo.websiteUrl,
149
        institutionName: this.selectedRepo.organization,
150
        englishName: this.selectedRepo.englishName,
151
        logoUrl: this.selectedRepo.logoUrl,
152
        timezone: this.selectedRepo.timezone,
153
        datasourceType: this.selectedRepo.datasourceClass,
154
        adminEmail: this.selectedRepo.contactEmail
155
      });
156
      if ( this.typologies.filter(x => x.value == this.updateGroup.get('softwarePlatform').value) == [] ) {
157
        this.updateGroup.get('softwarePlatform').setValue('');
158
        this.updateGroup.get('platformName').setValue(this.selectedRepo.typology);
159
      }
160
      this.updateGroup.get('officialName').disable();
161
      this.updateGroup.get('country').disable();
162
      this.updateGroup.get('longtitude').disable(); // MAYBE NOT DISABLED
163
      this.updateGroup.get('latitude').disable();   // MAYBE NOT DISABLED
164
      this.updateGroup.get('websiteUrl').disable();
165
      this.updateGroup.get('institutionName').disable();
166
      if (this.selectedRepo.datasourceType == 'journal') {
167
        let ssnToShow = this.selectedRepo.issn.slice(0, 4)+ '-' + this.selectedRepo.issn.toString().slice(4);
168
        this.updateGroup.get('issn').setValue(ssnToShow);
169
        if (this.selectedRepo.eissn) {
170
          ssnToShow = this.selectedRepo.eissn.slice(0, 4)+ '-' + this.selectedRepo.eissn.toString().slice(4);
171
          this.updateGroup.get('eissn').setValue(ssnToShow);
172
        }
173
        if (this.selectedRepo.eissn) {
174
          ssnToShow = this.selectedRepo.lissn.slice(0, 4)+ '-' + this.selectedRepo.lissn.toString().slice(4);
175
          this.updateGroup.get('lissn').setValue(ssnToShow);
176
        }
177
        this.updateGroup.get('issn').disable();
178
        this.updateGroup.get('eissn').disable();
179
        this.updateGroup.get('lissn').disable();
180
      }
181
      this.getDatasourceClasses();
182
    }
183
  }
184

    
185
  getDatasourceClasses() {
186
    this.repoService.getDatasourceClasses(this.selectedRepo.datasourceType).subscribe(
187
      classes => this.datasourceClasses = classes,
188
      error => {
189
        this.loadingMessage = '';
190
        this.errorMessage = noServiceMessage;
191
        console.log(error);
192
      },
193
      () => {
194
        for (let key in this.datasourceClasses){
195
          this.classCodes.push(key);
196
        }
197
        this.getCountries();
198
      }
199
    );
200
  }
201

    
202
  getCountries(){
203
    this.repoService.getCountries()
204
      .subscribe(
205
        countries => this.countries = countries.sort( function(a,b){
206
          if(a.name<b.name){
207
            return -1;
208
          } else if(a.name>b.name){
209
            return 1;
210
          } else {
211
            return 0;
212
          }
213
        } ),
214
        error => {
215
          this.loadingMessage = '';
216
          this.errorMessage = noServiceMessage;
217
          console.log(error);
218
        }, () => {
219
          this.getTypologies();
220
        });
221
  }
222

    
223
  getTypologies() {
224
    this.repoService.getTypologies().subscribe(
225
      types => this.typologies = types,
226
      error => {
227
        this.loadingMessage = '';
228
        console.log(error);
229
      },
230
      () => this.getTimezones()
231
    );
232
  }
233

    
234
  getTimezones() {
235
    this.repoService.getTimezones().subscribe(
236
      zones => this.timezones = zones,
237
      error => {
238
        this.loadingMessage = '';
239
        console.log(error);
240
      },
241
      () => {
242
        this.loadingMessage = '';
243
      }
244
    );
245
  }
246

    
247
  updateRepo() {
248
    this.errorMessage = '';
249
    this.successMessage = '';
250

    
251
    if (this.updateGroup.valid) {
252
      if ( this.selectedRepo.datasourceType != 'journal' || this.updateGroup.get('issn').value ) {
253
        this.refreshSelectedRepo();
254
        this.loadingMessage = formSubmitting;
255
        this.errorMessage = '';
256
        this.repoService.updateRepository(this.selectedRepo).subscribe(
257
          response => {
258
            if(response) {
259
              this.selectedRepo = response;
260
              console.log(`updateRepository responded: ${JSON.stringify(response)}`);
261
              this.emittedInfo.emit(response);
262
            }
263
          },
264
          error => {
265
            console.log(error);
266
            this.loadingMessage = '';
267
            this.errorMessage = formErrorWasntSaved;
268
          },
269
          () => {
270
            this.loadingMessage = '';
271
            if (!this.selectedRepo) {
272
              this.errorMessage = formErrorWasntSaved;
273
            } else {
274
              this.successMessage = formSuccessUpdatedRepo;
275
            }
276
          }
277
        );
278
      } else {
279
        this.errorMessage = formErrorRequiredFields;
280
      }
281
    } else {
282
      this.errorMessage = formErrorRequiredFields;
283
    }
284
  }
285

    
286
  refreshSelectedRepo() {
287
    if (this.updateGroup.get('platformName').value.trim() ) {
288
      this.selectedRepo.typology = this.updateGroup.get('platformName').value;
289
    } else if (this.updateGroup.get('softwarePlatform').value){
290
      this.selectedRepo.typology = this.updateGroup.get('softwarePlatform').value;
291
    }
292
    this.selectedRepo.officialName = this.updateGroup.get('officialName').value;
293
    this.selectedRepo.description = this.updateGroup.get('repoDescription').value;
294
    this.selectedRepo.countryCode = this.updateGroup.get('country').value;
295
    this.selectedRepo.countryName = this.countries.filter(x => x.code == this.updateGroup.get('country').value)[0].name;
296
    this.selectedRepo.longitude = this.updateGroup.get('longtitude').value;
297
    this.selectedRepo.latitude = this.updateGroup.get('latitude').value;
298
    this.selectedRepo.websiteUrl = this.updateGroup.get('websiteUrl').value;
299
    this.selectedRepo.organization = this.updateGroup.get('institutionName').value;
300
    this.selectedRepo.englishName = this.updateGroup.get('englishName').value;
301
    this.selectedRepo.logoUrl = this.updateGroup.get('logoUrl').value;
302
    this.selectedRepo.timezone = this.updateGroup.get('timezone').value;
303
    this.selectedRepo.datasourceClass = this.updateGroup.get('datasourceType').value;
304
    this.selectedRepo.contactEmail = this.updateGroup.get('adminEmail').value;
305
    if (this.selectedRepo.datasourceType == 'journal') {
306
      let ssnParts = this.updateGroup.get('issn').value.split('-');
307
      let correctSSN = ssnParts[0]+ssnParts[1];
308
      this.selectedRepo.issn = correctSSN;
309
      if ( this.updateGroup.get('eissn').value ) {
310
        ssnParts = this.updateGroup.get('eissn').value.split('-');
311
        correctSSN = ssnParts[0]+ssnParts[1];
312
        this.selectedRepo.eissn = correctSSN;
313
      }
314
      if ( this.updateGroup.get('lissn').value ) {
315
        ssnParts = this.updateGroup.get('lissn').value.split('-');
316
        correctSSN = ssnParts[0]+ssnParts[1];
317
        this.selectedRepo.lissn = correctSSN;
318
      }
319
    }
320
    if (!this.showButton) {
321
      this.selectedRepo.registeredBy = this.authService.getUserEmail();
322
      this.selectedRepo.registered = true;
323
      /*this.selectedRepo.registrationDate = new Date(Date.now());*/ //NOT NEEDED
324
    }
325
  }
326

    
327
  changeLogoUrl(logoUrl: string) {
328
    this.updateGroup.get('logoUrl').setValue(logoUrl);
329
  }
330

    
331
  updateLogoUrl(logoUrl: string){
332
    this.updateLogoUrlModal.ids = [logoUrl];
333
    this.updateLogoUrlModal.showModal();
334
  }
335

    
336
  updatedLogoUrl(event: any) {
337
    this.emittedUrl.emit(this.updateGroup.get('logoUrl').value);
338
  }
339

    
340
}
341

    
342
export function checkPlatform(c: AbstractControl) {
343
  if ( c.get('softwarePlatform').value || c.get('platformName').value )
344
    return null;
345
  return 'invalid';
346
}
(6-6/6)