Project

General

Profile

1
import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
2
import { formErrorRequiredFields, formErrorWasntSaved, formSubmitting, formSuccessUpdatedRepo, loadingRepoError,
3
         loadingRepoMessage, noServiceMessage } from '../../../domain/shared-messages';
4
import { RepositoryService } from '../../../services/repository.service';
5
import { AbstractControl, FormBuilder, FormGroup, Validators } from '@angular/forms';
6
import { Country, Repository, Timezone, Typology } from '../../../domain/typeScriptClasses';
7
import { Description, softwarePlatformDesc, platformNameDesc, officialNameDesc, repoDescriptionDesc, countryDesc,
8
         longtitudeDesc, latitudeDesc, websiteUrlDesc, institutionNameDesc, englishNameDesc, logoUrlDesc, timezoneDesc,
9
         datasourceTypeDesc, adminEmailDesc, lissnDesc, eissnDesc, issnDesc } from '../../../domain/oa-description';
10
import { AuthenticationService } from '../../../services/authentication.service';
11

    
12
@Component ({
13
  selector: 'datasource-update-form',
14
  templateUrl: './datasource-update-form.component.html'
15
})
16

    
17
export class DatasourceUpdateFormComponent implements OnInit {
18

    
19
  errorMessage: string;
20
  successMessage: string;
21
  loadingMessage: string;
22

    
23
  typologies: Typology[] = [];
24
  timezones: Timezone[] = [];
25
  countries: Country[] = [];
26
  datasourceClasses: Map<string, string> = new Map<string, string>();
27
  classCodes: string[] = [];
28

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

    
32
  @Input() selectedRepo: Repository;
33

    
34
  @Input() showButton: boolean;
35

    
36
  repoId: string;
37
  formSubmitted = false;
38
  updateGroup: FormGroup;
39
  readonly updateGroupDefinition = {
40
    softwarePlatform : '',
41
    platformName : '',
42
    officialName :  ['', Validators.required],
43
    issn : '',
44
    eissn : '',
45
    lissn : '',
46
    repoDescription : ['', Validators.required],
47
    country : '',
48
    longtitude : '',
49
    latitude : '',
50
    websiteUrl : [''],
51
    institutionName :  ['', Validators.required],
52
    englishName: ['', Validators.required],
53
    logoUrl: ['', Validators.pattern('^(http:\\/\\/www\\.|https:\\/\\/www\\.|http:\\/\\/|https:\\/\\/)?[a-z0-9]+([\\-\\.]{1}[a-z0-9]+)*\\.[a-z]{2,5}(:[0-9]{1,5})?(\\/.*)?$') ],
54
    timezone: ['', Validators.required],
55
    datasourceType: ['', Validators.required],
56
    adminEmail: ['', [Validators.required, Validators.email]]
57
  };
58

    
59
  softwarePlatformDesc: Description = softwarePlatformDesc;
60
  platformNameDesc: Description = platformNameDesc;
61
  officialNameDesc: Description = officialNameDesc;
62
  issnDesc: Description = issnDesc;
63
  eissnDesc: Description = eissnDesc;
64
  lissnDesc: Description = lissnDesc;
65
  repoDescriptionDesc: Description = repoDescriptionDesc;
66
  countryDesc: Description = countryDesc;
67
  longtitudeDesc: Description = longtitudeDesc;
68
  latitudeDesc: Description = latitudeDesc;
69
  websiteUrlDesc: Description = websiteUrlDesc;
70
  institutionNameDesc: Description = institutionNameDesc;
71
  englishNameDesc: Description = englishNameDesc;
72
  logoUrlDesc: Description = logoUrlDesc;
73
  timezoneDesc: Description = timezoneDesc;
74
  datasourceTypeDesc: Description = datasourceTypeDesc;
75
  adminEmailDesc: Description = adminEmailDesc;
76

    
77
  constructor(
78
    private fb: FormBuilder,
79
    private repoService: RepositoryService,
80
    private authService: AuthenticationService
81
  ) {}
82

    
83
  ngOnInit() {
84
    this.loadForm();
85
  }
86

    
87
  loadForm() {
88
    if (this.selectedRepo) {
89
      this.repoId = this.selectedRepo.id.split('::')[1];
90
      this.loadingMessage = loadingRepoMessage;
91
      this.updateGroup = this.fb.group(this.updateGroupDefinition, {validator: checkPlatform});
92
      this.getDatasourceClasses();
93
    } else {
94
      this.errorMessage = loadingRepoError;
95
    }
96
  }
97

    
98
  setupUpdateForm() {
99
    if (this.selectedRepo) {
100
      console.log(`my datasource type is: ${this.selectedRepo.datasourceType}`);
101

    
102
      this.updateGroup.setValue({
103
        softwarePlatform: this.selectedRepo.typology,
104
        platformName: '',
105
        officialName: this.selectedRepo.officialName,
106
        issn: '',
107
        eissn: '',
108
        lissn: '',
109
        repoDescription: this.selectedRepo.description,
110
        country: this.selectedRepo.countryCode,
111
        longtitude: this.selectedRepo.longitude,
112
        latitude: this.selectedRepo.latitude,
113
        websiteUrl: this.selectedRepo.websiteUrl,
114
        institutionName: this.selectedRepo.organization,
115
        englishName: this.selectedRepo.englishName,
116
        logoUrl: this.selectedRepo.logoUrl,
117
        timezone: this.selectedRepo.timezone,
118
        datasourceType: this.selectedRepo.datasourceClass,
119
        adminEmail: this.selectedRepo.contactEmail
120
      });
121

    
122
      if ( this.selectedRepo.typology === '' || !this.typologies.some(x => x.value === this.selectedRepo.typology) ) {
123
        this.updateGroup.get('softwarePlatform').setValue('');
124
        this.updateGroup.get('platformName').setValue(this.selectedRepo.typology);
125
      }
126

    
127
      // this.updateGroup.get('officialName').disable();
128
      this.updateGroup.get('country').disable();
129
      // this.updateGroup.get('longtitude').disable();
130
      // this.updateGroup.get('latitude').disable();
131
      this.updateGroup.get('websiteUrl').disable();
132
      // this.updateGroup.get('institutionName').disable();
133
      if (this.selectedRepo.datasourceType === 'journal') {
134

    
135
        let ssnToShow = this.selectedRepo.issn.slice(0, 4) + '-' + this.selectedRepo.issn.toString().slice(4);
136
        this.updateGroup.get('issn').setValue(ssnToShow);
137

    
138
        if (this.selectedRepo.eissn.trim().length) {
139
          ssnToShow = this.selectedRepo.eissn.slice(0, 4) + '-' + this.selectedRepo.eissn.toString().slice(4);
140
          this.updateGroup.get('eissn').setValue(ssnToShow);
141
        }
142

    
143
        if (this.selectedRepo.lissn.trim().length) {
144
          ssnToShow = this.selectedRepo.lissn.slice(0, 4) + '-' + this.selectedRepo.lissn.toString().slice(4);
145
          this.updateGroup.get('lissn').setValue(ssnToShow);
146
        }
147

    
148
        this.updateGroup.get('issn').disable();
149
        this.updateGroup.get('eissn').disable();
150
        this.updateGroup.get('lissn').disable();
151
      }
152
      /*this.getDatasourceClasses();*/
153
    }
154
  }
155

    
156
  getDatasourceClasses() {
157
    this.repoService.getDatasourceClasses(this.selectedRepo.datasourceType).subscribe(
158
      classes => this.datasourceClasses = classes,
159
      error => {
160
        this.loadingMessage = '';
161
        this.errorMessage = noServiceMessage;
162
        console.log(error);
163
      },
164
      () => {
165
        for (const key in this.datasourceClasses){
166
          this.classCodes.push(key);
167
        }
168
        this.getCountries();
169
      }
170
    );
171
  }
172

    
173
  getCountries() {
174
    this.repoService.getCountries()
175
      .subscribe(
176
        countries => this.countries = countries.sort( function(a, b) {
177
          if (a.name < b.name) {
178
            return -1;
179
          } else if (a.name > b.name) {
180
            return 1;
181
          } else {
182
            return 0;
183
          }
184
        } ),
185
        error => {
186
          this.loadingMessage = '';
187
          this.errorMessage = noServiceMessage;
188
          console.log(error);
189
        }, () => {
190
          this.getTypologies();
191
        });
192
  }
193

    
194
  getTypologies() {
195
    this.repoService.getTypologies().subscribe(
196
      types => this.typologies = types,
197
      error => {
198
        this.loadingMessage = '';
199
        console.log(error);
200
      },
201
      () => {
202
        this.getTimezones();
203
      }
204
    );
205
  }
206

    
207
  getTimezones() {
208
    this.repoService.getTimezones().subscribe(
209
      zones => this.timezones = zones,
210
      error => {
211
        this.loadingMessage = '';
212
        console.log(error);
213
      },
214
      () => {
215
        this.loadingMessage = '';
216
        this.setupUpdateForm();
217
      }
218
    );
219
  }
220

    
221
  updateRepo() {
222
    this.formSubmitted = true;
223
    this.errorMessage = '';
224
    this.successMessage = '';
225
    window.scroll(1, 1);
226

    
227
    if (this.updateGroup.valid) {
228
      if ( this.selectedRepo.datasourceType !== 'journal' || this.updateGroup.get('issn').value ) {
229
        this.refreshSelectedRepo();
230

    
231
        /*
232
          call the api only if the current page is sources/update
233
          [otherwise the repository will be updated during the registration procedure, after the first interface is saved]
234
        */
235
        if (this.showButton) {
236
          this.loadingMessage = formSubmitting;
237
          this.errorMessage = '';
238
          this.repoService.updateRepository(this.selectedRepo).subscribe(
239
            response => {
240
              if (response) {
241
                this.selectedRepo = response;
242
                console.log(`updateRepository responded: ${JSON.stringify(response)}`);
243
              }
244
            },
245
            error => {
246
              console.log(error);
247
              this.loadingMessage = '';
248
              this.errorMessage = formErrorWasntSaved;
249
            },
250
            () => {
251
              this.loadingMessage = '';
252
              if (!this.selectedRepo) {
253
                this.errorMessage = formErrorWasntSaved;
254
              } else {
255
                this.successMessage = formSuccessUpdatedRepo;
256
              }
257
            }
258
          );
259
        }
260
      } else {
261
        this.errorMessage = formErrorRequiredFields;
262
      }
263
    } else {
264
      this.errorMessage = formErrorRequiredFields;
265
    }
266
  }
267

    
268
  refreshSelectedRepo() {
269
    if (this.updateGroup.get('softwarePlatform').value ) {
270
      this.selectedRepo.typology = this.updateGroup.get('softwarePlatform').value;
271
    } else if (this.updateGroup.get('platformName').value) {
272
      this.selectedRepo.typology = this.updateGroup.get('platformName').value;
273
    }
274
    this.selectedRepo.officialName = this.updateGroup.get('officialName').value;
275
    this.selectedRepo.description = this.updateGroup.get('repoDescription').value;
276
    this.selectedRepo.countryCode = this.updateGroup.get('country').value;
277
    this.selectedRepo.countryName = this.countries.filter(x => x.code === this.updateGroup.get('country').value)[0].name;
278
    this.selectedRepo.longitude = this.updateGroup.get('longtitude').value;
279
    this.selectedRepo.latitude = this.updateGroup.get('latitude').value;
280
    this.selectedRepo.websiteUrl = this.updateGroup.get('websiteUrl').value;
281
    this.selectedRepo.organization = this.updateGroup.get('institutionName').value;
282
    this.selectedRepo.englishName = this.updateGroup.get('englishName').value;
283
    this.selectedRepo.logoUrl = this.updateGroup.get('logoUrl').value;
284
    this.selectedRepo.timezone = this.updateGroup.get('timezone').value;
285
    this.selectedRepo.datasourceClass = this.updateGroup.get('datasourceType').value;
286
    this.selectedRepo.contactEmail = this.updateGroup.get('adminEmail').value;
287
    if (this.selectedRepo.datasourceType === 'journal') {
288
      let ssnParts = this.updateGroup.get('issn').value.split('-');
289
      let correctSSN = ssnParts[0] + ssnParts[1];
290
      this.selectedRepo.issn = correctSSN;
291
      if ( this.updateGroup.get('eissn').value ) {
292
        ssnParts = this.updateGroup.get('eissn').value.split('-');
293
        correctSSN = ssnParts[0] + ssnParts[1];
294
        this.selectedRepo.eissn = correctSSN;
295
      }
296
      if ( this.updateGroup.get('lissn').value ) {
297
        ssnParts = this.updateGroup.get('lissn').value.split('-');
298
        correctSSN = ssnParts[0] + ssnParts[1];
299
        this.selectedRepo.lissn = correctSSN;
300
      }
301
    }
302
    if (!this.showButton) {
303
      this.selectedRepo.registeredBy = this.authService.getUserEmail();
304
      this.selectedRepo.registered = true;
305
      this.selectedRepo.registrationDate = new Date(Date.now()); // NOT NEEDED ??
306
      this.emittedInfo.emit(this.selectedRepo);
307
    }
308
  }
309

    
310
}
311

    
312
export function checkPlatform(c: AbstractControl) {
313
  if ( c.get('softwarePlatform').value || c.get('platformName').value ) {
314
    return null;
315
  }
316
  return 'invalid';
317
}
(8-8/8)