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
      console.log(`mode is: ${this.mode}`);
105

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

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

    
131
      // FIXME: Use eoscDatasourceType when we support the new model
132
      if ((this.mode === 'opendoar') || (this.mode === 're3data')) {
133

    
134
        this.updateGroup.get('country').disable();
135
      }
136

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

    
140
        this.longtitudeDesc.mandatory = false;
141
        this.latitudeDesc.mandatory = false;
142
        this.datasourceTypeDesc.label = 'CRIS scope/type';
143
      }
144

    
145
      // FIXME: Use eoscDatasourceType when we support the new model
146
      if (this.mode === 'journal') {
147

    
148
        let ssnToShow = this.selectedRepo.issn.slice(0, 4) + '-' + this.selectedRepo.issn.toString().slice(4);
149
        this.updateGroup.get('issn').setValue(ssnToShow);
150
        this.updateGroup.get('issn').clearValidators();
151
        this.updateGroup.get('issn').setValidators([Validators.required, Validators.pattern('^\\d{4}-\\d{3}[\\dxX]$')]);
152

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

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

    
163
        /* it was decided that all fields will be open, 21-12-2018 */
164
        /*this.updateGroup.get('issn').disable();
165
        this.updateGroup.get('eissn').disable();
166
        this.updateGroup.get('lissn').disable();*/
167
      }
168
    }
169
  }
170

    
171
  getDatasourceClasses() {
172
    // FIXME: Use eoscDatasourceType when we support the new model
173
    this.repoService.getDatasourceClasses(this.mode).subscribe(
174
      classes => this.datasourceClasses = classes,
175
      error => {
176
        this.loadingMessage = '';
177
        this.errorMessage = noServiceMessage;
178
        console.log(error);
179
      },
180
      () => {
181
        for (const key of Object.keys(this.datasourceClasses)) {
182
          this.classCodes.push(key);
183
        }
184
        this.getCountries();
185
      }
186
    );
187
  }
188

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

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

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

    
237
  updateRepo() {
238
    this.formSubmitted = true;
239
    this.errorMessage = '';
240
    this.successMessage = '';
241
    window.scroll(1, 1);
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.up
255
          this.repoService.updateRepository(this.selectedRepo).subscribe(
256
            response => {
257
              if (response) {
258
                this.selectedRepo = response;
259
                console.log(`updateRepository responded: ${JSON.stringify(response)}`);
260
              }
261
            },
262
            error => {
263
              console.log(error);
264
              this.loadingMessage = '';
265
              this.errorMessage = formErrorWasntSaved;
266
            },
267
            () => {
268
              this.loadingMessage = '';
269
              if (!this.selectedRepo) {
270
                this.errorMessage = formErrorWasntSaved;
271
              } else {
272
                this.successMessage = formSuccessUpdatedRepo;
273
              }
274
              // fixme is this the place to update the subject??
275
              this.sharedService.setRepository(this.selectedRepo);
276
            }
277
          );
278
        }
279
      } else {
280
        this.errorMessage = formErrorRequiredFields;
281
      }
282
    } else {
283
      this.errorMessage = formErrorRequiredFields;
284
    }
285
  }
286

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

    
329
}
330

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