-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathUserProfileService.cs
More file actions
3095 lines (2902 loc) · 172 KB
/
UserProfileService.cs
File metadata and controls
3095 lines (2902 loc) · 172 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using api.Models.Ttv;
using api.Models.ProfileEditor;
using api.Models.ProfileEditor.Items;
using Microsoft.EntityFrameworkCore;
using api.Models.Common;
using api.Models.Orcid;
using api.Models.Log;
using api.Services.Profiledata;
using Dapper;
using Microsoft.Extensions.Logging;
using System.Diagnostics;
namespace api.Services
{
/*
* UserProfileService implements utilities, which simplify handling of userprofile and related data.
*/
public class UserProfileService : IUserProfileService
{
private readonly TtvContext _ttvContext;
private readonly IAffiliationService _affiliationService;
private readonly IEducationService _educationService;
private readonly IEmailService _emailService;
private readonly IExternalIdentifierService _externalIdentifierService;
private readonly IKeywordService _keywordService;
private readonly INameService _nameService;
private readonly IPublicationService _publicationService;
private readonly IResearcherDescriptionService _researcherDescriptionService;
private readonly ITelephoneNumberService _telephoneNumberService;
private readonly IWebLinkService _webLinkService;
private readonly IFundingDecisionService _fundingDecisionService;
private readonly IResearchDatasetService _researchDatasetService;
private readonly IResearchActivityService _researchActivityService;
private readonly IUniqueDataSourcesService _uniqueDataSourcesService;
private readonly IDataSourceHelperService _dataSourceHelperService;
private readonly IUtilityService _utilityService;
private readonly ILanguageService _languageService;
private readonly IDuplicateHandlerService _duplicateHandlerService;
private readonly ISharingService _sharingService;
private readonly ITtvSqlService _ttvSqlService;
private readonly ILogger<UserProfileService> _logger;
private readonly IElasticsearchService _elasticsearchService;
private readonly ISettingsService _settingsService;
private readonly ICooperationChoicesService _cooperationChoicesService;
public UserProfileService(
TtvContext ttvContext,
IDataSourceHelperService dataSourceHelperService,
IUtilityService utilityService,
ILanguageService languageService,
IDuplicateHandlerService duplicateHandlerService,
ISharingService sharingService,
ITtvSqlService ttvSqlService,
ILogger<UserProfileService> logger,
IElasticsearchService elasticsearchService,
IAffiliationService affiliationService,
IEducationService educationService,
IEmailService emailService,
IExternalIdentifierService externalIdentifierService,
IKeywordService keywordService,
INameService nameService,
IPublicationService publicationService,
IResearcherDescriptionService researcherDescriptionService,
ITelephoneNumberService telephoneNumberService,
IWebLinkService webLinkService,
IFundingDecisionService fundingDecisionService,
IResearchDatasetService researchDatasetService,
IResearchActivityService researchActivityService,
IUniqueDataSourcesService uniqueDataSourcesService,
ISettingsService settingsService,
ICooperationChoicesService cooperationChoicesService)
{
_ttvContext = ttvContext;
_dataSourceHelperService = dataSourceHelperService;
_utilityService = utilityService;
_languageService = languageService;
_settingsService = settingsService;
_duplicateHandlerService = duplicateHandlerService;
_sharingService = sharingService;
_ttvSqlService = ttvSqlService;
_logger = logger;
_cooperationChoicesService = cooperationChoicesService;
_elasticsearchService = elasticsearchService;
_uniqueDataSourcesService = uniqueDataSourcesService;
_researchActivityService = researchActivityService;
_affiliationService = affiliationService;
_educationService = educationService;
_emailService = emailService;
_externalIdentifierService = externalIdentifierService;
_keywordService = keywordService;
_nameService = nameService;
_publicationService = publicationService;
_researcherDescriptionService = researcherDescriptionService;
_telephoneNumberService = telephoneNumberService;
_webLinkService = webLinkService;
_fundingDecisionService = fundingDecisionService;
_researchDatasetService = researchDatasetService;
}
public UserProfileService(
TtvContext ttvContext,
ITtvSqlService ttvSqlService,
ILogger<UserProfileService> logger)
{
_ttvContext = ttvContext;
_ttvSqlService = ttvSqlService;
_logger = logger;
}
public UserProfileService() { }
public UserProfileService(IUtilityService utilityService) {
_utilityService = utilityService;
}
public UserProfileService(IUtilityService utilityService, ILogger<UserProfileService> logger) {
_utilityService = utilityService;
_logger = logger;
}
public UserProfileService(IDataSourceHelperService dataSourceHelperService)
{
_dataSourceHelperService = dataSourceHelperService;
}
public UserProfileService(ILanguageService languageService)
{
_languageService = languageService;
}
/*
* Get FieldIdentifiers.
*/
public List<int> GetFieldIdentifiers()
{
return new List<int>()
{
Constants.FieldIdentifiers.PERSON_EMAIL_ADDRESS,
Constants.FieldIdentifiers.PERSON_EXTERNAL_IDENTIFIER,
Constants.FieldIdentifiers.PERSON_FIELD_OF_SCIENCE,
Constants.FieldIdentifiers.PERSON_KEYWORD,
Constants.FieldIdentifiers.PERSON_NAME,
Constants.FieldIdentifiers.PERSON_OTHER_NAMES,
Constants.FieldIdentifiers.PERSON_RESEARCHER_DESCRIPTION,
Constants.FieldIdentifiers.PERSON_TELEPHONE_NUMBER,
Constants.FieldIdentifiers.PERSON_WEB_LINK,
Constants.FieldIdentifiers.ACTIVITY_AFFILIATION,
Constants.FieldIdentifiers.ACTIVITY_EDUCATION,
Constants.FieldIdentifiers.ACTIVITY_PUBLICATION,
Constants.FieldIdentifiers.ACTIVITY_PUBLICATION_PROFILE_ONLY,
Constants.FieldIdentifiers.ACTIVITY_FUNDING_DECISION,
Constants.FieldIdentifiers.ACTIVITY_RESEARCH_DATASET,
Constants.FieldIdentifiers.ACTIVITY_RESEARCH_ACTIVITY
};
}
/*
* Update ORCID tokens in DimUserProfile
*/
public async Task UpdateOrcidTokensInDimUserProfile(int dimUserProfileId, OrcidTokens orcidTokens)
{
DimUserProfile dimUserProfile = await _ttvContext.DimUserProfiles.FindAsync(dimUserProfileId);
dimUserProfile.OrcidAccessToken = orcidTokens.AccessToken;
dimUserProfile.OrcidRefreshToken = orcidTokens.RefreshToken;
dimUserProfile.OrcidTokenScope = orcidTokens.Scope;
dimUserProfile.OrcidTokenExpires = orcidTokens.ExpiresDatetime;
await _ttvContext.SaveChangesAsync();
}
/*
* Check if data related to FactFieldValue can be removed.
* Data from registered data source ORCID can be removed.
*/
public bool CanDeleteFactFieldValueRelatedData(FactFieldValue ffv)
{
return ffv.DimRegisteredDataSourceId == _dataSourceHelperService.DimRegisteredDataSourceId_ORCID;
}
/*
* Get DimUserProfile based on ORCID Id.
*/
public async Task<DimUserProfile> GetUserprofile(string orcidId)
{
return await _ttvContext.DimUserProfiles.Where(dup => dup.OrcidId == orcidId).AsNoTracking().FirstOrDefaultAsync();
}
/*
* Get DimUserProfile based on ORCID Id.
* Returns tracking entity to allow modifications.
*/
public async Task<DimUserProfile> GetUserprofileTracking(string orcidId)
{
return await _ttvContext.DimUserProfiles.Where(dup => dup.OrcidId == orcidId).FirstOrDefaultAsync();
}
/*
* Get DimUserProfile based on Id.
*/
public async Task<DimUserProfile> GetUserprofileById(int Id)
{
return await _ttvContext.DimUserProfiles.Where(dup => dup.Id == Id).AsNoTracking().FirstOrDefaultAsync();
}
/*
* Check if user profile exists for ORCID Id.
*/
public async Task<(bool UserProfileExists, int UserProfileId)> GetUserprofileIdForOrcidId(string orcidId)
{
IntegerDTO dimUserProfileIdDTO = await _ttvContext.DimUserProfiles.Where(dup => dup.OrcidId == orcidId).AsNoTracking()
.Select(dimUserProfile => new IntegerDTO()
{
Value = dimUserProfile.Id
}).FirstOrDefaultAsync();
if (dimUserProfileIdDTO == null || dimUserProfileIdDTO.Value < 0) {
return (UserProfileExists: false, UserProfileId: -1);
}
else {
return (UserProfileExists: true, UserProfileId: dimUserProfileIdDTO.Value);
}
}
/*
* Set 'modified' timestamp in user profile
*/
public async Task SetModifiedTimestampInUserProfile(int Id)
{
await ExecuteRawSql(
_ttvSqlService.GetSqlQuery_Update_DimUserProfile_Modified(Id)
);
}
/*
* Add or update DimName.
*/
public async Task<DimName> AddOrUpdateDimName(String lastName, String firstNames, int dimKnownPersonId, int dimRegisteredDataSourceId)
{
DimName dimName = await _ttvContext.DimNames.FirstOrDefaultAsync(dn => dn.DimKnownPersonIdConfirmedIdentityNavigation.Id == dimKnownPersonId && dn.DimRegisteredDataSourceId == dimRegisteredDataSourceId);
if (dimName == null)
{
dimName = new DimName()
{
LastName = lastName,
FirstNames = firstNames,
DimKnownPersonIdConfirmedIdentity = dimKnownPersonId,
SourceId = Constants.SourceIdentifiers.PROFILE_API,
SourceDescription = Constants.SourceDescriptions.PROFILE_API,
Created = _utilityService.GetCurrentDateTime(),
Modified = _utilityService.GetCurrentDateTime(),
DimRegisteredDataSourceId = dimRegisteredDataSourceId
};
_ttvContext.DimNames.Add(dimName);
}
else
{
dimName.LastName = lastName;
dimName.FirstNames = firstNames;
dimName.Modified = _utilityService.GetCurrentDateTime();
}
await _ttvContext.SaveChangesAsync();
return dimName;
}
/*
* Add or update DimResearcherDescription.
*/
public async Task<DimResearcherDescription> AddOrUpdateDimResearcherDescription(String description_fi, String description_en, String description_sv, int dimKnownPersonId, int dimRegisteredDataSourceId)
{
DimResearcherDescription dimResearcherDescription = await _ttvContext.DimResearcherDescriptions.FirstOrDefaultAsync(dr => dr.DimKnownPersonId == dimKnownPersonId && dr.DimRegisteredDataSourceId == dimRegisteredDataSourceId);
if (dimResearcherDescription == null)
{
dimResearcherDescription = new DimResearcherDescription()
{
ResearchDescriptionFi = description_fi,
ResearchDescriptionEn = description_en,
ResearchDescriptionSv = description_sv,
SourceId = Constants.SourceIdentifiers.PROFILE_API,
SourceDescription = Constants.SourceDescriptions.PROFILE_API,
Created = _utilityService.GetCurrentDateTime(),
Modified = _utilityService.GetCurrentDateTime(),
DimKnownPersonId = dimKnownPersonId,
DimRegisteredDataSourceId = dimRegisteredDataSourceId
};
_ttvContext.DimResearcherDescriptions.Add(dimResearcherDescription);
}
else
{
dimResearcherDescription.ResearchDescriptionFi = description_fi;
dimResearcherDescription.ResearchDescriptionEn = description_en;
dimResearcherDescription.ResearchDescriptionSv = description_sv;
dimResearcherDescription.Modified = _utilityService.GetCurrentDateTime();
}
await _ttvContext.SaveChangesAsync();
return dimResearcherDescription;
}
/*
* Add or update DimEmailAddrress.
*/
public async Task<DimEmailAddrress> AddOrUpdateDimEmailAddress(string emailAddress, int dimKnownPersonId, int dimRegisteredDataSourceId)
{
DimEmailAddrress dimEmailAddress = await _ttvContext.DimEmailAddrresses.FirstOrDefaultAsync(dr => dr.Email == emailAddress && dr.DimKnownPersonId == dimKnownPersonId && dr.DimRegisteredDataSourceId == dimRegisteredDataSourceId);
if (dimEmailAddress == null)
{
dimEmailAddress = new DimEmailAddrress()
{
Email = emailAddress,
SourceId = Constants.SourceIdentifiers.PROFILE_API,
SourceDescription = Constants.SourceDescriptions.PROFILE_API,
Created = _utilityService.GetCurrentDateTime(),
Modified = _utilityService.GetCurrentDateTime(),
DimKnownPersonId = dimKnownPersonId,
DimRegisteredDataSourceId = dimRegisteredDataSourceId
};
_ttvContext.DimEmailAddrresses.Add(dimEmailAddress);
}
else
{
dimEmailAddress.Modified = _utilityService.GetCurrentDateTime();
}
await _ttvContext.SaveChangesAsync();
return dimEmailAddress;
}
/*
* Get new DimKnownPerson.
* - ORCID ID must be used as a source_id.
* - Registered data source must point to ORCID.
*/
public DimKnownPerson GetNewDimKnownPerson(string orcidId, DateTime currentDateTime)
{
return new DimKnownPerson()
{
SourceId = orcidId, // ORCID ID must be used in dim_known_person.source_id
SourceDescription = Constants.SourceDescriptions.PROFILE_API,
Created = currentDateTime,
Modified = currentDateTime,
DimRegisteredDataSourceId = _dataSourceHelperService.DimRegisteredDataSourceId_ORCID
};
}
/*
* Get empty FactFieldValue.
* Must use -1 in required foreign keys.
*/
public FactFieldValue GetEmptyFactFieldValue()
{
return new FactFieldValue()
{
DimUserProfileId = -1,
DimFieldDisplaySettingsId = -1,
DimNameId = -1,
DimWebLinkId = -1,
DimFundingDecisionId = -1,
DimPublicationId = -1,
DimPidId = -1,
DimPidIdOrcidPutCode = -1,
DimResearchActivityId = -1,
DimEventId = -1,
DimEducationId = -1,
DimCompetenceId = -1,
DimResearchCommunityId = -1,
DimTelephoneNumberId = -1,
DimEmailAddrressId = -1,
DimResearcherDescriptionId = -1,
DimIdentifierlessDataId = -1,
DimProfileOnlyDatasetId = -1,
DimProfileOnlyFundingDecisionId = -1,
DimProfileOnlyPublicationId = -1,
DimProfileOnlyResearchActivityId = -1,
DimKeywordId = -1,
DimAffiliationId = -1,
DimResearcherToResearchCommunityId = -1,
DimResearchDatasetId = -1,
DimReferencedataFieldOfScienceId = -1,
DimReferencedataActorRoleId = -1,
Show = false,
PrimaryValue = false,
SourceId = Constants.SourceIdentifiers.PROFILE_API,
SourceDescription = Constants.SourceDescriptions.PROFILE_API,
Created = _utilityService.GetCurrentDateTime(),
Modified = _utilityService.GetCurrentDateTime()
};
}
/*
* Get empty FactFieldValue. Set SourceID to DEMO.
*/
public FactFieldValue GetEmptyFactFieldValueDemo()
{
FactFieldValue factFieldValue = this.GetEmptyFactFieldValue();
factFieldValue.SourceId = Constants.SourceIdentifiers.DEMO;
return factFieldValue;
}
/*
* Get empty DimProfileOnlyDataset.
* Must use -1 in required foreign keys.
*/
public DimProfileOnlyDataset GetEmptyDimProfileOnlyDataset()
{
return new DimProfileOnlyDataset()
{
DimReferencedataIdAvailability = null,
OrcidWorkType = "",
LocalIdentifier = "",
NameFi = "",
NameEn = "",
NameSv = "",
NameUnd = "",
DescriptionFi = "",
DescriptionSv = "",
DescriptionEn = "",
DescriptionUnd = "",
VersionInfo = "",
DatasetCreated = null,
SourceId = Constants.SourceIdentifiers.PROFILE_API,
SourceDescription = Constants.SourceDescriptions.PROFILE_API,
Created = null,
Modified = null,
DimRegisteredDataSourceId = -1
};
}
/*
* Get empty DimProfileOnlyFundingDecision.
* Must use -1 in required foreign keys.
*/
public DimProfileOnlyFundingDecision GetEmptyDimProfileOnlyFundingDecision()
{
return new DimProfileOnlyFundingDecision()
{
DimDateIdApproval = -1,
DimDateIdStart = -1,
DimDateIdEnd = -1,
DimCallProgrammeId = -1,
DimTypeOfFundingId = -1,
DimOrganizationIdFunder = null,
OrcidWorkType = "",
FunderProjectNumber = "",
Acronym = "",
NameFi = "",
NameSv = "",
NameEn = "",
NameUnd = "",
DescriptionFi = "",
DescriptionEn = "",
DescriptionSv = "",
AmountInEur = -1,
AmountInFundingDecisionCurrency = null,
FundingDecisionCurrencyAbbreviation = "",
SourceId = Constants.SourceIdentifiers.PROFILE_API,
SourceDescription = Constants.SourceDescriptions.PROFILE_API,
Created = null,
Modified = null,
DimRegisteredDataSourceId = -1
};
}
/*
* Get empty DimProfileOnlyPublication.
* Must use -1 in required foreign keys.
*/
public DimProfileOnlyPublication GetEmptyDimProfileOnlyPublication()
{
return new DimProfileOnlyPublication()
{
DimProfileOnlyPublicationId = null,
ParentTypeClassificationCode = -1,
TypeClassificationCode = -1,
PublicationFormatCode = -1,
ArticleTypeCode = -1,
TargetAudienceCode = -1,
OrcidWorkType = null,
PublicationName = "",
ConferenceName = null,
ShortDescription = null,
PublicationYear = null,
PublicationId = "",
AuthorsText = "",
NumberOfAuthors = null,
PageNumberText = null,
ArticleNumberText = null,
IssueNumber = null,
Volume = null,
PublicationCountryCode = -1,
PublisherName = null,
PublisherLocation = null,
ParentPublicationName = null,
ParentPublicationEditors = null,
LicenseCode = -1,
LanguageCode = -1,
OpenAccessCode = null,
OriginalPublicationId = null,
PeerReviewed = null,
Report = null,
ThesisTypeCode = -1,
DoiHandle = null,
SourceId = Constants.SourceIdentifiers.PROFILE_API,
SourceDescription = Constants.SourceDescriptions.PROFILE_API,
Created = null,
Modified = null,
DimKnownPersonId = -1,
DimRegisteredDataSourceId = -1
};
}
/*
* Get empty DimProfileOnlyResearchActivity.
* Must use -1 in required foreign keys.
*/
public DimProfileOnlyResearchActivity GetEmptyDimProfileOnlyResearchActivity()
{
return new DimProfileOnlyResearchActivity()
{
DimDateIdStart = -1,
DimDateIdEnd = -1,
DimGeoIdCountry = null,
DimOrganizationId = -1,
DimEventId = -1,
LocalIdentifier = "",
OrcidWorkType = "",
NameFi = "",
NameSv = "",
NameEn = "",
NameUnd = "",
DescriptionFi = "",
DescriptionEn = "",
DescriptionSv = "",
IndentifierlessTargetOrg = "",
SourceId = Constants.SourceIdentifiers.PROFILE_API,
SourceDescription = Constants.SourceDescriptions.PROFILE_API,
Created = null,
Modified = null,
DimRegisteredDataSourceId = -1
};
}
/*
* Get empty DimPid.
* Must use -1 in required foreign keys.
*/
public DimPid GetEmptyDimPid()
{
return new DimPid()
{
PidContent = "",
PidType = "",
DimOrganizationId = -1,
DimKnownPersonId = -1,
DimPublicationId = -1,
DimServiceId = -1,
DimInfrastructureId = -1,
DimPublicationChannelId = -1,
DimResearchDatasetId = -1,
DimResearchDataCatalogId = -1,
DimResearchActivityId = -1,
DimEventId = -1,
DimProfileOnlyDatasetId = -1,
DimProfileOnlyFundingDecisionId = -1,
DimProfileOnlyPublicationId = -1,
DimResearchCommunityId = -1,
DimResearchProjectId = -1,
SourceId = Constants.SourceIdentifiers.PROFILE_API,
SourceDescription = Constants.SourceDescriptions.PROFILE_API,
Created = _utilityService.GetCurrentDateTime(),
Modified = _utilityService.GetCurrentDateTime()
};
}
/*
* Check if a DimName can be included in user profile.
* Exclude DimName, which are already included in profile.
* Exclude DimNames, whose registered data source is any of the following:
* - virta
* - metax
* - sftp_funding
*/
public bool CanIncludeDimNameInUserProfile(List<long> existingIDs, DimName dimName)
{
return
!existingIDs.Contains(dimName.Id) &&
!(
dimName.DimRegisteredDataSource.Name == "virta" ||
dimName.DimRegisteredDataSource.Name == "metax" ||
dimName.DimRegisteredDataSource.Name == "sftp_funding"
);
}
/*
* Check if research activities are duplicates.
* Comparison is based on fields:
* - start year
* - name FI
* - name EN
* - name SV
*/
public bool IsResearchActivityDuplicate(int aYear, string aNameFi, string aNameEn, string aNameSv, int bYear, string bNameFi, string bNameEn, string bNameSv)
{
return (
aYear == bYear &&
aNameFi == bNameFi &&
aNameEn == bNameEn &&
aNameSv == bNameSv);
}
/*
* Get fullName from lastName and firstNames
*/
public string GetFullname(string lastName, string firstNames)
{
return $"{lastName.Trim()} {firstNames.Trim()}".Trim();
}
/*
* Helper method, set parameter 'show' of new FactFieldValue.
* This decides wheter new items are automatically included in the profile.
*
* Despite its name, the setting DimUserProfile.PublishNewOrcidData covers both ORCID and TTV data.
*/
public bool SetFactFieldValuesShow(DimUserProfile dimUserProfile, int fieldIdentifier, LogUserIdentification logUserIdentification)
{
try
{
if (dimUserProfile == null)
{
_logger.LogInformation(
LogContent.MESSAGE_TEMPLATE,
logUserIdentification,
new LogApiInfo(
action: LogContent.Action.PROFILE_MODIFY_SHOW,
state: LogContent.ActionState.FAILED,
message: $"Failed to assert auto publish criteria: dimUserProfile==null"
));
return false;
}
else if (fieldIdentifier < 0)
{
_logger.LogInformation(
LogContent.MESSAGE_TEMPLATE,
logUserIdentification,
new LogApiInfo(
action: LogContent.Action.PROFILE_MODIFY_SHOW,
state: LogContent.ActionState.FAILED,
message: $"Failed to assert auto publish criteria: fieldIdentifier<0"
));
return false;
}
return
dimUserProfile.PublishNewOrcidData &&
fieldIdentifier != Constants.FieldIdentifiers.PERSON_NAME &&
fieldIdentifier != Constants.FieldIdentifiers.PERSON_TELEPHONE_NUMBER &&
fieldIdentifier != Constants.FieldIdentifiers.PERSON_KEYWORD &&
fieldIdentifier != Constants.FieldIdentifiers.PERSON_RESEARCHER_DESCRIPTION;
}
catch
{
_logger.LogInformation(
LogContent.MESSAGE_TEMPLATE,
logUserIdentification,
new LogApiInfo(
action: LogContent.Action.PROFILE_MODIFY_SHOW,
state: LogContent.ActionState.FAILED,
message: $"Failed to set FactFieldValues.Show"
));
return false;
}
}
/*
* Search and add data from TTV database.
* This is data that is already linked to the ORCID id in DimPid and it's related DimKnownPerson.
* ProfileOnly* items must be excluded in these queries.
*/
public async Task AddTtvDataToUserProfile(DimKnownPerson dimKnownPerson, DimUserProfile dimUserProfile, LogUserIdentification logUserIdentification)
{
_logger.LogInformation(
LogContent.MESSAGE_TEMPLATE,
logUserIdentification,
new LogApiInfo(
action: LogContent.Action.PROFILE_ADD_TTV_DATA,
state: LogContent.ActionState.START,
message: $"dim_user_profile.id={dimUserProfile.Id}"
));
// Get FactFieldValues
List<FactFieldValue> ffvs = await _ttvContext.FactFieldValues.Where(f => f.DimUserProfileId == dimUserProfile.Id).AsNoTracking().ToListAsync();
// Collect lists of IDs, which are already included in the profile.
// They are used in SQL where condition to filter out duplicates.
List<int> existingEmailIds = new();
List<int> existingWebLinkIds = new();
List<int> existingTelephoneNumberIds = new();
List<int> existingResearcherDescriptionIds = new();
List<int> existingAffiliationIds = new();
List<int> existingEducationIds = new();
List<long> existingNameIds = new();
List<int> existingPublicationIds = new();
List<int> existingResearchActivityIds = new();
List<int> existingResearchDatasetIds = new();
List<int> existingFundingDecisionIds = new();
if (ffvs != null)
{
existingEmailIds = ffvs.Where(ffv => ffv.DimEmailAddrressId != -1).Select(ffv => ffv.DimEmailAddrressId).Distinct().ToList<int>();
existingWebLinkIds = ffvs.Where(ffv => ffv.DimWebLinkId != -1).Select(ffv => ffv.DimWebLinkId).Distinct().ToList<int>();
existingTelephoneNumberIds = ffvs.Where(ffv => ffv.DimTelephoneNumberId != -1).Select(ffv => ffv.DimTelephoneNumberId).Distinct().ToList<int>();
existingResearcherDescriptionIds = ffvs.Where(ffv => ffv.DimResearcherDescriptionId != -1).Select(ffv => ffv.DimResearcherDescriptionId).Distinct().ToList<int>();
existingAffiliationIds = ffvs.Where(ffv => ffv.DimAffiliationId != -1).Select(ffv => ffv.DimAffiliationId).Distinct().ToList<int>();
existingEducationIds = ffvs.Where(ffv => ffv.DimEducationId != -1).Select(ffv => ffv.DimEducationId).Distinct().ToList<int>();
existingNameIds = ffvs.Where(ffv => ffv.DimNameId != -1).Select(ffv => ffv.DimNameId).Distinct().ToList<long>();
existingPublicationIds = ffvs.Where(ffv => ffv.DimPublicationId != -1).Select(ffv => ffv.DimPublicationId).Distinct().ToList<int>();
existingResearchActivityIds = ffvs.Where(ffv => ffv.DimResearchActivityId != -1).Select(ffv => ffv.DimResearchActivityId).Distinct().ToList<int>();
existingResearchDatasetIds = ffvs.Where(ffv => ffv.DimResearchDatasetId != -1).Select(ffv => ffv.DimResearchDatasetId).Distinct().ToList<int>();
existingFundingDecisionIds = ffvs.Where(ffv => ffv.DimFundingDecisionId != -1).Select(ffv => ffv.DimFundingDecisionId).Distinct().ToList<int>();
}
using (var connection = _ttvContext.Database.GetDbConnection())
{
// email
try
{
string emailSql = _ttvSqlService.GetSqlQuery_Select_DimEmailAddrress(dimKnownPerson.Id, existingEmailIds);
List<DimTableMinimalDTO> emails = (await connection.QueryAsync<DimTableMinimalDTO>(emailSql)).ToList();
DimFieldDisplaySetting dimFieldDisplaySetting_emailAddress =
dimUserProfile.DimFieldDisplaySettings.Where(dfds => dfds.FieldIdentifier == Constants.FieldIdentifiers.PERSON_EMAIL_ADDRESS).First();
foreach (DimTableMinimalDTO email in emails)
{
FactFieldValue factFieldValueEmailAddress = this.GetEmptyFactFieldValue();
factFieldValueEmailAddress.DimUserProfileId = dimUserProfile.Id;
factFieldValueEmailAddress.DimFieldDisplaySettingsId = dimFieldDisplaySetting_emailAddress.Id;
factFieldValueEmailAddress.DimEmailAddrressId = email.Id;
factFieldValueEmailAddress.DimRegisteredDataSourceId = email.DimRegisteredDataSourceId;
factFieldValueEmailAddress.Show = this.SetFactFieldValuesShow(dimUserProfile, Constants.FieldIdentifiers.PERSON_EMAIL_ADDRESS, logUserIdentification);
_ttvContext.FactFieldValues.Add(factFieldValueEmailAddress);
}
}
catch (Exception ex)
{
_logger.LogError(
LogContent.MESSAGE_TEMPLATE,
logUserIdentification,
new LogApiInfo(
action: LogContent.Action.PROFILE_ADD_TTV_DATA,
state: LogContent.ActionState.FAILED,
error: true,
message: $"dim_user_profile.id={dimUserProfile.Id}, email: {ex.ToString()}"));
}
// web link
try
{
string webLinkSql = _ttvSqlService.GetSqlQuery_Select_DimWebLink(dimKnownPerson.Id, existingWebLinkIds);
List<DimTableMinimalDTO> webLinks = (await connection.QueryAsync<DimTableMinimalDTO>(webLinkSql)).ToList();
DimFieldDisplaySetting dimFieldDisplaySetting_webLink =
dimUserProfile.DimFieldDisplaySettings.Where(dfds => dfds.FieldIdentifier == Constants.FieldIdentifiers.PERSON_WEB_LINK).First();
foreach (DimTableMinimalDTO webLink in webLinks)
{
FactFieldValue factFieldValueWebLink = this.GetEmptyFactFieldValue();
factFieldValueWebLink.DimUserProfileId = dimUserProfile.Id;
factFieldValueWebLink.DimFieldDisplaySettingsId = dimFieldDisplaySetting_webLink.Id;
factFieldValueWebLink.DimWebLinkId = webLink.Id;
factFieldValueWebLink.DimRegisteredDataSourceId = webLink.DimRegisteredDataSourceId;
factFieldValueWebLink.Show = this.SetFactFieldValuesShow(dimUserProfile, Constants.FieldIdentifiers.PERSON_WEB_LINK, logUserIdentification);
_ttvContext.FactFieldValues.Add(factFieldValueWebLink);
}
}
catch (Exception ex)
{
_logger.LogError(
LogContent.MESSAGE_TEMPLATE,
logUserIdentification,
new LogApiInfo(
action: LogContent.Action.PROFILE_ADD_TTV_DATA,
state: LogContent.ActionState.FAILED,
error: true,
message: $"dim_user_profile.id={dimUserProfile.Id}, web link: {ex.ToString()}"));
}
// telephone number
try
{
string telephoneNumberSql = _ttvSqlService.GetSqlQuery_Select_DimTelephoneNumber(dimKnownPerson.Id, existingTelephoneNumberIds);
List<DimTableMinimalDTO> telephoneNumbers = (await connection.QueryAsync<DimTableMinimalDTO>(telephoneNumberSql)).ToList();
DimFieldDisplaySetting dimFieldDisplaySetting_telephoneNumber =
dimUserProfile.DimFieldDisplaySettings.Where(dfds => dfds.FieldIdentifier == Constants.FieldIdentifiers.PERSON_TELEPHONE_NUMBER).First();
foreach (DimTableMinimalDTO telephoneNumber in telephoneNumbers)
{
FactFieldValue factFieldValueTelephoneNumber = this.GetEmptyFactFieldValue();
factFieldValueTelephoneNumber.DimUserProfileId = dimUserProfile.Id;
factFieldValueTelephoneNumber.DimFieldDisplaySettingsId = dimFieldDisplaySetting_telephoneNumber.Id;
factFieldValueTelephoneNumber.DimTelephoneNumberId = telephoneNumber.Id;
factFieldValueTelephoneNumber.DimRegisteredDataSourceId = telephoneNumber.DimRegisteredDataSourceId;
factFieldValueTelephoneNumber.Show = this.SetFactFieldValuesShow(dimUserProfile, Constants.FieldIdentifiers.PERSON_TELEPHONE_NUMBER, logUserIdentification);
_ttvContext.FactFieldValues.Add(factFieldValueTelephoneNumber);
}
}
catch (Exception ex)
{
_logger.LogError(
LogContent.MESSAGE_TEMPLATE,
logUserIdentification,
new LogApiInfo(
action: LogContent.Action.PROFILE_ADD_TTV_DATA,
state: LogContent.ActionState.FAILED,
error: true,
message: $"dim_user_profile.id={dimUserProfile.Id}, telephone number: {ex.ToString()}"));
}
// researcher description
try
{
string researcherDescriptionSql = _ttvSqlService.GetSqlQuery_Select_DimResearcherDescription(dimKnownPerson.Id, existingResearcherDescriptionIds);
List<DimTableMinimalDTO> researcherDescriptions = (await connection.QueryAsync<DimTableMinimalDTO>(researcherDescriptionSql)).ToList();
DimFieldDisplaySetting dimFieldDisplaySetting_researcherDescription =
dimUserProfile.DimFieldDisplaySettings.Where(dfds => dfds.FieldIdentifier == Constants.FieldIdentifiers.PERSON_RESEARCHER_DESCRIPTION).First();
foreach (DimTableMinimalDTO researcherDescription in researcherDescriptions)
{
FactFieldValue factFieldValueResearcherDescription = this.GetEmptyFactFieldValue();
factFieldValueResearcherDescription.DimUserProfileId = dimUserProfile.Id;
factFieldValueResearcherDescription.DimFieldDisplaySettingsId = dimFieldDisplaySetting_researcherDescription.Id;
factFieldValueResearcherDescription.DimResearcherDescriptionId = researcherDescription.Id;
factFieldValueResearcherDescription.DimRegisteredDataSourceId = researcherDescription.DimRegisteredDataSourceId;
factFieldValueResearcherDescription.Show = this.SetFactFieldValuesShow(dimUserProfile, Constants.FieldIdentifiers.PERSON_RESEARCHER_DESCRIPTION, logUserIdentification);
_ttvContext.FactFieldValues.Add(factFieldValueResearcherDescription);
}
}
catch (Exception ex)
{
_logger.LogError(
LogContent.MESSAGE_TEMPLATE,
logUserIdentification,
new LogApiInfo(
action: LogContent.Action.PROFILE_ADD_TTV_DATA,
state: LogContent.ActionState.FAILED,
error: true,
message: $"dim_user_profile.id={dimUserProfile.Id}, researcher description: {ex.ToString()}"));
}
// affiliation
try
{
string affiliationSql = _ttvSqlService.GetSqlQuery_Select_DimAffiliation(dimKnownPerson.Id, existingAffiliationIds);
List<DimTableMinimalDTO> affiliations = (await connection.QueryAsync<DimTableMinimalDTO>(affiliationSql)).ToList();
DimFieldDisplaySetting dimFieldDisplaySetting_affiliation =
dimUserProfile.DimFieldDisplaySettings.Where(dfds => dfds.FieldIdentifier == Constants.FieldIdentifiers.ACTIVITY_AFFILIATION).First();
foreach (DimTableMinimalDTO affiliation in affiliations)
{
FactFieldValue factFieldValueAffiliation = this.GetEmptyFactFieldValue();
factFieldValueAffiliation.DimUserProfileId = dimUserProfile.Id;
factFieldValueAffiliation.DimFieldDisplaySettingsId = dimFieldDisplaySetting_affiliation.Id;
factFieldValueAffiliation.DimAffiliationId = affiliation.Id;
factFieldValueAffiliation.DimRegisteredDataSourceId = affiliation.DimRegisteredDataSourceId;
factFieldValueAffiliation.Show = this.SetFactFieldValuesShow(dimUserProfile, Constants.FieldIdentifiers.ACTIVITY_AFFILIATION, logUserIdentification);
_ttvContext.FactFieldValues.Add(factFieldValueAffiliation);
}
}
catch (Exception ex)
{
_logger.LogError(
LogContent.MESSAGE_TEMPLATE,
logUserIdentification,
new LogApiInfo(
action: LogContent.Action.PROFILE_ADD_TTV_DATA,
state: LogContent.ActionState.FAILED,
error: true,
message: $"dim_user_profile.id={dimUserProfile.Id}, affiliation: {ex.ToString()}"));
}
// education
try
{
string educationSql = _ttvSqlService.GetSqlQuery_Select_DimEducation(dimKnownPerson.Id, existingEducationIds);
List<DimTableMinimalDTO> educations = (await connection.QueryAsync<DimTableMinimalDTO>(educationSql)).ToList();
DimFieldDisplaySetting dimFieldDisplaySetting_education =
dimUserProfile.DimFieldDisplaySettings.Where(dfds => dfds.FieldIdentifier == Constants.FieldIdentifiers.ACTIVITY_EDUCATION).First();
foreach (DimTableMinimalDTO education in educations)
{
FactFieldValue factFieldValueEducation = this.GetEmptyFactFieldValue();
factFieldValueEducation.DimUserProfileId = dimUserProfile.Id;
factFieldValueEducation.DimFieldDisplaySettingsId = dimFieldDisplaySetting_education.Id;
factFieldValueEducation.DimEducationId = education.Id;
factFieldValueEducation.DimRegisteredDataSourceId = education.DimRegisteredDataSourceId;
factFieldValueEducation.Show = this.SetFactFieldValuesShow(dimUserProfile, Constants.FieldIdentifiers.ACTIVITY_EDUCATION, logUserIdentification);
_ttvContext.FactFieldValues.Add(factFieldValueEducation);
}
}
catch (Exception ex)
{
_logger.LogError(
LogContent.MESSAGE_TEMPLATE,
logUserIdentification,
new LogApiInfo(
action: LogContent.Action.PROFILE_ADD_TTV_DATA,
state: LogContent.ActionState.FAILED,
error: true,
message: $"dim_user_profile.id={dimUserProfile.Id}, education: {ex.ToString()}"));
}
DimFieldDisplaySetting dimFieldDisplaySetting_name =
dimUserProfile.DimFieldDisplaySettings.Where(dfds => dfds.FieldIdentifier == Constants.FieldIdentifiers.PERSON_NAME).First();
DimFieldDisplaySetting dimFieldDisplaySetting_otherNames =
dimUserProfile.DimFieldDisplaySettings.Where(dfds => dfds.FieldIdentifier == Constants.FieldIdentifiers.PERSON_OTHER_NAMES).First();
DimFieldDisplaySetting dimFieldDisplaySetting_publication =
dimUserProfile.DimFieldDisplaySettings.Where(dfds => dfds.FieldIdentifier == Constants.FieldIdentifiers.ACTIVITY_PUBLICATION).First();
DimFieldDisplaySetting dimFieldDisplaySetting_fundingDecision =
dimUserProfile.DimFieldDisplaySettings.Where(dfds => dfds.FieldIdentifier == Constants.FieldIdentifiers.ACTIVITY_FUNDING_DECISION).First();
DimFieldDisplaySetting dimFieldDisplaySetting_researchActivity =
dimUserProfile.DimFieldDisplaySettings.Where(dfds => dfds.FieldIdentifier == Constants.FieldIdentifiers.ACTIVITY_RESEARCH_ACTIVITY).First();
DimFieldDisplaySetting dimFieldDisplaySetting_researchDataset =
dimUserProfile.DimFieldDisplaySettings.Where(dfds => dfds.FieldIdentifier == Constants.FieldIdentifiers.ACTIVITY_RESEARCH_DATASET).First();
// Loop DimNames, which have valid registered data source
foreach (DimName dimName in dimKnownPerson.DimNames.Where(dimName => dimName.DimRegisteredDataSourceId != -1))
{
// Name
// Exclude DimNames which are already in user profile or have a specific registered data source (see CanIncludeDimNameInUserProfile)
if (CanIncludeDimNameInUserProfile(existingNameIds, dimName))
{
if (!String.IsNullOrWhiteSpace(dimName.FirstNames) && !String.IsNullOrWhiteSpace(dimName.LastName))
{
// name: first_names & last_name
FactFieldValue factFieldValueName = this.GetEmptyFactFieldValue();
factFieldValueName.DimUserProfileId = dimUserProfile.Id;
factFieldValueName.DimFieldDisplaySettingsId = dimFieldDisplaySetting_name.Id;
factFieldValueName.DimNameId = dimName.Id;
factFieldValueName.DimRegisteredDataSourceId = dimName.DimRegisteredDataSourceId;
factFieldValueName.Show = this.SetFactFieldValuesShow(dimUserProfile, Constants.FieldIdentifiers.PERSON_NAME, logUserIdentification);
_ttvContext.FactFieldValues.Add(factFieldValueName);
}
else if (!String.IsNullOrWhiteSpace(dimName.FullName))
{
// other name: full_name
FactFieldValue factFieldValueOtherNames = this.GetEmptyFactFieldValue();
factFieldValueOtherNames.DimUserProfileId = dimUserProfile.Id;
factFieldValueOtherNames.DimFieldDisplaySettingsId = dimFieldDisplaySetting_otherNames.Id;
factFieldValueOtherNames.DimNameId = dimName.Id;
factFieldValueOtherNames.DimRegisteredDataSourceId = dimName.DimRegisteredDataSourceId;
factFieldValueOtherNames.Show = this.SetFactFieldValuesShow(dimUserProfile, Constants.FieldIdentifiers.PERSON_OTHER_NAMES, logUserIdentification);
_ttvContext.FactFieldValues.Add(factFieldValueOtherNames);
}
}
// fact_contribution
try
{
string factContributionSql = _ttvSqlService.GetSqlQuery_Select_FactContribution(dimName.Id);
List<FactContributionTableMinimalDTO> factContributions = (await connection.QueryAsync<FactContributionTableMinimalDTO>(factContributionSql)).ToList();
// Loop FactContributions related to a DimName. Add entries to user profile. Exclude already existing IDs.
foreach (FactContributionTableMinimalDTO fc in factContributions)
{
// publication
//
// Co-publications have multiple rows in table fact_contribution. Here only the "main" publication should be included.
// If FactContributionTableMinimalDTO.CoPublication_Parent_DimPublicationId has value (other than -1), that must be used.
// Otherwise FactContributionTableMinimalDTO.DimPublicationId must be used.
int publicationId = fc.CoPublication_Parent_DimPublicationId > 0 ? fc.CoPublication_Parent_DimPublicationId : fc.DimPublicationId;
if (publicationId != -1 && !existingPublicationIds.Contains(publicationId))
{
FactFieldValue factFieldValuePublication = this.GetEmptyFactFieldValue();
factFieldValuePublication.DimUserProfileId = dimUserProfile.Id;
factFieldValuePublication.DimFieldDisplaySettingsId = dimFieldDisplaySetting_publication.Id;
factFieldValuePublication.DimPublicationId = publicationId;
factFieldValuePublication.DimRegisteredDataSourceId = dimName.DimRegisteredDataSourceId;
factFieldValuePublication.Show = this.SetFactFieldValuesShow(dimUserProfile, Constants.FieldIdentifiers.ACTIVITY_PUBLICATION, logUserIdentification);
_ttvContext.FactFieldValues.Add(factFieldValuePublication);
// Prevent duplicate key error with publications
existingPublicationIds.Add(publicationId);
}
// research activity
if (fc.DimResearchActivityId != -1 && !existingResearchActivityIds.Contains(fc.DimResearchActivityId))
{
FactFieldValue factFieldValueResearchActivity = this.GetEmptyFactFieldValue();
factFieldValueResearchActivity.DimUserProfileId = dimUserProfile.Id;
factFieldValueResearchActivity.DimFieldDisplaySettingsId = dimFieldDisplaySetting_researchActivity.Id;
factFieldValueResearchActivity.DimResearchActivityId = fc.DimResearchActivityId;
factFieldValueResearchActivity.DimRegisteredDataSourceId = dimName.DimRegisteredDataSourceId;
factFieldValueResearchActivity.Show = this.SetFactFieldValuesShow(dimUserProfile, Constants.FieldIdentifiers.ACTIVITY_RESEARCH_ACTIVITY, logUserIdentification);
_ttvContext.FactFieldValues.Add(factFieldValueResearchActivity);
// Prevent duplicate key error with research activities
existingResearchActivityIds.Add(fc.DimResearchActivityId);
}
// research dataset
if (fc.DimResearchDatasetId != -1 && !existingResearchDatasetIds.Contains(fc.DimResearchDatasetId))
{
FactFieldValue factFieldValueResearchDataset = this.GetEmptyFactFieldValue();
factFieldValueResearchDataset.DimUserProfileId = dimUserProfile.Id;
factFieldValueResearchDataset.DimFieldDisplaySettingsId = dimFieldDisplaySetting_researchDataset.Id;
factFieldValueResearchDataset.DimResearchDatasetId = fc.DimResearchDatasetId;