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
  /*  in sources/register (in literature or data mode) the updated repository is emitted */
52
  @Output() emittedInfo: EventEmitter<Repository> = new EventEmitter();
53

    
54
  @Input() selectedRepo: Repository;
55

    
56
  @Input() showButton: boolean;
57

    
58
  formSubmitted:boolean = false;
59
  updateGroup: FormGroup;
60
  readonly updateGroupDefinition = {
61
    softwarePlatform : '',
62
    platformName : '',
63
    officialName : '',
64
    issn : '',
65
    eissn : '',
66
    lissn : '',
67
    repoDescription : ['', Validators.required],
68
    country : '',
69
    longtitude : '',
70
    latitude : '',
71
    websiteUrl : [''],
72
    institutionName : [''],
73
    englishName: ['', Validators.required],
74
    logoUrl: ['', Validators.pattern('^(http:\\/\\/www\\.|https:\\/\\/www\\.|http:\\/\\/|https:\\/\\/)?[a-z0-9]+([\\-\\.]{1}[a-z0-9]+)*\\.[a-z]{2,5}(:[0-9]{1,5})?(\\/.*)?$') ],
75
    timezone: ['', Validators.required],
76
    datasourceType: ['', Validators.required],
77
    adminEmail: ['', [Validators.required, Validators.email]]
78
  };
79

    
80
  softwarePlatformDesc : Description = softwarePlatformDesc;
81
  platformNameDesc : Description = platformNameDesc;
82
  officialNameDesc : Description = officialNameDesc;
83
  issnDesc : Description = issnDesc;
84
  eissnDesc : Description = eissnDesc;
85
  lissnDesc : Description = lissnDesc;
86
  repoDescriptionDesc : Description = repoDescriptionDesc;
87
  countryDesc : Description = countryDesc;
88
  longtitudeDesc : Description = longtitudeDesc;
89
  latitudeDesc : Description = latitudeDesc;
90
  websiteUrlDesc : Description = websiteUrlDesc;
91
  institutionNameDesc : Description = institutionNameDesc;
92
  englishNameDesc : Description = englishNameDesc;
93
  logoUrlDesc : Description = logoUrlDesc;
94
  timezoneDesc : Description = timezoneDesc;
95
  datasourceTypeDesc : Description = datasourceTypeDesc;
96
  adminEmailDesc : Description = adminEmailDesc;
97

    
98
  constructor(
99
    private fb: FormBuilder,
100
    private repoService: RepositoryService,
101
    private authService: AuthenticationService
102
  ) {}
103

    
104
  ngOnInit(){
105
    this.loadForm();
106
  }
107

    
108
  loadForm() {
109
    if (this.selectedRepo) {
110
      this.loadingMessage = loadingRepoMessage;
111
      this.updateGroup = this.fb.group(this.updateGroupDefinition, {validator: checkPlatform});
112
      this.getDatasourceClasses();
113
    } else {
114
      this.errorMessage = loadingRepoError;
115
    }
116
  }
117

    
118
  setupUpdateForm() {
119
    if (this.selectedRepo) {
120
      console.log(`my datasource type is: ${this.selectedRepo.datasourceType}`);
121
      /*if (this.selectedRepo.datasourceType == 'journal') {
122
        this.datasourceTypeDesc = journalTypeDesc;
123
      } else if (this.selectedRepo.datasourceType == 'aggregator') {
124
        this.datasourceTypeDesc = aggregatorTypeDesc;
125
      } else {
126
        this.datasourceTypeDesc = datasourceTypeDesc;
127
      }*/
128
      this.updateGroup.setValue({
129
        softwarePlatform: this.selectedRepo.typology,
130
        platformName: '',
131
        officialName: this.selectedRepo.officialName,
132
        issn: '',
133
        eissn: '',
134
        lissn: '',
135
        repoDescription: this.selectedRepo.description,
136
        country: this.selectedRepo.countryCode,
137
        longtitude: this.selectedRepo.longitude,
138
        latitude: this.selectedRepo.latitude,
139
        websiteUrl: this.selectedRepo.websiteUrl,
140
        institutionName: this.selectedRepo.organization,
141
        englishName: this.selectedRepo.englishName,
142
        logoUrl: this.selectedRepo.logoUrl,
143
        timezone: this.selectedRepo.timezone,
144
        datasourceType: this.selectedRepo.datasourceClass,
145
        adminEmail: this.selectedRepo.contactEmail
146
      });
147

    
148
      if ( this.selectedRepo.typology === '' || !this.typologies.some(x => x.value == this.selectedRepo.typology) ) {
149
        this.updateGroup.get('softwarePlatform').setValue('');
150
        this.updateGroup.get('platformName').setValue(this.selectedRepo.typology);
151
      }
152

    
153
      this.updateGroup.get('officialName').disable();
154
      this.updateGroup.get('country').disable();
155
      this.updateGroup.get('longtitude').disable(); // MAYBE NOT DISABLED
156
      this.updateGroup.get('latitude').disable();   // MAYBE NOT DISABLED
157
      this.updateGroup.get('websiteUrl').disable();
158
      this.updateGroup.get('institutionName').disable();
159
      if (this.selectedRepo.datasourceType == 'journal') {
160

    
161
        let ssnToShow = this.selectedRepo.issn.slice(0, 4)+ '-' + this.selectedRepo.issn.toString().slice(4);
162
        this.updateGroup.get('issn').setValue(ssnToShow);
163

    
164
        if (this.selectedRepo.eissn.trim().length) {
165
          ssnToShow = this.selectedRepo.eissn.slice(0, 4)+ '-' + this.selectedRepo.eissn.toString().slice(4);
166
          this.updateGroup.get('eissn').setValue(ssnToShow);
167
        }
168

    
169
        if (this.selectedRepo.lissn.trim().length) {
170
          ssnToShow = this.selectedRepo.lissn.slice(0, 4)+ '-' + this.selectedRepo.lissn.toString().slice(4);
171
          this.updateGroup.get('lissn').setValue(ssnToShow);
172
        }
173

    
174
        this.updateGroup.get('issn').disable();
175
        this.updateGroup.get('eissn').disable();
176
        this.updateGroup.get('lissn').disable();
177
      }
178
      /*this.getDatasourceClasses();*/
179
    }
180
  }
181

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

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

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

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

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

    
252
    if (this.updateGroup.valid) {
253
      if ( this.selectedRepo.datasourceType != 'journal' || this.updateGroup.get('issn').value ) {
254
        this.refreshSelectedRepo();
255

    
256
        /*
257
          call the api only if the current page is sources/update
258
          [otherwise the repository will be updated during the registration procedure, after the first interface is saved]
259
        */
260
        if (this.showButton) {
261
          this.loadingMessage = formSubmitting;
262
          this.errorMessage = '';
263
          this.repoService.updateRepository(this.selectedRepo).subscribe(
264
            response => {
265
              if (response) {
266
                this.selectedRepo = response;
267
                console.log(`updateRepository responded: ${JSON.stringify(response)}`);
268
              }
269
            },
270
            error => {
271
              console.log(error);
272
              this.loadingMessage = '';
273
              this.errorMessage = formErrorWasntSaved;
274
            },
275
            () => {
276
              this.loadingMessage = '';
277
              if (!this.selectedRepo) {
278
                this.errorMessage = formErrorWasntSaved;
279
              } else {
280
                this.successMessage = formSuccessUpdatedRepo;
281
              }
282
            }
283
          );
284
        }
285
      } else {
286
        this.errorMessage = formErrorRequiredFields;
287
      }
288
    } else {
289
      this.errorMessage = formErrorRequiredFields;
290
    }
291
  }
292

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

    
335
}
336

    
337
export function checkPlatform(c: AbstractControl) {
338
  if ( c.get('softwarePlatform').value || c.get('platformName').value )
339
    return null;
340
  return 'invalid';
341
}
(6-6/6)