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 : ['', [Validators.pattern('^\\d{4}-\\d{3}[\\dxX]$')] ],
44
    eissn : ['', Validators.pattern('^\\d{4}-\\d{3}[\\dxX]$') ],
45
    lissn : ['', Validators.pattern('^\\d{4}-\\d{3}[\\dxX]$') ],
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
      if ((this.selectedRepo.datasourceType === 'opendoar') ||
128
        (this.selectedRepo.datasourceType === 're3data')) {
129

    
130
        // this.updateGroup.get('officialName').disable();
131
        this.updateGroup.get('country').disable();
132
        // this.updateGroup.get('longtitude').disable();
133
        // this.updateGroup.get('latitude').disable();
134
        this.updateGroup.get('websiteUrl').disable();
135
        // this.updateGroup.get('institutionName').disable();
136

    
137
      }
138

    
139
      if (this.selectedRepo.datasourceType === 'journal') {
140

    
141
        let ssnToShow = this.selectedRepo.issn.slice(0, 4) + '-' + this.selectedRepo.issn.toString().slice(4);
142
        this.updateGroup.get('issn').setValue(ssnToShow);
143
        this.updateGroup.get('issn').clearValidators();
144
        this.updateGroup.get('issn').setValidators([Validators.required, Validators.pattern('^\\d{4}-\\d{3}[\\dxX]$')]);
145

    
146
        if (this.selectedRepo.eissn.trim().length) {
147
          ssnToShow = this.selectedRepo.eissn.slice(0, 4) + '-' + this.selectedRepo.eissn.toString().slice(4);
148
          this.updateGroup.get('eissn').setValue(ssnToShow);
149
        }
150

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

    
156
        /* it was decided that all fields will be open, 21-12-2018 */
157
        /*this.updateGroup.get('issn').disable();
158
        this.updateGroup.get('eissn').disable();
159
        this.updateGroup.get('lissn').disable();*/
160
      }
161
      /*this.getDatasourceClasses();*/
162
    }
163
  }
164

    
165
  getDatasourceClasses() {
166
    this.repoService.getDatasourceClasses(this.selectedRepo.datasourceType).subscribe(
167
      classes => this.datasourceClasses = classes,
168
      error => {
169
        this.loadingMessage = '';
170
        this.errorMessage = noServiceMessage;
171
        console.log(error);
172
      },
173
      () => {
174
        for (const key of Object.keys(this.datasourceClasses)) {
175
          this.classCodes.push(key);
176
        }
177
        this.getCountries();
178
      }
179
    );
180
  }
181

    
182
  getCountries() {
183
    this.repoService.getCountries()
184
      .subscribe(
185
        countries => this.countries = countries.sort( function(a, b) {
186
          if (a.name < b.name) {
187
            return -1;
188
          } else if (a.name > b.name) {
189
            return 1;
190
          } else {
191
            return 0;
192
          }
193
        } ),
194
        error => {
195
          this.loadingMessage = '';
196
          this.errorMessage = noServiceMessage;
197
          console.log(error);
198
        }, () => {
199
          this.getTypologies();
200
        });
201
  }
202

    
203
  getTypologies() {
204
    this.repoService.getTypologies().subscribe(
205
      types => this.typologies = types,
206
      error => {
207
        this.loadingMessage = '';
208
        console.log(error);
209
      },
210
      () => {
211
        this.getTimezones();
212
      }
213
    );
214
  }
215

    
216
  getTimezones() {
217
    this.repoService.getTimezones().subscribe(
218
      zones => this.timezones = zones,
219
      error => {
220
        this.loadingMessage = '';
221
        console.log(error);
222
      },
223
      () => {
224
        this.loadingMessage = '';
225
        this.setupUpdateForm();
226
      }
227
    );
228
  }
229

    
230
  updateRepo() {
231
    this.formSubmitted = true;
232
    this.errorMessage = '';
233
    this.successMessage = '';
234
    window.scroll(1, 1);
235

    
236
    if (this.updateGroup.valid) {
237
      if ( this.selectedRepo.datasourceType !== 'journal' || this.updateGroup.get('issn').value ) {
238
        this.refreshSelectedRepo();
239

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

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

    
319
}
320

    
321
export function checkPlatform(c: AbstractControl) {
322
  if ( c.get('softwarePlatform').value || c.get('platformName').value ) {
323
    return null;
324
  }
325
  return 'invalid';
326
}
(8-8/8)