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
import {SharedService} from '../../../services/shared.service';
12

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

    
18
export class DatasourceUpdateFormComponent implements OnInit {
19

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

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

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

    
33
  @Input() selectedRepo: Repository;
34

    
35
  @Input() mode: string;
36

    
37
  @Input() showButton: boolean;
38

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

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

    
80
  constructor(
81
    private fb: FormBuilder,
82
    private repoService: RepositoryService,
83
    private sharedService: SharedService,
84
    private authService: AuthenticationService
85
  ) {}
86

    
87
  ngOnInit() {
88
    this.loadForm();
89
  }
90

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

    
102
  setupUpdateForm() {
103
    if (this.selectedRepo) {
104

    
105
      this.updateGroup.setValue({
106
        softwarePlatform: this.selectedRepo.platform,
107
        platformName: '',
108
        officialName: this.selectedRepo.officialname,
109
        issn: '',
110
        eissn: '',
111
        lissn: '',
112
        repoDescription: this.selectedRepo.description,
113
        country: this.selectedRepo.organizations[0].country, // countryCode
114
        longtitude: this.selectedRepo.longitude,
115
        latitude: this.selectedRepo.latitude,
116
        websiteUrl: this.selectedRepo.websiteurl,
117
        institutionName: this.selectedRepo.organizations[0].legalname,
118
        englishName: this.selectedRepo.englishname,
119
        logoUrl: this.selectedRepo.logourl,
120
        timezone: this.selectedRepo.timezone,
121
        datasourceType: this.selectedRepo.typology, // TODO: rename to typology?
122
        adminEmail: this.selectedRepo.contactemail
123
      });
124

    
125
      if ( this.selectedRepo.platform === '' || !this.typologies.some(x => x.value === this.selectedRepo.platform) ) {
126
        this.updateGroup.get('softwarePlatform').setValue('');
127
        this.updateGroup.get('platformName').setValue(this.selectedRepo.platform);
128
      }
129

    
130
      if (this.selectedRepo.eoscDatasourceType === 'Journal archive') {
131
        console.log('inside journal');
132
        this.updateGroup.get('issn').setValue(this.selectedRepo.issn);
133
        this.updateGroup.get('eissn').setValue(this.selectedRepo.eissn);
134
        this.updateGroup.get('lissn').setValue(this.selectedRepo.lissn);
135
      }
136

    
137
      // FIXME: Use eoscDatasourceType when we support the new model
138
      if ((this.mode === 'opendoar') || (this.mode === 're3data')) {
139

    
140
        this.updateGroup.get('country').disable();
141
      }
142

    
143
      // FIXME: Use eoscDatasourceType when we support the new model
144
      if (this.mode === 'cris') {
145
        this.longtitudeDesc.mandatory = false;
146
        this.latitudeDesc.mandatory = false;
147
        this.datasourceTypeDesc.label = 'CRIS scope/type';
148
      } else {
149
        this.longtitudeDesc.mandatory = true;
150
        this.latitudeDesc.mandatory = true;
151
        this.datasourceTypeDesc.label = 'Data source type';
152
      }
153

    
154
      // FIXME: Use eoscDatasourceType when we support the new model
155
      if (this.mode === 'journal') {
156

    
157
        let ssnToShow = this.selectedRepo.issn.slice(0, 4) + '-' + this.selectedRepo.issn.toString().slice(4);
158
        this.updateGroup.get('issn').setValue(ssnToShow);
159
        this.updateGroup.get('issn').clearValidators();
160
        this.updateGroup.get('issn').setValidators([Validators.required, Validators.pattern('^(\\d{4}-?\\d{3}[\\dxX])$')]);
161

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

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

    
172
        /* it was decided that all fields will be open, 21-12-2018 */
173
        /*this.updateGroup.get('issn').disable();
174
        this.updateGroup.get('eissn').disable();
175
        this.updateGroup.get('lissn').disable();*/
176
      }
177
    }
178
  }
179

    
180
  getDatasourceClasses() {
181
    // FIXME: Use eoscDatasourceType when we support the new model
182

    
183
    let param = this.selectedRepo.collectedfrom.split('::')[1];
184
    if (this.selectedRepo.eoscDatasourceType === 'Journal archive') { param = 'journal'; }
185
    if (this.selectedRepo.eoscDatasourceType === 'Aggregator') { param = 'aggregator'; }
186

    
187
    this.repoService.getDatasourceClasses(param).subscribe(
188
      classes => {
189
        for (const [key, value] of Object.entries(classes)) {
190
          this.datasourceClasses.set(key, value);
191
        }},
192
      error => {
193
        this.loadingMessage = '';
194
        this.errorMessage = noServiceMessage;
195
        console.log(error);
196
      },
197
      () => {
198
        console.log('gotDatasourceClasses');
199
        this.classCodes = Array.from(this.datasourceClasses.keys());
200
        this.getCountries();
201
      }
202
    );
203
  }
204

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

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

    
238
  getTimezones() {
239
    this.repoService.getTimezones().subscribe(
240
      zones => this.timezones = zones,
241
      error => {
242
        this.loadingMessage = '';
243
        console.log(error);
244
      },
245
      () => {
246
        this.loadingMessage = '';
247
        this.setupUpdateForm();
248
      }
249
    );
250
  }
251

    
252
  updateRepo() {
253
    this.formSubmitted = true;
254
    this.errorMessage = '';
255
    this.successMessage = '';
256
    window.scroll(1, 1);
257

    
258
    if (this.updateGroup.valid) {
259
      if ( this.selectedRepo.eoscDatasourceType !== 'journal' || this.updateGroup.get('issn').value ) {
260
        this.refreshSelectedRepo();
261

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

    
302
  refreshSelectedRepo() {
303
    if (this.updateGroup.get('softwarePlatform').value ) {
304
      this.selectedRepo.platform = this.updateGroup.get('softwarePlatform').value;
305
    } else if (this.updateGroup.get('platformName').value) {
306
      this.selectedRepo.platform = this.updateGroup.get('platformName').value;
307
    }
308
    this.selectedRepo.typology = this.updateGroup.get('datasourceType').value;
309
    console.log('typology ', this.selectedRepo.typology);
310
    console.log(this.datasourceClasses);
311
    console.log(this.updateGroup.get('datasourceType').value);
312
    this.selectedRepo.officialname = this.updateGroup.get('officialName').value.toString();
313
    this.selectedRepo.description = this.updateGroup.get('repoDescription').value.toString();
314
    this.selectedRepo.organizations[0].country = this.updateGroup.get('country').value; // countryCode
315
    this.selectedRepo.longitude = this.updateGroup.get('longtitude').value;
316
    this.selectedRepo.latitude = this.updateGroup.get('latitude').value;
317
    this.selectedRepo.websiteurl = this.updateGroup.get('websiteUrl').value;
318
    this.selectedRepo.organizations[0].legalname = this.updateGroup.get('institutionName').value.toString();
319
    this.selectedRepo.englishname = this.updateGroup.get('englishName').value.toString();
320
    this.selectedRepo.logourl = this.updateGroup.get('logoUrl').value;
321
    this.selectedRepo.timezone = this.updateGroup.get('timezone').value;
322
    this.selectedRepo.contactemail = this.updateGroup.get('adminEmail').value;
323
    if (this.selectedRepo.eoscDatasourceType === 'journal') {
324
      let ssnParts = this.updateGroup.get('issn').value.split('-');
325
      let correctSSN = ssnParts[0] + ssnParts[1];
326
      this.selectedRepo.issn = correctSSN;
327
      if ( this.updateGroup.get('eissn').value ) {
328
        ssnParts = this.updateGroup.get('eissn').value.split('-');
329
        correctSSN = ssnParts[0] + ssnParts[1];
330
        this.selectedRepo.eissn = correctSSN;
331
      }
332
      if ( this.updateGroup.get('lissn').value ) {
333
        ssnParts = this.updateGroup.get('lissn').value.split('-');
334
        correctSSN = ssnParts[0] + ssnParts[1];
335
        this.selectedRepo.lissn = correctSSN;
336
      }
337
    }
338
    if (!this.showButton) { // on register
339
      this.selectedRepo.registeredby = this.authService.getUserEmail();
340
      this.selectedRepo.managed = true;
341
      const now = new Date(Date.now());
342
      this.selectedRepo.consentTermsOfUseDate = now;
343
      this.selectedRepo.lastConsentTermsOfUseDate = now;
344
      this.selectedRepo.registrationdate = now;
345
      this.emittedInfo.emit(this.selectedRepo);
346
    }
347
  }
348

    
349
}
350

    
351
export function checkPlatform(c: AbstractControl) {
352
  if ( c.get('softwarePlatform').value || c.get('platformName').value ) {
353
    return null;
354
  }
355
  return 'invalid';
356
}
(6-6/8)