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

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

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

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

    
106
  loadForm() {
107
    if (this.selectedRepo) {
108
      this.repoId = this.selectedRepo.id.split('::')[1];
109
      this.loadingMessage = loadingRepoMessage;
110
      this.updateGroup = this.fb.group(this.updateGroupDefinition, {validator: checkPlatform});
111
      this.getDatasourceClasses();
112
    } else {
113
      this.errorMessage = loadingRepoError;
114
    }
115
  }
116

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
249
        /*
250
          call the api only if the current page is sources/update
251
          [otherwise the repository will be updated during the registration procedure, after the first interface is saved]
252
        */
253
        if (this.showButton) {
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
              }
262
            },
263
            error => {
264
              console.log(error);
265
              this.loadingMessage = '';
266
              this.errorMessage = formErrorWasntSaved;
267
            },
268
            () => {
269
              this.loadingMessage = '';
270
              if (!this.selectedRepo) {
271
                this.errorMessage = formErrorWasntSaved;
272
              } else {
273
                this.successMessage = formSuccessUpdatedRepo;
274
              }
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('softwarePlatform').value ) {
288
      this.selectedRepo.typology = this.updateGroup.get('softwarePlatform').value;
289
    } else if (this.updateGroup.get('platformName').value) {
290
      this.selectedRepo.typology = this.updateGroup.get('platformName').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
      this.emittedInfo.emit(this.selectedRepo);
325
    }
326
  }
327

    
328
}
329

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