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])|([0-9]{7}[\\dxX]$)')] ],
47
    eissn : ['', Validators.pattern('^(\\d{4}-\\d{3}[\\dxX])|([0-9]{7}[\\dxX]$)') ],
48
    lissn : ['', Validators.pattern('^(\\d{4}-\\d{3}[\\dxX])|([0-9]{7}[\\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
console.log(this.mode);
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])|([0-9]{7}[\\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
    console.log('mode b4 getdatasourceclasses ', this.mode);
183

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

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

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

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

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

    
256
  updateRepo() {
257
    this.formSubmitted = true;
258
    this.errorMessage = '';
259
    this.successMessage = '';
260
    window.scroll(1, 1);
261

    
262
    if (this.updateGroup.valid) {
263
      if ( this.selectedRepo.eoscDatasourceType !== 'journal' || this.updateGroup.get('issn').value ) {
264
        this.refreshSelectedRepo();
265

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

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

    
355
}
356

    
357
export function checkPlatform(c: AbstractControl) {
358
  if ( c.get('softwarePlatform').value || c.get('platformName').value ) {
359
    return null;
360
  }
361
  return 'invalid';
362
}
(6-6/8)