Project

General

Profile

1
import { Component, EventEmitter, Input, OnInit, Output } 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
  adminEmailDesc, lissnDesc, eissnDesc, issnDesc
28
} from '../../../domain/oa-description';
29
import {AuthenticationService} from "../../../services/authentication.service";
30

    
31
@Component ({
32
  selector: 'datasource-update-form',
33
  templateUrl: './datasource-update-form.component.html'
34
})
35

    
36
export class DatasourceUpdateFormComponent implements OnInit {
37

    
38
  errorMessage: string;
39
  successMessage: string;
40
  loadingMessage: string;
41

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

    
48
  /*  in sources/register (in literature or data mode) the updated repository is emitted */
49
  @Output() emittedInfo: EventEmitter<Repository> = new EventEmitter();
50

    
51
  @Input() selectedRepo: Repository;
52

    
53
  @Input() showButton: boolean;
54

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

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

    
95
  constructor(
96
    private fb: FormBuilder,
97
    private repoService: RepositoryService,
98
    private authService: AuthenticationService
99
  ) {}
100

    
101
  ngOnInit(){
102
    this.loadForm();
103
  }
104

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

    
115
  setupUpdateForm() {
116
    if (this.selectedRepo) {
117
      console.log(`my datasource type is: ${this.selectedRepo.datasourceType}`);
118

    
119
      this.updateGroup.setValue({
120
        softwarePlatform: this.selectedRepo.typology,
121
        platformName: '',
122
        officialName: this.selectedRepo.officialName,
123
        issn: '',
124
        eissn: '',
125
        lissn: '',
126
        repoDescription: this.selectedRepo.description,
127
        country: this.selectedRepo.countryCode,
128
        longtitude: this.selectedRepo.longitude,
129
        latitude: this.selectedRepo.latitude,
130
        websiteUrl: this.selectedRepo.websiteUrl,
131
        institutionName: this.selectedRepo.organization,
132
        englishName: this.selectedRepo.englishName,
133
        logoUrl: this.selectedRepo.logoUrl,
134
        timezone: this.selectedRepo.timezone,
135
        datasourceType: this.selectedRepo.datasourceClass,
136
        adminEmail: this.selectedRepo.contactEmail
137
      });
138

    
139
      if ( this.selectedRepo.typology === '' || !this.typologies.some(x => x.value == this.selectedRepo.typology) ) {
140
        this.updateGroup.get('softwarePlatform').setValue('');
141
        this.updateGroup.get('platformName').setValue(this.selectedRepo.typology);
142
      }
143

    
144
      // this.updateGroup.get('officialName').disable();
145
      this.updateGroup.get('country').disable();
146
      // this.updateGroup.get('longtitude').disable();
147
      // this.updateGroup.get('latitude').disable();
148
      this.updateGroup.get('websiteUrl').disable();
149
      //this.updateGroup.get('institutionName').disable();
150
      if (this.selectedRepo.datasourceType == 'journal') {
151

    
152
        let ssnToShow = this.selectedRepo.issn.slice(0, 4)+ '-' + this.selectedRepo.issn.toString().slice(4);
153
        this.updateGroup.get('issn').setValue(ssnToShow);
154

    
155
        if (this.selectedRepo.eissn.trim().length) {
156
          ssnToShow = this.selectedRepo.eissn.slice(0, 4)+ '-' + this.selectedRepo.eissn.toString().slice(4);
157
          this.updateGroup.get('eissn').setValue(ssnToShow);
158
        }
159

    
160
        if (this.selectedRepo.lissn.trim().length) {
161
          ssnToShow = this.selectedRepo.lissn.slice(0, 4)+ '-' + this.selectedRepo.lissn.toString().slice(4);
162
          this.updateGroup.get('lissn').setValue(ssnToShow);
163
        }
164

    
165
        this.updateGroup.get('issn').disable();
166
        this.updateGroup.get('eissn').disable();
167
        this.updateGroup.get('lissn').disable();
168
      }
169
      /*this.getDatasourceClasses();*/
170
    }
171
  }
172

    
173
  getDatasourceClasses() {
174
    this.repoService.getDatasourceClasses(this.selectedRepo.datasourceType).subscribe(
175
      classes => this.datasourceClasses = classes,
176
      error => {
177
        this.loadingMessage = '';
178
        this.errorMessage = noServiceMessage;
179
        console.log(error);
180
      },
181
      () => {
182
        for (let key in this.datasourceClasses){
183
          this.classCodes.push(key);
184
        }
185
        this.getCountries();
186
      }
187
    );
188
  }
189

    
190
  getCountries(){
191
    this.repoService.getCountries()
192
      .subscribe(
193
        countries => this.countries = countries.sort( function(a,b){
194
          if(a.name<b.name){
195
            return -1;
196
          } else if(a.name>b.name){
197
            return 1;
198
          } else {
199
            return 0;
200
          }
201
        } ),
202
        error => {
203
          this.loadingMessage = '';
204
          this.errorMessage = noServiceMessage;
205
          console.log(error);
206
        }, () => {
207
          this.getTypologies();
208
        });
209
  }
210

    
211
  getTypologies() {
212
    this.repoService.getTypologies().subscribe(
213
      types => this.typologies = types,
214
      error => {
215
        this.loadingMessage = '';
216
        console.log(error);
217
      },
218
      () => {
219
        this.getTimezones();
220
      }
221
    );
222
  }
223

    
224
  getTimezones() {
225
    this.repoService.getTimezones().subscribe(
226
      zones => this.timezones = zones,
227
      error => {
228
        this.loadingMessage = '';
229
        console.log(error);
230
      },
231
      () => {
232
        this.loadingMessage = '';
233
        this.setupUpdateForm();
234
      }
235
    );
236
  }
237

    
238
  updateRepo() {
239
    this.formSubmitted = true;
240
    this.errorMessage = '';
241
    this.successMessage = '';
242

    
243
    if (this.updateGroup.valid) {
244
      if ( this.selectedRepo.datasourceType != 'journal' || this.updateGroup.get('issn').value ) {
245
        this.refreshSelectedRepo();
246

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

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

    
326
}
327

    
328
export function checkPlatform(c: AbstractControl) {
329
  if ( c.get('softwarePlatform').value || c.get('platformName').value )
330
    return null;
331
  return 'invalid';
332
}
(6-6/6)