diff --git a/src/app/core/interceptors/error.interceptor.spec.ts b/src/app/core/interceptors/error.interceptor.spec.ts index 951e22394..68b73a2b9 100644 --- a/src/app/core/interceptors/error.interceptor.spec.ts +++ b/src/app/core/interceptors/error.interceptor.spec.ts @@ -295,6 +295,34 @@ describe('errorInterceptor', () => { expect(toastServiceMock.showError).not.toHaveBeenCalled(); }); + it('should navigate to request-access for 403 node URL with trailing slash and query', async () => { + setup('browser', false, '/projects/abc'); + const request = createRequest('/api/v2/nodes/abc/?related_counts=forks'); + const error = new HttpErrorResponse({ + status: 403, + error: {}, + url: '/api/v2/nodes/abc/?related_counts=forks', + }); + + const caught = await runInterceptor(request, error); + + expect(caught?.status).toBe(403); + expect(router.navigate).toHaveBeenCalledWith(['/request-access', 'abc']); + }); + + it('should not redirect on 403 for node relationship URL', async () => { + setup('browser', false, '/projects/abc'); + const request = createRequest('/api/v2/nodes/abc/preprints/'); + const error = new HttpErrorResponse({ status: 403, error: {}, url: '/api/v2/nodes/abc/preprints/' }); + + const caught = await runInterceptor(request, error); + + expect(caught?.status).toBe(403); + expect(router.navigate).not.toHaveBeenCalled(); + expect(loaderServiceMock.hide).toHaveBeenCalled(); + expect(toastServiceMock.showError).not.toHaveBeenCalled(); + }); + it('should navigate to forbidden for 403 without a node URL', async () => { setup(); const request = createRequest('/api/v2/users/me/'); @@ -308,6 +336,18 @@ describe('errorInterceptor', () => { expect(toastServiceMock.showError).not.toHaveBeenCalled(); }); + it('should not set SSR response status for node relationship 403', async () => { + setup('server'); + const request = createRequest('/api/v2/nodes/abc/preprints/'); + const error = new HttpErrorResponse({ status: 403, error: {}, url: '/api/v2/nodes/abc/preprints/' }); + + const caught = await runInterceptor(request, error); + + expect(caught?.status).toBe(403); + expect(responseInit.status).toBeUndefined(); + expect(router.navigate).not.toHaveBeenCalled(); + }); + it('should not redirect on 403 when current route is a draft registry', async () => { setup('browser', false, '/registries/drafts/abc'); const request = createRequest('/api/v2/nodes/abc'); diff --git a/src/app/core/interceptors/error.interceptor.ts b/src/app/core/interceptors/error.interceptor.ts index 1709438d0..952ee58e2 100644 --- a/src/app/core/interceptors/error.interceptor.ts +++ b/src/app/core/interceptors/error.interceptor.ts @@ -26,7 +26,8 @@ import { BYPASS_ERROR_INTERCEPTOR } from './error-interceptor.tokens'; const NO_AUTH_REDIRECT_HEADER = 'X-No-Auth-Redirect'; const REQUEST_ACCESS_URL_REGEX = /\/v2\/nodes\/[^/]+\/requests\/?$/i; -const NODE_ID_URL_REGEX = /\/v2\/nodes\/([^/]+)/; +const NODE_RESOURCE_URL_REGEX = /\/v2\/nodes\/([^/?]+)\/?(?:\?|$)/i; +const NODE_RELATED_URL_REGEX = /\/v2\/nodes\/[^/?]+\/[^?]/i; const DRAFT_REGISTRY_ROUTE_REGEX = /\/registries\/drafts\/.+/i; const isSilentForbidden = (req: HttpRequest, error: HttpErrorResponse): boolean => @@ -35,6 +36,11 @@ const isSilentForbidden = (req: HttpRequest, error: HttpErrorResponse): const isPendingModerationForbidden = (error: HttpErrorResponse): boolean => error.error?.errors?.[0]?.detail === PREPRINT_PENDING_MODERATION_DETAIL; +const getNodeResourceId = (url: string | null | undefined): string | undefined => + url?.match(NODE_RESOURCE_URL_REGEX)?.[1]; + +const isNodeRelatedUrl = (url: string | null | undefined): boolean => !!url && NODE_RELATED_URL_REGEX.test(url); + const getErrorMessage = (error: HttpErrorResponse): string => { if (error.error instanceof ErrorEvent) { return error.error.message; @@ -76,20 +82,24 @@ export const errorInterceptor: HttpInterceptorFn = (req, next) => { }; const handleForbidden = (url: string | null) => { - const nodeId = url?.match(NODE_ID_URL_REGEX)?.[1]; + const nodeId = getNodeResourceId(url); - if (!nodeId) { - router.navigate(['/forbidden']); - } else if (!DRAFT_REGISTRY_ROUTE_REGEX.test(router.url)) { - router.navigate(['/request-access', nodeId]); + if (nodeId) { + if (!DRAFT_REGISTRY_ROUTE_REGEX.test(router.url)) { + router.navigate(['/request-access', nodeId]); + } + return; } + + router.navigate(['/forbidden']); }; const applySsrStatus = (error: HttpErrorResponse) => { if ( req.context.get(BYPASS_ERROR_INTERCEPTOR) || !shouldPropagateHttpStatusToSsr(error.status) || - isSilentForbidden(req, error) + isSilentForbidden(req, error) || + (error.status === 403 && isNodeRelatedUrl(error.url)) ) { return; } @@ -122,7 +132,7 @@ export const errorInterceptor: HttpInterceptorFn = (req, next) => { handleUnauthorized(); break; case 403: - if (!isSilentForbidden(req, error) && !isPendingModerationForbidden(error)) { + if (!isSilentForbidden(req, error) && !isPendingModerationForbidden(error) && !isNodeRelatedUrl(error.url)) { handleForbidden(error.url); } break; diff --git a/src/app/features/collections/components/add-to-collection/add-to-collection.component.html b/src/app/features/collections/components/add-to-collection/add-to-collection.component.html index a4cd6f026..923c7d081 100644 --- a/src/app/features/collections/components/add-to-collection/add-to-collection.component.html +++ b/src/app/features/collections/components/add-to-collection/add-to-collection.component.html @@ -29,7 +29,6 @@

{{ collectionProvider()? [stepperActiveValue]="stepperActiveValue()" [targetStepValue]="AddToCollectionSteps.ProjectMetadata" [isDisabled]="isProjectMetadataDisabled()" - [providerId]="providerId()" (metadataSaved)="handleProjectMetadataSaved()" (stepChange)="handleChangeStep($event)" /> diff --git a/src/app/features/collections/components/add-to-collection/add-to-collection.component.spec.ts b/src/app/features/collections/components/add-to-collection/add-to-collection.component.spec.ts index 8062f0dde..a4710cdd3 100644 --- a/src/app/features/collections/components/add-to-collection/add-to-collection.component.spec.ts +++ b/src/app/features/collections/components/add-to-collection/add-to-collection.component.spec.ts @@ -5,12 +5,7 @@ import { of, Subject, throwError } from 'rxjs'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ActivatedRoute, Router } from '@angular/router'; -import { UserSelectors } from '@core/store/user'; -import { CollectionMetadataStepComponent } from '@osf/features/collections/components/add-to-collection/collection-metadata-step/collection-metadata-step.component'; -import { ProjectContributorsStepComponent } from '@osf/features/collections/components/add-to-collection/project-contributors-step/project-contributors-step.component'; -import { ProjectMetadataStepComponent } from '@osf/features/collections/components/add-to-collection/project-metadata-step/project-metadata-step.component'; -import { SelectProjectStepComponent } from '@osf/features/collections/components/add-to-collection/select-project-step/select-project-step.component'; -import { AddToCollectionSteps } from '@osf/features/collections/enums'; +import { UserSelectors } from '@osf/core/store/user'; import { CedarRecordDataBinding } from '@osf/features/metadata/models'; import { MetadataSelectors } from '@osf/features/metadata/store'; import { LoadingSpinnerComponent } from '@osf/shared/components/loading-spinner/loading-spinner.component'; @@ -19,8 +14,8 @@ import { CustomDialogService } from '@osf/shared/services/custom-dialog.service' import { HeaderStyleService } from '@osf/shared/services/header-style.service'; import { LoaderService } from '@osf/shared/services/loader.service'; import { ToastService } from '@osf/shared/services/toast.service'; -import { CollectionsSelectors } from '@shared/stores/collections'; -import { ProjectsSelectors } from '@shared/stores/projects/projects.selectors'; +import { CollectionsSelectors } from '@osf/shared/stores/collections'; +import { ProjectsSelectors } from '@osf/shared/stores/projects'; import { MOCK_USER } from '@testing/mocks/data.mock'; import { MOCK_PROJECT } from '@testing/mocks/project.mock'; @@ -38,8 +33,13 @@ import { RouterMockBuilder } from '@testing/providers/router-provider.mock'; import { mergeSignalOverrides, provideMockStore, SignalOverride } from '@testing/providers/store-provider.mock'; import { ToastServiceMock } from '@testing/providers/toast-provider.mock'; +import { AddToCollectionSteps } from '../../enums'; import { AddToCollectionSelectors } from '../../store/add-to-collection'; +import { CollectionMetadataStepComponent } from './collection-metadata-step/collection-metadata-step.component'; +import { ProjectContributorsStepComponent } from './project-contributors-step/project-contributors-step.component'; +import { ProjectMetadataStepComponent } from './project-metadata-step/project-metadata-step.component'; +import { SelectProjectStepComponent } from './select-project-step/select-project-step.component'; import { AddToCollectionComponent } from './add-to-collection.component'; const mockCollectionProvider = MOCK_PROVIDER; @@ -138,11 +138,6 @@ describe('AddToCollectionComponent', () => { expect(mockRouter.navigate).toHaveBeenCalledWith(['/not-found']); }); - it('should set providerId and dispatch getCollectionProvider when providerId is present', () => { - const { component } = setup({ routeParams: { providerId: 'provider-1' } }); - expect(component.providerId()).toBe('provider-1'); - }); - it('should handle project selection', () => { const { component } = setup(); component.handleProjectSelected(); diff --git a/src/app/features/collections/components/add-to-collection/add-to-collection.component.ts b/src/app/features/collections/components/add-to-collection/add-to-collection.component.ts index f52a209a9..292062365 100644 --- a/src/app/features/collections/components/add-to-collection/add-to-collection.component.ts +++ b/src/app/features/collections/components/add-to-collection/add-to-collection.component.ts @@ -105,7 +105,6 @@ export class AddToCollectionComponent implements CanDeactivateComponent { isProjectReadOnly = select(UserSelectors.isProjectReadOnly); cedarRecords = select(MetadataSelectors.getCedarRecords); - providerId = signal(''); allowNavigation = signal(false); projectMetadataSaved = signal(false); projectContributorsSaved = signal(false); @@ -298,7 +297,6 @@ export class AddToCollectionComponent implements CanDeactivateComponent { return; } - this.providerId.set(id); this.actions.getCollectionProvider(id); } diff --git a/src/app/features/collections/components/add-to-collection/collection-metadata-step/collection-metadata-step.component.spec.ts b/src/app/features/collections/components/add-to-collection/collection-metadata-step/collection-metadata-step.component.spec.ts index 0a65b99f0..5cf55d01c 100644 --- a/src/app/features/collections/components/add-to-collection/collection-metadata-step/collection-metadata-step.component.spec.ts +++ b/src/app/features/collections/components/add-to-collection/collection-metadata-step/collection-metadata-step.component.spec.ts @@ -4,7 +4,11 @@ import { Step, StepItem, StepPanel } from 'primeng/stepper'; import { ComponentFixture, TestBed } from '@angular/core/testing'; -import { CedarMetadataRecordModel, CedarMetadataTemplateModel } from '@osf/features/metadata/models'; +import { + CedarEditorElement, + CedarMetadataRecordModel, + CedarMetadataTemplateModel, +} from '@osf/features/metadata/models'; import { MOCK_CEDAR_RECORD } from '@testing/data/collections/cedar-metadata.mock'; import { MOCK_CEDAR_METADATA_TEMPLATE } from '@testing/mocks/cedar-metadata-domain.mock'; @@ -26,6 +30,7 @@ describe('CollectionMetadataStepComponent', () => { stepperActiveValue?: number; targetStepValue?: number; isDisabled?: boolean; + editor?: CedarEditorElement; } = {} ) { TestBed.configureTestingModule({ @@ -36,6 +41,10 @@ describe('CollectionMetadataStepComponent', () => { fixture = TestBed.createComponent(CollectionMetadataStepComponent); component = fixture.componentInstance; + if (options.editor) { + vi.spyOn(component, 'cedarEditor').mockReturnValue({ nativeElement: options.editor } as never); + } + fixture.componentRef.setInput('stepperActiveValue', options.stepperActiveValue ?? 0); fixture.componentRef.setInput('targetStepValue', options.targetStepValue ?? 1); fixture.componentRef.setInput('isDisabled', options.isDisabled ?? false); @@ -121,6 +130,53 @@ describe('CollectionMetadataStepComponent', () => { expect(component.cedarFormData()).toEqual({ field: 'value' }); }); + it('should load existing record metadata with the template and then on its own to keep checkbox answers when step opens', () => { + const editor = {} as CedarEditorElement; + setup({ + cedarTemplate: mockCedarTemplate, + existingCedarRecord: MOCK_CEDAR_RECORD, + stepperActiveValue: 1, + editor, + }); + + expect(Object.keys(editor)).toEqual(['templateAndInstanceObject', 'instanceObject']); + expect(editor.templateAndInstanceObject).toEqual({ + templateObject: mockCedarTemplate.template, + instanceObject: { field: 'value' }, + }); + expect(editor.instanceObject).toEqual({ field: 'value' }); + }); + + it('should load saved metadata together with template when step is reopened', () => { + const editor = {} as CedarEditorElement; + setup({ cedarTemplate: mockCedarTemplate, editor }); + + component.cedarFormData.set({ field: 'saved' }); + component.collectionMetadataSaved.set(true); + fixture.componentRef.setInput('stepperActiveValue', 1); + fixture.detectChanges(); + + expect(editor.templateAndInstanceObject).toEqual({ + templateObject: mockCedarTemplate.template, + instanceObject: { field: 'saved' }, + }); + expect(editor.instanceObject).toEqual({ field: 'saved' }); + }); + + it('should load existing record metadata together with template on discard', () => { + const editor = {} as CedarEditorElement; + setup({ cedarTemplate: mockCedarTemplate, existingCedarRecord: MOCK_CEDAR_RECORD, editor }); + + component.cedarFormData.set({ field: 'edited' }); + component.handleDiscardChanges(); + + expect(editor.templateAndInstanceObject).toEqual({ + templateObject: mockCedarTemplate.template, + instanceObject: { field: 'value' }, + }); + expect(editor.instanceObject).toEqual({ field: 'value' }); + }); + it('should populate cedarFormData from existingCedarRecord', () => { setup({ cedarTemplate: mockCedarTemplate, diff --git a/src/app/features/collections/components/add-to-collection/collection-metadata-step/collection-metadata-step.component.ts b/src/app/features/collections/components/add-to-collection/collection-metadata-step/collection-metadata-step.component.ts index d383908ec..2bf9c4689 100644 --- a/src/app/features/collections/components/add-to-collection/collection-metadata-step/collection-metadata-step.component.ts +++ b/src/app/features/collections/components/add-to-collection/collection-metadata-step/collection-metadata-step.component.ts @@ -69,7 +69,7 @@ export class CollectionMetadataStepComponent { handleDiscardChanges() { const record = this.existingCedarRecord(); this.cedarFormData.set(record?.metadata ? (record.metadata as Record) : {}); - this.syncCedarInstance(this.cedarEditor()?.nativeElement); + this.syncCedarEditor(); this.collectionMetadataSaved.set(false); } @@ -124,7 +124,7 @@ export class CollectionMetadataStepComponent { if (!record?.metadata && !saved) return; - this.syncCedarInstance(this.cedarEditor()?.nativeElement); + this.syncCedarEditor(); }); effect(() => { @@ -133,6 +133,18 @@ export class CollectionMetadataStepComponent { }); } + private syncCedarEditor(): void { + const editor = this.cedarEditor()?.nativeElement; + const template = this.cedarTemplate()?.template; + if (editor && template) { + editor.templateAndInstanceObject = { + templateObject: template, + instanceObject: untracked(() => this.cedarFormData()), + }; + this.syncCedarInstance(editor); + } + } + private syncCedarInstance(element: CedarEditorElement | undefined): void { if (element) { element.instanceObject = untracked(() => this.cedarFormData()); diff --git a/src/app/features/collections/components/add-to-collection/project-metadata-step/project-metadata-step.component.html b/src/app/features/collections/components/add-to-collection/project-metadata-step/project-metadata-step.component.html index 01e9f6508..b602967d1 100644 --- a/src/app/features/collections/components/add-to-collection/project-metadata-step/project-metadata-step.component.html +++ b/src/app/features/collections/components/add-to-collection/project-metadata-step/project-metadata-step.component.html @@ -38,10 +38,10 @@

{{ 'collections.addToCollection.resourceMetadata' | translate }}

} @@ -141,16 +141,16 @@

{{ 'collections.addToCollection.resourceMetadata' | translate }}

diff --git a/src/app/features/collections/components/add-to-collection/project-metadata-step/project-metadata-step.component.spec.ts b/src/app/features/collections/components/add-to-collection/project-metadata-step/project-metadata-step.component.spec.ts index 77eabd4aa..8bea9428a 100644 --- a/src/app/features/collections/components/add-to-collection/project-metadata-step/project-metadata-step.component.spec.ts +++ b/src/app/features/collections/components/add-to-collection/project-metadata-step/project-metadata-step.component.spec.ts @@ -1,118 +1,205 @@ +import { Store } from '@ngxs/store'; + import { MockComponents, MockPipe, MockProvider } from 'ng-mocks'; +import { Step, StepItem, StepPanel } from 'primeng/stepper'; + +import { Mock } from 'vitest'; + +import { signal, WritableSignal } from '@angular/core'; import { ComponentFixture, TestBed } from '@angular/core/testing'; -import { AddToCollectionSelectors } from '@osf/features/collections/store/add-to-collection'; +import { AddToCollectionSteps } from '@osf/features/collections/enums'; +import { AddToCollectionSelectors, GetCollectionLicenses } from '@osf/features/collections/store/add-to-collection'; import { TagsInputComponent } from '@osf/shared/components/tags-input/tags-input.component'; import { TextInputComponent } from '@osf/shared/components/text-input/text-input.component'; import { TruncatedTextComponent } from '@osf/shared/components/truncated-text/truncated-text.component'; +import { ResourceType } from '@osf/shared/enums/resource-type.enum'; +import { LicenseModel } from '@osf/shared/models/license/license.model'; +import { InterpolatePipe } from '@osf/shared/pipes/interpolate.pipe'; import { ToastService } from '@osf/shared/services/toast.service'; -import { InterpolatePipe } from '@shared/pipes/interpolate.pipe'; -import { ProjectsSelectors } from '@shared/stores/projects/projects.selectors'; +import { CollectionsSelectors } from '@osf/shared/stores/collections'; +import { GetAllContributors } from '@osf/shared/stores/contributors'; +import { ClearProjects, ProjectsSelectors } from '@osf/shared/stores/projects'; import { MOCK_PROJECT } from '@testing/mocks/project.mock'; +import { MOCK_PROVIDER } from '@testing/mocks/provider.mock'; import { provideOSFCore } from '@testing/osf.testing.provider'; -import { provideMockStore } from '@testing/providers/store-provider.mock'; +import { + BaseSetupOverrides, + mergeSignalOverrides, + provideMockStore, + SignalOverride, +} from '@testing/providers/store-provider.mock'; import { ToastServiceMockBuilder } from '@testing/providers/toast-provider.mock'; import { ProjectMetadataStepComponent } from './project-metadata-step.component'; -describe.skip('ProjectMetadataStepComponent', () => { +const MOCK_LICENSE: LicenseModel = { + id: 'MIT', + name: 'MIT License', + requiredFields: [], + url: '', + text: '', +}; + +const MOCK_COLLECTION_PROVIDER = { + ...MOCK_PROVIDER, + licensesLink: 'https://api.osf.io/v2/providers/collections/1/licenses/', + defaultLicenseId: null, +}; + +interface SetupOverrides extends BaseSetupOverrides { + project?: typeof MOCK_PROJECT | null; + licenses?: LicenseModel[]; + provider?: typeof MOCK_COLLECTION_PROVIDER | null; +} + +describe('ProjectMetadataStepComponent', () => { let component: ProjectMetadataStepComponent; let fixture: ComponentFixture; - let toastServiceMock: ReturnType; + let store: Store; + let licensesSignal: WritableSignal; + + function setup(overrides: SetupOverrides = {}) { + const project = 'project' in overrides ? overrides.project! : MOCK_PROJECT; + const licenses = overrides.licenses ?? []; + const provider = 'provider' in overrides ? overrides.provider! : MOCK_COLLECTION_PROVIDER; + const toastServiceMock = ToastServiceMockBuilder.create().build(); + + licensesSignal = signal(licenses); - beforeEach(() => { - toastServiceMock = ToastServiceMockBuilder.create().build(); + const defaultSignals: SignalOverride[] = [ + { selector: ProjectsSelectors.getSelectedProject, value: project }, + { selector: CollectionsSelectors.getCollectionProvider, value: provider }, + { selector: AddToCollectionSelectors.getCollectionLicenses, value: licensesSignal }, + { selector: ProjectsSelectors.getSelectedProjectUpdateSubmitting, value: false }, + ]; TestBed.configureTestingModule({ imports: [ ProjectMetadataStepComponent, - ...MockComponents(TagsInputComponent, TextInputComponent, TruncatedTextComponent), + ...MockComponents(TagsInputComponent, TextInputComponent, TruncatedTextComponent, StepPanel, Step, StepItem), MockPipe(InterpolatePipe), ], providers: [ provideOSFCore(), MockProvider(ToastService, toastServiceMock), provideMockStore({ - signals: [ - { selector: ProjectsSelectors.getSelectedProject, value: MOCK_PROJECT }, - { selector: AddToCollectionSelectors.getCollectionLicenses, value: [] }, - { selector: ProjectsSelectors.getSelectedProjectUpdateSubmitting, value: false }, - ], + signals: mergeSignalOverrides(defaultSignals, overrides.selectorOverrides), }), ], }); + store = TestBed.inject(Store); fixture = TestBed.createComponent(ProjectMetadataStepComponent); component = fixture.componentInstance; fixture.componentRef.setInput('stepperActiveValue', 0); - fixture.componentRef.setInput('targetStepValue', 2); + fixture.componentRef.setInput('targetStepValue', AddToCollectionSteps.ProjectMetadata); fixture.componentRef.setInput('isDisabled', false); - fixture.componentRef.setInput('providerId', 'id1'); - fixture.detectChanges(); - }); + } - it('should create', () => { - expect(component).toBeTruthy(); - }); + it('should create with required inputs', () => { + setup(); - it('should initialize with input values', () => { + expect(component).toBeTruthy(); expect(component.stepperActiveValue()).toBe(0); - expect(component.targetStepValue()).toBe(2); + expect(component.targetStepValue()).toBe(AddToCollectionSteps.ProjectMetadata); expect(component.isDisabled()).toBe(false); - expect(component.providerId()).toBe('id1'); }); - it('should handle tags change', () => { - const mockTags = ['tag1', 'tag2', 'tag3']; + it('should dispatch GetCollectionLicenses with provider licensesLink when licenses are empty', () => { + setup({ licenses: [] }); + + expect(store.dispatch).toHaveBeenCalledWith(new GetCollectionLicenses(MOCK_COLLECTION_PROVIDER.licensesLink)); + }); + + it('should not dispatch GetCollectionLicenses when licenses are already loaded', () => { + setup({ licenses: [MOCK_LICENSE] }); - component.handleTagsChange(mockTags); + expect(store.dispatch).not.toHaveBeenCalledWith(expect.any(GetCollectionLicenses)); + }); + + it('should resolve projectLicense from collection licenses by project licenseId', () => { + setup({ licenses: [MOCK_LICENSE] }); - expect(component.projectTags()).toEqual(mockTags); + expect(component.projectLicense()).toEqual(MOCK_LICENSE); + expect(component.selectedLicense()).toEqual(MOCK_LICENSE); }); - it('should handle discard changes', () => { + it('should return null projectLicense when project is missing', () => { + setup({ project: null, licenses: [MOCK_LICENSE] }); + + expect(component.projectLicense()).toBeNull(); + }); + + it('should update tags on handleTagsChange', () => { + setup({ licenses: [MOCK_LICENSE] }); + component.handleTagsChange(['tag1', 'tag2']); + expect(component.projectTags()).toEqual(['tag1', 'tag2']); + }); + it('should restore project tags on discard changes', () => { + setup({ licenses: [MOCK_LICENSE] }); + + component.handleTagsChange(['changed']); component.handleDiscardChanges(); - expect(component).toBeTruthy(); + expect(component.projectTags()).toEqual(MOCK_PROJECT.tags); }); - it('should handle edit step', () => { + it('should emit stepChange on handleEditStep', () => { + setup(); const stepChangeSpy = vi.spyOn(component.stepChange, 'emit'); component.handleEditStep(); - expect(stepChangeSpy).toHaveBeenCalledWith(component.targetStepValue()); + expect(stepChangeSpy).toHaveBeenCalledWith(AddToCollectionSteps.ProjectMetadata); }); - it('should handle different input values', () => { - fixture.componentRef.setInput('stepperActiveValue', 1); - fixture.componentRef.setInput('targetStepValue', 3); - fixture.componentRef.setInput('isDisabled', true); - fixture.componentRef.setInput('providerId', 'id2'); - fixture.detectChanges(); + it('should select license from select change event', () => { + setup({ licenses: [MOCK_LICENSE] }); + const otherLicense: LicenseModel = { ...MOCK_LICENSE, id: 'CC0', name: 'CC0' }; + + component.handleSelectCollectionLicense({ value: otherLicense } as never); - expect(component.stepperActiveValue()).toBe(1); - expect(component.targetStepValue()).toBe(3); - expect(component.isDisabled()).toBe(true); - expect(component.providerId()).toBe('id2'); + expect(component.selectedLicense()).toEqual(otherLicense); }); - it('should initialize selected license as null', () => { - expect(component.selectedLicense()).toBe(null); + it('should proceed to contributors step when metadata is unchanged', () => { + setup({ licenses: [MOCK_LICENSE] }); + (store.dispatch as Mock).mockClear(); + const stepChangeSpy = vi.spyOn(component.stepChange, 'emit'); + const metadataSavedSpy = vi.spyOn(component.metadataSaved, 'emit'); + + component.handleUpdateMetadata(); + + expect(stepChangeSpy).toHaveBeenCalledWith(AddToCollectionSteps.ProjectContributors); + expect(store.dispatch).toHaveBeenCalledWith(new GetAllContributors(MOCK_PROJECT.id, ResourceType.Project)); + expect(metadataSavedSpy).toHaveBeenCalled(); }); - it('should have project metadata form', () => { - expect(component.projectMetadataForm).toBeDefined(); + it('should not update metadata when project is missing', () => { + setup({ project: null }); + (store.dispatch as Mock).mockClear(); + const stepChangeSpy = vi.spyOn(component.stepChange, 'emit'); + + component.handleUpdateMetadata(); + + expect(stepChangeSpy).not.toHaveBeenCalled(); + expect(store.dispatch).not.toHaveBeenCalledWith(expect.any(GetAllContributors)); }); - it('should have computed project license', () => { - expect(component.projectLicense()).toBeDefined(); + it('should dispatch ClearProjects on destroy', () => { + setup(); + (store.dispatch as Mock).mockClear(); + + fixture.destroy(); + + expect(store.dispatch).toHaveBeenCalledWith(new ClearProjects()); }); }); diff --git a/src/app/features/collections/components/add-to-collection/project-metadata-step/project-metadata-step.component.ts b/src/app/features/collections/components/add-to-collection/project-metadata-step/project-metadata-step.component.ts index 4f38ab5dc..ab3ebd894 100644 --- a/src/app/features/collections/components/add-to-collection/project-metadata-step/project-metadata-step.component.ts +++ b/src/app/features/collections/components/add-to-collection/project-metadata-step/project-metadata-step.component.ts @@ -28,7 +28,7 @@ import { untracked, } from '@angular/core'; import { takeUntilDestroyed, toSignal } from '@angular/core/rxjs-interop'; -import { FormGroup, FormsModule, ReactiveFormsModule } from '@angular/forms'; +import { FormGroup, ReactiveFormsModule } from '@angular/forms'; import { AddToCollectionSteps, ProjectMetadataFormControls } from '@osf/features/collections/enums'; import { ProjectMetadataForm } from '@osf/features/collections/models/project-metadata-form.model'; @@ -54,7 +54,6 @@ import { CollectionsSelectors } from '@shared/stores/collections'; TranslatePipe, ReactiveFormsModule, Textarea, - FormsModule, TagsInputComponent, Chip, Card, @@ -94,7 +93,6 @@ export class ProjectMetadataStepComponent { stepperActiveValue = input.required(); targetStepValue = input.required(); isDisabled = input.required(); - providerId = input.required(); stepChange = output(); metadataSaved = output(); @@ -219,10 +217,9 @@ export class ProjectMetadataStepComponent { private setupEffects(): void { effect(() => { const licenses = this.collectionLicenses(); - const providerId = this.providerId(); - if (!licenses.length && providerId) { - this.actions.getCollectionLicenses(providerId); + if (!licenses.length) { + this.actions.getCollectionLicenses(this.collectionProvider()?.licensesLink); } }); diff --git a/src/app/features/collections/services/add-to-collection.service.spec.ts b/src/app/features/collections/services/add-to-collection.service.spec.ts new file mode 100644 index 000000000..f12e874da --- /dev/null +++ b/src/app/features/collections/services/add-to-collection.service.spec.ts @@ -0,0 +1,114 @@ +import { MockProvider } from 'ng-mocks'; + +import { firstValueFrom, of } from 'rxjs'; + +import { TestBed } from '@angular/core/testing'; + +import { CollectionsMapper } from '@osf/shared/mappers/collections'; +import { ReviewActionsMapper } from '@osf/shared/mappers/review-actions.mapper'; +import { CollectionSubmissionPayload } from '@osf/shared/models/collections/collection-submission-payload.model'; +import { CollectionSubmissionPayloadJsonApi } from '@osf/shared/models/collections/collection-submission-payload-json-api.model'; +import { ReviewActionPayloadJsonApi } from '@osf/shared/models/review-action/review-action-payload-json-api.model'; +import { JsonApiService } from '@osf/shared/services/json-api.service'; + +import { MOCK_API_URL, provideMockEnvironment } from '@testing/providers/environment.provider.mock'; +import { JsonApiServiceMock, JsonApiServiceMockType } from '@testing/providers/json-api.service.mock'; + +import { RemoveCollectionSubmissionPayload } from '../models/remove-collection-submission-payload.model'; + +import { AddToCollectionService } from './add-to-collection.service'; + +describe('AddToCollectionService', () => { + let service: AddToCollectionService; + let jsonApiService: JsonApiServiceMockType; + + const submissionPayload: CollectionSubmissionPayload = { + collectionId: 'collection-1', + projectId: 'project-1', + userId: 'user-1', + }; + + const removePayload: RemoveCollectionSubmissionPayload = { + projectId: 'project-1', + collectionId: 'collection-1', + comment: 'Removing from collection', + }; + + function setup() { + jsonApiService = JsonApiServiceMock.simple(); + + TestBed.configureTestingModule({ + providers: [AddToCollectionService, MockProvider(JsonApiService, jsonApiService), provideMockEnvironment()], + }); + + service = TestBed.inject(AddToCollectionService); + } + + it('should expose apiUrl from environment', () => { + setup(); + + expect(service.apiUrl).toBe(MOCK_API_URL); + }); + + it('createCollectionSubmission should map payload and post to collection submissions', async () => { + setup(); + const mappedPayload = { + data: { + type: 'collection-submissions', + attributes: { guid: 'project-1' }, + relationships: { + collection: { data: { id: 'collection-1', type: 'collections' } }, + creator: { data: { type: 'users', id: 'user-1' } }, + }, + }, + } as CollectionSubmissionPayloadJsonApi; + const mapperSpy = vi.spyOn(CollectionsMapper, 'toCollectionSubmissionRequest').mockReturnValue(mappedPayload); + jsonApiService.post.mockReturnValue(of(undefined)); + + const response = await firstValueFrom(service.createCollectionSubmission(submissionPayload)); + + expect(mapperSpy).toHaveBeenCalledWith(submissionPayload); + expect(jsonApiService.post).toHaveBeenCalledWith( + `${MOCK_API_URL}/collections/${submissionPayload.collectionId}/collection_submissions/`, + mappedPayload + ); + expect(response).toBeUndefined(); + }); + + it('removeCollectionSubmission should map review action and post to collection submission actions', async () => { + setup(); + const mappedParams = { + data: { + type: 'collection_submission_actions', + attributes: { + trigger: 'remove', + comment: removePayload.comment, + }, + relationships: { + target: { + data: { + type: 'collection-submissions', + id: `${removePayload.projectId}-${removePayload.collectionId}`, + }, + }, + }, + }, + } as ReviewActionPayloadJsonApi; + const mapperSpy = vi.spyOn(ReviewActionsMapper, 'toReviewActionPayloadJsonApi').mockReturnValue(mappedParams); + jsonApiService.post.mockReturnValue(of(undefined)); + + const response = await firstValueFrom(service.removeCollectionSubmission(removePayload)); + + expect(mapperSpy).toHaveBeenCalledWith( + { + action: 'remove', + targetId: `${removePayload.projectId}-${removePayload.collectionId}`, + comment: removePayload.comment, + }, + 'collection_submission_actions', + 'collection-submissions' + ); + expect(jsonApiService.post).toHaveBeenCalledWith(`${MOCK_API_URL}/collection_submission_actions/`, mappedParams); + expect(response).toBeUndefined(); + }); +}); diff --git a/src/app/features/collections/services/add-to-collection.service.ts b/src/app/features/collections/services/add-to-collection.service.ts index c2e8a1c1b..8f786bb7f 100644 --- a/src/app/features/collections/services/add-to-collection.service.ts +++ b/src/app/features/collections/services/add-to-collection.service.ts @@ -1,16 +1,13 @@ -import { map, Observable } from 'rxjs'; +import { Observable } from 'rxjs'; import { inject, Injectable } from '@angular/core'; import { ENVIRONMENT } from '@core/provider/environment.provider'; import { CollectionsMapper } from '@osf/shared/mappers/collections'; -import { LicensesMapper } from '@osf/shared/mappers/licenses.mapper'; import { ReviewActionsMapper } from '@osf/shared/mappers/review-actions.mapper'; import { ReviewActionPayload } from '@osf/shared/models/review-action/review-action-payload.model'; import { JsonApiService } from '@osf/shared/services/json-api.service'; import { CollectionSubmissionPayload } from '@shared/models/collections/collection-submission-payload.model'; -import { LicenseModel } from '@shared/models/license/license.model'; -import { LicensesResponseJsonApi } from '@shared/models/license/licenses-json-api.model'; import { RemoveCollectionSubmissionPayload } from '../models/remove-collection-submission-payload.model'; @@ -25,15 +22,6 @@ export class AddToCollectionService { return `${this.environment.apiDomainUrl}/v2`; } - fetchCollectionLicenses(providerId: string): Observable { - return this.jsonApiService - .get(`${this.apiUrl}/providers/collections/${providerId}/licenses/`, { - 'page[size]': 100, - sort: 'name', - }) - .pipe(map((licenses) => LicensesMapper.fromLicensesResponse(licenses))); - } - createCollectionSubmission(payload: CollectionSubmissionPayload): Observable { const collectionId = payload.collectionId; const metadata = CollectionsMapper.toCollectionSubmissionRequest(payload); diff --git a/src/app/features/collections/store/add-to-collection/add-to-collection.actions.ts b/src/app/features/collections/store/add-to-collection/add-to-collection.actions.ts index 8b68c33b5..c8bdfdeab 100644 --- a/src/app/features/collections/store/add-to-collection/add-to-collection.actions.ts +++ b/src/app/features/collections/store/add-to-collection/add-to-collection.actions.ts @@ -5,7 +5,7 @@ import { RemoveCollectionSubmissionPayload } from '../../models/remove-collectio export class GetCollectionLicenses { static readonly type = '[Add To Collection] Get Collection Licenses'; - constructor(public providerId: string) {} + constructor(public licensesUrl?: string) {} } export class GetCurrentCollectionSubmission { diff --git a/src/app/features/collections/store/add-to-collection/add-to-collection.state.ts b/src/app/features/collections/store/add-to-collection/add-to-collection.state.ts index 1e1f230f0..fff5d1ea7 100644 --- a/src/app/features/collections/store/add-to-collection/add-to-collection.state.ts +++ b/src/app/features/collections/store/add-to-collection/add-to-collection.state.ts @@ -1,6 +1,6 @@ import { Action, State, StateContext } from '@ngxs/store'; -import { tap } from 'rxjs'; +import { EMPTY, tap } from 'rxjs'; import { catchError } from 'rxjs/operators'; import { inject, Injectable } from '@angular/core'; @@ -8,6 +8,7 @@ import { inject, Injectable } from '@angular/core'; import { AddToCollectionService } from '@osf/features/collections/services/add-to-collection.service'; import { handleSectionError } from '@osf/shared/helpers/state-error.handler'; import { CollectionsService } from '@osf/shared/services/collections.service'; +import { LicensesService } from '@osf/shared/services/licenses.service'; import { ClearAddToCollectionState, @@ -26,9 +27,14 @@ import { ADD_TO_COLLECTION_DEFAULTS, AddToCollectionStateModel } from './add-to- export class AddToCollectionState { addToCollectionService = inject(AddToCollectionService); collectionsService = inject(CollectionsService); + licensesService = inject(LicensesService); @Action(GetCollectionLicenses) getCollectionLicenses(ctx: StateContext, action: GetCollectionLicenses) { + if (!action.licensesUrl) { + return EMPTY; + } + const state = ctx.getState(); ctx.patchState({ collectionLicenses: { @@ -37,7 +43,7 @@ export class AddToCollectionState { }, }); - return this.addToCollectionService.fetchCollectionLicenses(action.providerId).pipe( + return this.licensesService.getLicenses(action.licensesUrl).pipe( tap((licenses) => { ctx.patchState({ collectionLicenses: { diff --git a/src/app/features/home/constants/dashboard-products.constants.ts b/src/app/features/home/constants/dashboard-products.constants.ts index 75ddab13e..aad039ae5 100644 --- a/src/app/features/home/constants/dashboard-products.constants.ts +++ b/src/app/features/home/constants/dashboard-products.constants.ts @@ -1,13 +1,6 @@ import { DashboardProductLink } from '../models/dashboard-product-link.model'; export const DASHBOARD_PRODUCT_LINKS: DashboardProductLink[] = [ - { - link: 'https://www.cos.io/products/osf-collections', - imageSrc: 'assets/images/dashboard/products/osf-collections.png', - altKey: 'home.loggedIn.dashboard.images.osfCollectionsImageAltText', - external: true, - testId: 'products-collections', - }, { link: '/institutions', imageSrc: 'assets/images/dashboard/products/osf-institutions.png', diff --git a/src/app/features/home/models/dashboard-product-link.model.ts b/src/app/features/home/models/dashboard-product-link.model.ts index 3f40c022c..d3997158b 100644 --- a/src/app/features/home/models/dashboard-product-link.model.ts +++ b/src/app/features/home/models/dashboard-product-link.model.ts @@ -2,6 +2,4 @@ export interface DashboardProductLink { imageSrc: string; altKey: string; link: string; - external?: boolean; - testId?: string; } diff --git a/src/app/features/home/pages/dashboard/dashboard.component.html b/src/app/features/home/pages/dashboard/dashboard.component.html index 9a5645c48..e7791102c 100644 --- a/src/app/features/home/pages/dashboard/dashboard.component.html +++ b/src/app/features/home/pages/dashboard/dashboard.component.html @@ -84,20 +84,9 @@

{{ 'home.loggedIn.latestResearch.title' | translate }}

@for (product of dashboardProducts; track product.imageSrc) { - @if (product.external) { - - - - } @else { - - - - } + + + }
} diff --git a/src/app/features/home/pages/dashboard/dashboard.component.spec.ts b/src/app/features/home/pages/dashboard/dashboard.component.spec.ts index 7e207830a..bbc04c67f 100644 --- a/src/app/features/home/pages/dashboard/dashboard.component.spec.ts +++ b/src/app/features/home/pages/dashboard/dashboard.component.spec.ts @@ -2,13 +2,16 @@ import { Store } from '@ngxs/store'; import { MockComponents, MockProvider } from 'ng-mocks'; +import { SortEvent } from 'primeng/api'; +import { TablePageEvent } from 'primeng/table'; + import { Subject } from 'rxjs'; import { Mock } from 'vitest'; import { PLATFORM_ID } from '@angular/core'; import { ComponentFixture, TestBed } from '@angular/core/testing'; -import { ActivatedRoute, Router } from '@angular/router'; +import { ActivatedRoute, provideRouter, Router } from '@angular/router'; import { ScheduledBannerComponent } from '@core/components/osf-banners/scheduled-banner/scheduled-banner.component'; import { UserSelectors } from '@osf/core/store/user'; @@ -19,13 +22,20 @@ import { SearchInputComponent } from '@osf/shared/components/search-input/search import { SubHeaderComponent } from '@osf/shared/components/sub-header/sub-header.component'; import { FEATURE_FLAGS } from '@osf/shared/constants/feature-flags.const'; import { SortOrder } from '@osf/shared/enums/sort-order.enum'; -import { MyResourcesItem } from '@osf/shared/models/my-resources/my-resources-item.model'; import { CustomDialogService } from '@osf/shared/services/custom-dialog.service'; import { ProjectRedirectDialogService } from '@osf/shared/services/project-redirect-dialog.service'; import { ClearMyResources, GetMyProjects, MyResourcesSelectors } from '@osf/shared/stores/my-resources'; +import { + MOCK_MY_RESOURCES_ITEM_PROJECT, + MOCK_MY_RESOURCES_ITEM_PROJECT_PRIVATE, +} from '@testing/mocks/my-resources.mock'; import { provideOSFCore } from '@testing/osf.testing.provider'; import { CustomDialogServiceMock, CustomDialogServiceMockType } from '@testing/providers/custom-dialog-provider.mock'; +import { + ProjectRedirectDialogServiceMock, + ProjectRedirectDialogServiceMockType, +} from '@testing/providers/project-redirect-dialog.service.mock'; import { ActivatedRouteMockBuilder } from '@testing/providers/route-provider.mock'; import { RouterMockBuilder, RouterMockType } from '@testing/providers/router-provider.mock'; import { @@ -36,7 +46,6 @@ import { } from '@testing/providers/store-provider.mock'; import { WorkflowLauncherSectionComponent } from '../../components/workflow-launcher-section/workflow-launcher-section.component'; -import { DASHBOARD_PRODUCT_LINKS } from '../../constants/dashboard-products.constants'; import { DashboardComponent } from './dashboard.component'; @@ -46,27 +55,10 @@ describe('DashboardComponent', () => { let store: Store; let routerMock: RouterMockType; let customDialogService: CustomDialogServiceMockType; - let projectRedirectDialogService: { showProjectRedirectDialog: Mock }; - - const projectItem: MyResourcesItem = { - id: '1', - type: 'nodes', - title: 'Alpha project', - dateCreated: '2024-01-01', - dateModified: '2024-01-02', - isPublic: true, - contributors: [], - }; - - const secondProjectItem: MyResourcesItem = { - id: '2', - type: 'nodes', - title: 'Beta project', - dateCreated: '2024-01-03', - dateModified: '2024-01-04', - isPublic: false, - contributors: [], - }; + let projectRedirectDialogService: ProjectRedirectDialogServiceMockType; + + const projectItem = MOCK_MY_RESOURCES_ITEM_PROJECT; + const secondProjectItem = MOCK_MY_RESOURCES_ITEM_PROJECT_PRIVATE; const defaultSignals: SignalOverride[] = [ { selector: MyResourcesSelectors.getProjects, value: [] }, @@ -84,7 +76,7 @@ describe('DashboardComponent', () => { function setup(options: SetupOverrides = {}) { routerMock = RouterMockBuilder.create().build(); customDialogService = CustomDialogServiceMock.simple(); - projectRedirectDialogService = { showProjectRedirectDialog: vi.fn() }; + projectRedirectDialogService = ProjectRedirectDialogServiceMock.simple(); const routeMock = ActivatedRouteMockBuilder.create() .withQueryParams(options.routeQueryParams ?? {}) .build(); @@ -103,11 +95,12 @@ describe('DashboardComponent', () => { ], providers: [ provideOSFCore(), + provideRouter([]), MockProvider(ActivatedRoute, routeMock), MockProvider(Router, routerMock), MockProvider(CustomDialogService, customDialogService), MockProvider(ProjectRedirectDialogService, projectRedirectDialogService), - MockProvider(PLATFORM_ID, options?.platformId ?? 'browser'), + MockProvider(PLATFORM_ID, options.platformId ?? 'browser'), provideMockStore({ signals: mergeSignalOverrides(defaultSignals, options.selectorOverrides) }), ], }); @@ -118,6 +111,10 @@ describe('DashboardComponent', () => { fixture.detectChanges(); } + afterEach(() => { + vi.useRealTimers(); + }); + it('should create and fetch projects with default params on init', () => { setup(); @@ -132,14 +129,6 @@ describe('DashboardComponent', () => { ); }); - it('should disable project creation and show tooltip when isProjectCreationDisabled is true', () => { - setup({ - selectorOverrides: [{ selector: UserSelectors.isProjectCreationDisabled, value: true }], - }); - - expect(component.buttonTooltip()).toBe('home.loggedIn.dashboard.createProjectDisabledTooltip'); - }); - it('should read query params and fetch projects on init', () => { setup({ routeQueryParams: { @@ -166,12 +155,6 @@ describe('DashboardComponent', () => { ); }); - it('should sync total projects count into table params', () => { - setup({ selectorOverrides: [{ selector: MyResourcesSelectors.getTotalProjects, value: 42 }] }); - - expect(component.tableParams().totalRecords).toBe(42); - }); - it('should default sort order when query param sort order is invalid', () => { setup({ routeQueryParams: { @@ -183,20 +166,26 @@ describe('DashboardComponent', () => { expect(component.sortOrder()).toBe(SortOrder.Asc); }); - it('should use dashboard sub header when projects exist', () => { + it('should sync total projects count into table params', () => { + setup({ selectorOverrides: [{ selector: MyResourcesSelectors.getTotalProjects, value: 42 }] }); + + expect(component.tableParams().totalRecords).toBe(42); + }); + + it('should disable project creation messaging when isProjectCreationDisabled is true', () => { setup({ - selectorOverrides: [{ selector: MyResourcesSelectors.getProjects, value: [projectItem] }], + selectorOverrides: [{ selector: UserSelectors.isProjectCreationDisabled, value: true }], }); - expect(component.existsProjects()).toBeTruthy(); - expect(component.subHeaderTitle()).toBe('home.loggedIn.dashboard.title'); + expect(component.buttonTooltip()).toBe('home.loggedIn.dashboard.createProjectDisabledTooltip'); + expect(component.noProjectsMessage()).toBe('home.loggedIn.dashboard.noCreatedProjectAndCreateProjectDisabled'); }); it('should update query params on page change', () => { setup(); (routerMock.navigate as Mock).mockClear(); - component.onPageChange({ first: 20, rows: 10 } as never); + component.onPageChange({ first: 20, rows: 10 } as TablePageEvent); expect(routerMock.navigate).toHaveBeenCalledWith([], { relativeTo: TestBed.inject(ActivatedRoute), @@ -215,10 +204,10 @@ describe('DashboardComponent', () => { setup(); (routerMock.navigate as Mock).mockClear(); - component.onSort({ field: 'dateModified', order: -1 } as never); + component.onSort({ field: 'dateModified', order: SortOrder.Desc } as SortEvent); expect(component.sortColumn()).toBe('dateModified'); - expect(component.sortOrder()).toBe(-1); + expect(component.sortOrder()).toBe(SortOrder.Desc); expect(routerMock.navigate).toHaveBeenCalledWith([], { relativeTo: TestBed.inject(ActivatedRoute), queryParams: { @@ -226,7 +215,7 @@ describe('DashboardComponent', () => { rows: 10, search: undefined, sortField: 'dateModified', - sortOrder: -1, + sortOrder: SortOrder.Desc, }, queryParamsHandling: 'merge', }); @@ -236,85 +225,85 @@ describe('DashboardComponent', () => { setup(); (routerMock.navigate as Mock).mockClear(); - component.onSort({ field: undefined, order: SortOrder.Desc } as never); + component.onSort({ field: undefined, order: SortOrder.Desc } as SortEvent); expect(routerMock.navigate).not.toHaveBeenCalled(); }); - it('should dispatch fetch projects with current search and sort state', () => { + it('should update query params after search debounce', () => { + vi.useFakeTimers(); setup(); - (store.dispatch as Mock).mockClear(); - - component.searchControl.setValue('alp'); - component.sortColumn.set('title'); - component.sortOrder.set(-1); - - component.fetchProjects(); + (routerMock.navigate as Mock).mockClear(); - expect(store.dispatch).toHaveBeenCalledWith( - new GetMyProjects(1, 10, { - searchValue: 'alp', - searchFields: ['title'], - sortColumn: 'title', - sortOrder: -1, - }) - ); - }); + component.searchControl.setValue('alpha'); + vi.advanceTimersByTime(300); - it('should filter projects by search value', () => { - setup({ - routeQueryParams: { search: 'alp' }, - selectorOverrides: [ - { - selector: MyResourcesSelectors.getProjects, - value: [projectItem, secondProjectItem], - }, - ], + expect(routerMock.navigate).toHaveBeenCalledWith([], { + relativeTo: TestBed.inject(ActivatedRoute), + queryParams: { + page: 1, + rows: 10, + search: 'alpha', + sortField: undefined, + sortOrder: 1, + }, + queryParamsHandling: 'merge', }); - - expect(component.filteredProjects()).toEqual([projectItem]); - }); - - it('should treat search value as existing projects when list is empty', () => { - setup({ routeQueryParams: { search: 'query' } }); - - expect(component.existsProjects()).toBeTruthy(); - expect(component.subHeaderTitle()).toBe('home.loggedIn.dashboard.title'); }); - it('should use welcome sub header when no projects and no search', () => { + it('should not update query params when debounced search value is unchanged', () => { + vi.useFakeTimers(); setup(); + component.searchControl.setValue('alpha'); + vi.advanceTimersByTime(300); + (routerMock.navigate as Mock).mockClear(); - expect(component.existsProjects()).toBe(false); - expect(component.subHeaderTitle()).toBe('home.loggedIn.dashboard.welcome'); - }); - - it('should expose dashboard product links', () => { - setup(); + component.searchControl.setValue('alpha'); + vi.advanceTimersByTime(300); - expect(component.dashboardProducts).toBe(DASHBOARD_PRODUCT_LINKS); + expect(routerMock.navigate).not.toHaveBeenCalled(); }); - it('should update query params after search debounce', () => { - vi.useFakeTimers(); + it('should omit empty search from query params', () => { setup(); (routerMock.navigate as Mock).mockClear(); - component.searchControl.setValue('alpha'); - vi.advanceTimersByTime(300); + component.searchControl.setValue(''); + component.updateQueryParams(); expect(routerMock.navigate).toHaveBeenCalledWith([], { relativeTo: TestBed.inject(ActivatedRoute), queryParams: { page: 1, rows: 10, - search: 'alpha', + search: undefined, sortField: undefined, sortOrder: 1, }, queryParamsHandling: 'merge', }); - vi.useRealTimers(); + }); + + it('should filter projects by search value case insensitively', () => { + setup({ + routeQueryParams: { search: 'PRIVATE' }, + selectorOverrides: [ + { + selector: MyResourcesSelectors.getProjects, + value: [projectItem, secondProjectItem], + }, + ], + }); + + expect(component.filteredProjects()).toEqual([secondProjectItem]); + }); + + it('should return all projects when search is empty', () => { + setup({ + selectorOverrides: [{ selector: MyResourcesSelectors.getProjects, value: [projectItem, secondProjectItem] }], + }); + + expect(component.filteredProjects()).toEqual([projectItem, secondProjectItem]); }); it('should navigate to project and set active project', () => { @@ -343,12 +332,14 @@ describe('DashboardComponent', () => { it('should not redirect when create project dialog closes without project id', () => { setup(); - const onClose$ = new Subject(); + const onClose$ = new Subject<{ project?: { id?: string } } | null>(); customDialogService.open.mockReturnValue(CustomDialogServiceMock.dialogRefWithClose(onClose$.asObservable())); component.createProject(); onClose$.next(null); + expect(projectRedirectDialogService.showProjectRedirectDialog).not.toHaveBeenCalled(); + onClose$.next({ project: {} }); expect(projectRedirectDialogService.showProjectRedirectDialog).not.toHaveBeenCalled(); }); @@ -402,100 +393,31 @@ describe('DashboardComponent', () => { expect(fixture.nativeElement.querySelector('osf-workflow-launcher-section')).toBeFalsy(); }); - it('should return all projects when search is empty', () => { - setup({ - selectorOverrides: [{ selector: MyResourcesSelectors.getProjects, value: [projectItem, secondProjectItem] }], - }); - - expect(component.filteredProjects()).toEqual([projectItem, secondProjectItem]); - }); - - it('should filter projects case insensitively', () => { - setup({ - routeQueryParams: { search: 'ALPHA' }, - selectorOverrides: [{ selector: MyResourcesSelectors.getProjects, value: [projectItem, secondProjectItem] }], - }); - - expect(component.filteredProjects()).toEqual([projectItem]); - }); - - it('should omit empty search from query params', () => { + it('should use welcome state when no projects and no search', () => { setup(); - (routerMock.navigate as Mock).mockClear(); - - component.searchControl.setValue(''); - component.updateQueryParams(); - expect(routerMock.navigate).toHaveBeenCalledWith([], { - relativeTo: TestBed.inject(ActivatedRoute), - queryParams: { - page: 1, - rows: 10, - search: undefined, - sortField: undefined, - sortOrder: 1, - }, - queryParamsHandling: 'merge', - }); - }); - - it('should not update query params when debounced search value is unchanged', () => { - vi.useFakeTimers(); - setup(); - component.searchControl.setValue('alpha'); - vi.advanceTimersByTime(300); - (routerMock.navigate as Mock).mockClear(); - - component.searchControl.setValue('alpha'); - vi.advanceTimersByTime(300); - - expect(routerMock.navigate).not.toHaveBeenCalled(); - vi.useRealTimers(); + expect(component.existsProjects()).toBe(false); + expect(component.subHeaderTitle()).toBe('home.loggedIn.dashboard.welcome'); + expect(component.noProjectsMessage()).toBe('home.loggedIn.dashboard.noCreatedProject'); + expect(fixture.nativeElement.querySelector('osf-my-projects-table')).toBeFalsy(); + expect(fixture.nativeElement.querySelector('.latest-research-container')).toBeFalsy(); }); - it('should render empty state when no projects exist', () => { - setup(); + it('should treat search value as existing projects when list is empty', () => { + setup({ routeQueryParams: { search: 'query' } }); - expect(fixture.nativeElement.querySelector('.connected-record-image')).toBeTruthy(); - expect(fixture.nativeElement.querySelector('osf-my-projects-table')).toBeFalsy(); - expect(fixture.nativeElement.querySelector('.latest-research-container')).toBeFalsy(); + expect(component.existsProjects()).toBeTruthy(); + expect(component.subHeaderTitle()).toBe('home.loggedIn.dashboard.title'); }); - it('should render projects table and latest research when projects exist', () => { + it('should show projects table when projects exist', () => { setup({ selectorOverrides: [{ selector: MyResourcesSelectors.getProjects, value: [projectItem] }], }); + expect(component.existsProjects()).toBeTruthy(); + expect(component.subHeaderTitle()).toBe('home.loggedIn.dashboard.title'); expect(fixture.nativeElement.querySelector('osf-my-projects-table')).toBeTruthy(); expect(fixture.nativeElement.querySelector('.latest-research-container')).toBeTruthy(); - expect(fixture.nativeElement.querySelector('.connected-record-image')).toBeFalsy(); - }); - - it('should render dashboard product links', () => { - setup(); - - const productImages = fixture.nativeElement.querySelectorAll('.flex.flex-column.p-4 img'); - - expect(productImages.length).toBe(DASHBOARD_PRODUCT_LINKS.length); - }); - - it('should render external product link with blank target', () => { - setup(); - - const externalLink = fixture.nativeElement.querySelector('[data-test-products-collections]'); - - expect(externalLink?.getAttribute('target')).toBe('_blank'); - expect(externalLink?.getAttribute('rel')).toBe('noopener noreferrer'); - }); - - it('should not redirect when create project dialog closes with missing project id', () => { - setup(); - const onClose$ = new Subject<{ project: { id?: string } }>(); - customDialogService.open.mockReturnValue(CustomDialogServiceMock.dialogRefWithClose(onClose$.asObservable())); - - component.createProject(); - onClose$.next({ project: {} }); - - expect(projectRedirectDialogService.showProjectRedirectDialog).not.toHaveBeenCalled(); }); }); diff --git a/src/app/features/home/pages/dashboard/dashboard.component.ts b/src/app/features/home/pages/dashboard/dashboard.component.ts index 0e8a1730b..0eda1d14e 100644 --- a/src/app/features/home/pages/dashboard/dashboard.component.ts +++ b/src/app/features/home/pages/dashboard/dashboard.component.ts @@ -9,7 +9,17 @@ import { TablePageEvent } from 'primeng/table'; import { debounceTime, distinctUntilChanged, filter, tap } from 'rxjs'; import { isPlatformBrowser, NgOptimizedImage } from '@angular/common'; -import { Component, computed, DestroyRef, effect, inject, OnInit, PLATFORM_ID, signal } from '@angular/core'; +import { + ChangeDetectionStrategy, + Component, + computed, + DestroyRef, + effect, + inject, + OnInit, + PLATFORM_ID, + signal, +} from '@angular/core'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { FormControl } from '@angular/forms'; import { ActivatedRoute, Router, RouterLink } from '@angular/router'; @@ -50,6 +60,7 @@ import { DASHBOARD_PRODUCT_LINKS } from '../../constants/dashboard-products.cons ], templateUrl: './dashboard.component.html', styleUrl: './dashboard.component.scss', + changeDetection: ChangeDetectionStrategy.OnPush, }) export class DashboardComponent implements OnInit { private readonly destroyRef = inject(DestroyRef); @@ -57,8 +68,7 @@ export class DashboardComponent implements OnInit { private readonly route = inject(ActivatedRoute); private readonly customDialogService = inject(CustomDialogService); private readonly projectRedirectDialogService = inject(ProjectRedirectDialogService); - private readonly platformId = inject(PLATFORM_ID); - private readonly isBrowser = isPlatformBrowser(this.platformId); + private readonly isBrowser = isPlatformBrowser(inject(PLATFORM_ID)); readonly searchControl = new FormControl(''); readonly activeProject = signal(null); @@ -83,17 +93,16 @@ export class DashboardComponent implements OnInit { return this.projects().filter((project) => project.title.toLowerCase().includes(search)); }); - readonly buttonTooltip = computed(() => { - return this.projectCreationDisabled() ? 'home.loggedIn.dashboard.createProjectDisabledTooltip' : ''; - }); - readonly existsProjects = computed(() => this.projects().length || !!this.searchControl.value?.length); - readonly noProjectsMessage = computed(() => { - if (this.projectCreationDisabled()) { - return 'home.loggedIn.dashboard.noCreatedProjectAndCreateProjectDisabled'; - } - return 'home.loggedIn.dashboard.noCreatedProject'; - }); + + readonly buttonTooltip = computed(() => + this.projectCreationDisabled() ? 'home.loggedIn.dashboard.createProjectDisabledTooltip' : '' + ); + readonly noProjectsMessage = computed(() => + this.projectCreationDisabled() + ? 'home.loggedIn.dashboard.noCreatedProjectAndCreateProjectDisabled' + : 'home.loggedIn.dashboard.noCreatedProject' + ); readonly subHeaderTitle = computed(() => this.existsProjects() ? 'home.loggedIn.dashboard.title' : 'home.loggedIn.dashboard.welcome' ); @@ -215,7 +224,7 @@ export class DashboardComponent implements OnInit { this.customDialogService .open(CreateProjectDialogComponent, { header: 'myProjects.header.createProject', width: '850px' }) .onClose.pipe( - filter((result) => result?.project.id), + filter((result: { project: MyResourcesItem }) => !!result?.project.id), tap((result) => this.projectRedirectDialogService.showProjectRedirectDialog(result.project.id)), takeUntilDestroyed(this.destroyRef) ) diff --git a/src/app/features/metadata/components/cedar-template-form/cedar-template-form.component.spec.ts b/src/app/features/metadata/components/cedar-template-form/cedar-template-form.component.spec.ts index 83bc459ae..76aaf0c01 100644 --- a/src/app/features/metadata/components/cedar-template-form/cedar-template-form.component.spec.ts +++ b/src/app/features/metadata/components/cedar-template-form/cedar-template-form.component.spec.ts @@ -4,6 +4,7 @@ import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ActivatedRoute } from '@angular/router'; import { CedarMetadataHelper } from '@osf/features/metadata/helpers'; +import { CedarEditorElement } from '@osf/features/metadata/models'; import { MOCK_CEDAR_METADATA_RECORD, MOCK_CEDAR_METADATA_TEMPLATE } from '@testing/mocks/cedar-metadata-domain.mock'; import { provideOSFCore } from '@testing/osf.testing.provider'; @@ -102,4 +103,46 @@ describe('CedarTemplateFormComponent', () => { expect(component.formData()).toEqual(initialFormData); }); + + it('should load record metadata with the template and then on its own to keep checkbox answers', () => { + const editor = {} as CedarEditorElement; + vi.spyOn(component, 'cedarEditor').mockReturnValue({ nativeElement: editor } as never); + + fixture.componentRef.setInput('existingRecord', mockRecord); + fixture.detectChanges(); + + expect(Object.keys(editor)).toEqual(['templateAndInstanceObject', 'instanceObject']); + expect(editor.templateAndInstanceObject).toEqual({ + templateObject: mockTemplate.template, + instanceObject: mockRecord.metadata, + }); + expect(editor.instanceObject).toEqual(mockRecord.metadata); + }); + + it('should publish on submit when the editor report is valid', () => { + const editor = { + currentMetadata: { field: 'value' }, + dataQualityReport: { isValid: true }, + } as unknown as CedarEditorElement; + vi.spyOn(component, 'cedarEditor').mockReturnValue({ nativeElement: editor } as never); + const emitSpy = vi.spyOn(component.emitData, 'emit'); + component.isValid = false; + + component.onSubmit(); + + expect(emitSpy).toHaveBeenCalledWith({ data: { field: 'value' }, id: mockTemplate.id, isPublished: true }); + }); + + it('should save as draft on submit when the editor report is not valid', () => { + const editor = { + currentMetadata: { field: 'value' }, + dataQualityReport: { isValid: false }, + } as unknown as CedarEditorElement; + vi.spyOn(component, 'cedarEditor').mockReturnValue({ nativeElement: editor } as never); + const emitSpy = vi.spyOn(component.emitData, 'emit'); + + component.onSubmit(); + + expect(emitSpy).toHaveBeenCalledWith({ data: { field: 'value' }, id: mockTemplate.id, isPublished: false }); + }); }); diff --git a/src/app/features/metadata/components/cedar-template-form/cedar-template-form.component.ts b/src/app/features/metadata/components/cedar-template-form/cedar-template-form.component.ts index 3072ae81d..b512087bc 100644 --- a/src/app/features/metadata/components/cedar-template-form/cedar-template-form.component.ts +++ b/src/app/features/metadata/components/cedar-template-form/cedar-template-form.component.ts @@ -113,7 +113,11 @@ export class CedarTemplateFormComponent { this.initializeFormData(); if (metadata) { - if (editor) editor.instanceObject = metadata; + const template = this.template()?.template; + if (editor && template) { + editor.templateAndInstanceObject = { templateObject: template, instanceObject: metadata }; + editor.instanceObject = metadata; + } if (viewer) viewer.instanceObject = metadata; } @@ -182,6 +186,7 @@ export class CedarTemplateFormComponent { onSubmit() { const editor = this.cedarEditor()?.nativeElement; if (editor && typeof editor.currentMetadata !== 'undefined') { + this.validateCedarMetadata(); const finalData = { data: editor.currentMetadata, id: this.template().id, isPublished: this.isValid }; this.formData.set(finalData); this.emitData.emit(finalData as CedarRecordDataBinding); diff --git a/src/app/features/metadata/dialogs/license-dialog/license-dialog.component.html b/src/app/features/metadata/dialogs/license-dialog/license-dialog.component.html index 019867cbc..342ca8642 100644 --- a/src/app/features/metadata/dialogs/license-dialog/license-dialog.component.html +++ b/src/app/features/metadata/dialogs/license-dialog/license-dialog.component.html @@ -1,32 +1,22 @@
@if (licensesLoading()) { - + } @else { -
-

{{ 'project.metadata.license.dialog.chooseLicense.label' | translate }}

+

{{ 'project.metadata.license.dialog.chooseLicense.label' | translate }}

- -
+ }
- +
diff --git a/src/app/features/metadata/dialogs/license-dialog/license-dialog.component.spec.ts b/src/app/features/metadata/dialogs/license-dialog/license-dialog.component.spec.ts index 63f7e51c4..e17d79a24 100644 --- a/src/app/features/metadata/dialogs/license-dialog/license-dialog.component.spec.ts +++ b/src/app/features/metadata/dialogs/license-dialog/license-dialog.component.spec.ts @@ -1,137 +1,197 @@ +import { Store } from '@ngxs/store'; + import { MockComponents, MockProvider } from 'ng-mocks'; import { DynamicDialogConfig, DynamicDialogRef } from 'primeng/dynamicdialog'; +import { signal, WritableSignal } from '@angular/core'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { LicenseComponent } from '@osf/shared/components/license/license.component'; import { LoadingSpinnerComponent } from '@osf/shared/components/loading-spinner/loading-spinner.component'; -import { LicensesSelectors } from '@shared/stores/licenses'; +import { LicenseModel, LicenseOptions } from '@osf/shared/models/license/license.model'; +import { FetchLicenses, LicensesSelectors } from '@osf/shared/stores/licenses'; import { MOCK_LICENSE } from '@testing/mocks/license.mock'; +import { MOCK_PROJECT_METADATA } from '@testing/mocks/project-metadata.mock'; import { provideOSFCore } from '@testing/osf.testing.provider'; +import { provideDynamicDialogRefMock } from '@testing/providers/dynamic-dialog-ref.mock'; import { provideMockStore } from '@testing/providers/store-provider.mock'; +import { LicenseDialogData } from '../../models/license-dialog.model'; + import { LicenseDialogComponent } from './license-dialog.component'; +const DEFAULT_LICENSES_URL = 'https://api.osf.io/v2/licenses/'; + describe('LicenseDialogComponent', () => { let component: LicenseDialogComponent; let fixture: ComponentFixture; + let store: Store; + let dialogRef: DynamicDialogRef; + let licensesLoadingSignal: WritableSignal; + + const licenseWithoutFields: LicenseModel = { + ...MOCK_LICENSE, + id: 'license-simple', + name: 'MIT', + requiredFields: [], + }; + + const mockLicenseOptions: LicenseOptions = { + copyrightHolders: 'John Doe', + year: '2023', + }; + + interface SetupOverrides { + dialogData?: LicenseDialogData; + licenses?: LicenseModel[]; + licensesLoading?: boolean; + } + + function setup(overrides: SetupOverrides = {}) { + licensesLoadingSignal = signal(overrides.licensesLoading ?? false); - beforeEach(() => { TestBed.configureTestingModule({ imports: [LicenseDialogComponent, ...MockComponents(LoadingSpinnerComponent, LicenseComponent)], providers: [ provideOSFCore(), - MockProvider(DynamicDialogRef), - MockProvider(DynamicDialogConfig), + provideDynamicDialogRefMock(), + MockProvider(DynamicDialogConfig, { + data: { licensesUrl: DEFAULT_LICENSES_URL, ...overrides.dialogData }, + }), provideMockStore({ signals: [ - { selector: LicensesSelectors.getLicenses, value: [MOCK_LICENSE] }, - { selector: LicensesSelectors.getLoading, value: false }, + { + selector: LicensesSelectors.getLicenses, + value: overrides.licenses ?? [MOCK_LICENSE, licenseWithoutFields], + }, + { selector: LicensesSelectors.getLoading, value: licensesLoadingSignal }, ], }), ], }); + store = TestBed.inject(Store); + dialogRef = TestBed.inject(DynamicDialogRef); fixture = TestBed.createComponent(LicenseDialogComponent); component = fixture.componentInstance; - }); + fixture.detectChanges(); + } - it('should create', () => { - expect(component).toBeTruthy(); + it('should dispatch FetchLicenses on init with licensesUrl', () => { + setup(); + + expect(store.dispatch).toHaveBeenCalledWith(new FetchLicenses(DEFAULT_LICENSES_URL)); }); - it('should handle license selection', () => { - component.onSelectLicense(MOCK_LICENSE); + it('should initialize selected license and options from metadata', () => { + setup({ + dialogData: { + metadata: { + ...MOCK_PROJECT_METADATA, + license: MOCK_LICENSE, + }, + }, + }); expect(component.selectedLicenseId()).toBe(MOCK_LICENSE.id); + expect(component.initialLicenseOptions).toEqual({ + copyrightHolders: 'Test Author, Test University', + year: '2024', + }); }); - it('should handle license creation with non-existent license', () => { - const dialogRef = TestBed.inject(DynamicDialogRef); + it('should close dialog with license options when saving a valid required-fields license', () => { + setup(); const closeSpy = vi.spyOn(dialogRef, 'close'); + component.selectedLicenseId.set(MOCK_LICENSE.id); + component.licenseState.set({ + licenseOptions: mockLicenseOptions, + formInvalid: false, + }); - const createEvent = { - id: 'non-existent-license', - licenseOptions: { copyrightHolders: 'John Doe', year: '2023' }, - }; - - component.onCreateLicense(createEvent); + expect(component.isSaveDisabled()).toBe(false); + component.save(); - expect(closeSpy).not.toHaveBeenCalled(); - expect(component.isSubmitting()).toBe(false); + expect(closeSpy).toHaveBeenCalledWith({ + licenseId: MOCK_LICENSE.id, + licenseOptions: mockLicenseOptions, + }); }); - it('should handle save with license that has required fields', () => { + it('should not save when required fields form is invalid', () => { + setup(); + const closeSpy = vi.spyOn(dialogRef, 'close'); component.selectedLicenseId.set(MOCK_LICENSE.id); - - const mockLicenseComponent = { - selectedLicense: () => MOCK_LICENSE, - licenseForm: { invalid: false }, - saveLicense: vi.fn(), - }; - - Object.defineProperty(component, 'licenseComponent', { - get: () => () => mockLicenseComponent, + component.licenseState.set({ + licenseOptions: { copyrightHolders: '', year: '' }, + formInvalid: true, }); + expect(component.isSaveDisabled()).toBe(true); component.save(); - expect(mockLicenseComponent.saveLicense).toHaveBeenCalled(); - expect(component.isSubmitting()).toBe(true); + expect(closeSpy).not.toHaveBeenCalled(); }); - it('should not save when no license is selected', () => { - const dialogRef = TestBed.inject(DynamicDialogRef); + it('should close dialog when saving license without required fields', () => { + setup(); const closeSpy = vi.spyOn(dialogRef, 'close'); + component.selectedLicenseId.set(licenseWithoutFields.id); - component.selectedLicenseId.set(null); - + expect(component.isSaveDisabled()).toBe(false); component.save(); - expect(closeSpy).not.toHaveBeenCalled(); + expect(closeSpy).toHaveBeenCalledWith({ + licenseId: licenseWithoutFields.id, + licenseOptions: undefined, + }); }); - it('should not save when selected license is not found', () => { - const dialogRef = TestBed.inject(DynamicDialogRef); + it('should not save when no license is selected', () => { + setup(); const closeSpy = vi.spyOn(dialogRef, 'close'); + component.selectedLicenseId.set(null); - component.selectedLicenseId.set('non-existent-license'); - + expect(component.isSaveDisabled()).toBe(true); component.save(); expect(closeSpy).not.toHaveBeenCalled(); }); - it('should handle cancel', () => { - const dialogRef = TestBed.inject(DynamicDialogRef); + it('should close dialog on cancel', () => { + setup(); const closeSpy = vi.spyOn(dialogRef, 'close'); - const mockLicenseComponent = { - cancel: vi.fn(), - }; - - Object.defineProperty(component, 'licenseComponent', { - get: () => () => mockLicenseComponent, - }); - component.cancel(); - expect(mockLicenseComponent.cancel).toHaveBeenCalled(); expect(closeSpy).toHaveBeenCalled(); }); - it('should handle cancel when license component is not available', () => { - const dialogRef = TestBed.inject(DynamicDialogRef); - const closeSpy = vi.spyOn(dialogRef, 'close'); + it('should disable save while licenses are loading', () => { + setup({ licensesLoading: true }); - Object.defineProperty(component, 'licenseComponent', { - get: () => () => null, - }); + expect(component.isSaveDisabled()).toBe(true); + }); - component.cancel(); + it('should disable save when license and options are unchanged', () => { + setup({ + dialogData: { + metadata: { + ...MOCK_PROJECT_METADATA, + license: MOCK_LICENSE, + }, + }, + }); + component.licenseState.set({ + licenseOptions: { + copyrightHolders: 'Test Author, Test University', + year: '2024', + }, + formInvalid: false, + }); - expect(closeSpy).toHaveBeenCalled(); + expect(component.isSaveDisabled()).toBe(true); }); }); diff --git a/src/app/features/metadata/dialogs/license-dialog/license-dialog.component.ts b/src/app/features/metadata/dialogs/license-dialog/license-dialog.component.ts index 0afd8ca27..247a63104 100644 --- a/src/app/features/metadata/dialogs/license-dialog/license-dialog.component.ts +++ b/src/app/features/metadata/dialogs/license-dialog/license-dialog.component.ts @@ -5,13 +5,15 @@ import { TranslatePipe } from '@ngx-translate/core'; import { Button } from 'primeng/button'; import { DynamicDialogConfig, DynamicDialogRef } from 'primeng/dynamicdialog'; -import { ChangeDetectionStrategy, Component, inject, OnInit, signal, viewChild } from '@angular/core'; +import { ChangeDetectionStrategy, Component, computed, inject, OnInit, signal } from '@angular/core'; -import { MetadataModel } from '@osf/features/metadata/models'; import { LicenseComponent } from '@osf/shared/components/license/license.component'; import { LoadingSpinnerComponent } from '@osf/shared/components/loading-spinner/loading-spinner.component'; -import { LicenseModel, LicenseOptions } from '@osf/shared/models/license/license.model'; -import { LicensesSelectors, LoadAllLicenses } from '@osf/shared/stores/licenses'; +import { LicenseOptions, LicenseState } from '@osf/shared/models/license/license.model'; +import { FetchLicenses, LicensesSelectors } from '@osf/shared/stores/licenses'; + +import { MetadataModel } from '../../models'; +import { LicenseDialogData, LicenseDialogResult } from '../../models/license-dialog.model'; @Component({ selector: 'osf-license-dialog', @@ -20,78 +22,86 @@ import { LicensesSelectors, LoadAllLicenses } from '@osf/shared/stores/licenses' changeDetection: ChangeDetectionStrategy.OnPush, }) export class LicenseDialogComponent implements OnInit { - dialogRef = inject(DynamicDialogRef); - config = inject(DynamicDialogConfig); + readonly dialogRef = inject(DynamicDialogRef); + readonly config = inject(DynamicDialogConfig); + + readonly actions = createDispatchMap({ fetchLicenses: FetchLicenses }); + + readonly licenses = select(LicensesSelectors.getLicenses); + readonly licensesLoading = select(LicensesSelectors.getLoading); - actions = createDispatchMap({ loadLicenses: LoadAllLicenses }); + private readonly data = this.config.data ?? {}; + private readonly initialLicenseId = this.data.metadata?.license?.id || null; - licenses = select(LicensesSelectors.getLicenses); - licensesLoading = select(LicensesSelectors.getLoading); + readonly initialLicenseOptions = this.resolveLicenseOptions(this.data.metadata); + readonly selectedLicenseId = signal(this.initialLicenseId); + readonly licenseState = signal(null); - selectedLicenseId = signal(null); - selectedLicenseOptions = signal(null); - metadata: MetadataModel | null = null; - isSubmitting = signal(false); + readonly selectedLicense = computed( + () => this.licenses().find((license) => license.id === this.selectedLicenseId()) ?? null + ); - licenseComponent = viewChild('licenseComponent'); + readonly isUnchanged = computed(() => { + const license = this.selectedLicense(); + if (!license || license.id !== this.initialLicenseId) { + return false; + } + + if (!license.requiredFields.length) { + return true; + } + + const initial = this.initialLicenseOptions; + const current = this.licenseState()?.licenseOptions; - get isInvalid(): boolean { return ( - !!this.licenseComponent()?.selectedLicense()?.requiredFields?.length && - !!this.licenseComponent()?.licenseForm.invalid + !!initial && !!current && initial.year === current.year && initial.copyrightHolders === current.copyrightHolders ); - } + }); - ngOnInit(): void { - this.actions.loadLicenses(); - this.metadata = this.config.data?.metadata || null; - if (this.metadata?.license) { - this.selectedLicenseId.set(this.metadata.license.id || null); - if (this.metadata.nodeLicense) { - this.selectedLicenseOptions.set({ - copyrightHolders: this.metadata.nodeLicense.copyrightHolders?.join(', ') || '', - year: this.metadata.nodeLicense.year || new Date().getFullYear().toString(), - }); - } + readonly isSaveDisabled = computed(() => { + const license = this.selectedLicense(); + if (this.licensesLoading() || !license) { + return true; } - } - - onSelectLicense(license: LicenseModel): void { - this.selectedLicenseId.set(license.id); - } - onCreateLicense(event: { id: string; licenseOptions: LicenseOptions }): void { - const selectedLicense = this.licenses().find((license) => license.id === event.id); - if (selectedLicense) { - this.dialogRef.close({ - licenseId: selectedLicense.id, - licenseOptions: event.licenseOptions, - }); + if (license.requiredFields.length && (this.licenseState()?.formInvalid ?? true)) { + return true; } - this.isSubmitting.set(false); + return this.isUnchanged(); + }); + + ngOnInit(): void { + this.actions.fetchLicenses(this.data.licensesUrl); } save(): void { - const selectedLicenseId = this.selectedLicenseId(); - if (!selectedLicenseId) return; - - const selectedLicense = this.licenses().find((license) => license.id === selectedLicenseId); - if (!selectedLicense) return; - - this.isSubmitting.set(true); - - if (selectedLicense.requiredFields?.length) { - this.licenseComponent()?.saveLicense(); - } else { - this.dialogRef.close({ - licenseId: selectedLicense.id, - }); + const license = this.selectedLicense(); + if (!license || this.isSaveDisabled()) { + return; } + + const result: LicenseDialogResult = { + licenseId: license.id, + licenseOptions: license.requiredFields.length ? this.licenseState()?.licenseOptions : undefined, + }; + this.dialogRef.close(result); } cancel(): void { - this.licenseComponent()?.cancel(); this.dialogRef.close(); } + + private resolveLicenseOptions(metadata?: MetadataModel | null): LicenseOptions | null { + const nodeLicense = metadata?.nodeLicense; + if (!nodeLicense) { + return null; + } + + return { + copyrightHolders: nodeLicense.copyrightHolders?.join(', ') ?? '', + year: nodeLicense.year ?? '', + }; + } } diff --git a/src/app/features/metadata/metadata.component.spec.ts b/src/app/features/metadata/metadata.component.spec.ts index 1f6cfb69d..d8fd626b7 100644 --- a/src/app/features/metadata/metadata.component.spec.ts +++ b/src/app/features/metadata/metadata.component.spec.ts @@ -1,5 +1,9 @@ +import { Store } from '@ngxs/store'; + import { MockComponents, MockProvider } from 'ng-mocks'; +import { of } from 'rxjs'; + import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ActivatedRoute, Router } from '@angular/router'; @@ -9,19 +13,45 @@ import { SubHeaderComponent } from '@osf/shared/components/sub-header/sub-header import { ResourceType } from '@osf/shared/enums/resource-type.enum'; import { CustomConfirmationService } from '@osf/shared/services/custom-confirmation.service'; import { CustomDialogService } from '@osf/shared/services/custom-dialog.service'; +import { SignpostingService } from '@osf/shared/services/signposting.service'; import { ToastService } from '@osf/shared/services/toast.service'; +import { CollectionsSelectors, GetProjectSubmissions } from '@osf/shared/stores/collections'; +import { + ContributorsSelectors, + GetBibliographicContributors, + LoadMoreBibliographicContributors, +} from '@osf/shared/stores/contributors'; +import { FetchResourceInstitutions, InstitutionsSelectors } from '@osf/shared/stores/institutions'; import { RegistrationProviderSelectors } from '@osf/shared/stores/registration-provider'; - +import { + FetchChildrenSubjects, + FetchSelectedSubjects, + FetchSubjects, + SubjectsSelectors, + UpdateResourceSubjects, +} from '@osf/shared/stores/subjects'; + +import { MOCK_LICENSE } from '@testing/mocks/license.mock'; import { MOCK_PROJECT_METADATA } from '@testing/mocks/project-metadata.mock'; import { provideOSFCore } from '@testing/osf.testing.provider'; import { CustomConfirmationServiceMockBuilder } from '@testing/providers/custom-confirmation-provider.mock'; -import { CustomDialogServiceMockBuilder } from '@testing/providers/custom-dialog-provider.mock'; +import { + CustomDialogServiceMock, + CustomDialogServiceMockBuilder, +} from '@testing/providers/custom-dialog-provider.mock'; import { ActivatedRouteMockBuilder } from '@testing/providers/route-provider.mock'; import { RouterMockBuilder } from '@testing/providers/router-provider.mock'; -import { mergeSignalOverrides, provideMockStore, SignalOverride } from '@testing/providers/store-provider.mock'; +import { SignpostingServiceMock } from '@testing/providers/signposting-provider.mock'; +import { + BaseSetupOverrides, + mergeSignalOverrides, + provideMockStore, + SignalOverride, +} from '@testing/providers/store-provider.mock'; import { ToastServiceMockBuilder } from '@testing/providers/toast-provider.mock'; import { MetadataAffiliatedInstitutionsComponent } from './components/metadata-affiliated-institutions/metadata-affiliated-institutions.component'; +import { MetadataCollectionsComponent } from './components/metadata-collections/metadata-collections.component'; import { MetadataContributorsComponent } from './components/metadata-contributors/metadata-contributors.component'; import { MetadataDateInfoComponent } from './components/metadata-date-info/metadata-date-info.component'; import { MetadataDescriptionComponent } from './components/metadata-description/metadata-description.component'; @@ -29,59 +59,107 @@ import { MetadataFundingComponent } from './components/metadata-funding/metadata import { MetadataLicenseComponent } from './components/metadata-license/metadata-license.component'; import { MetadataPublicationDoiComponent } from './components/metadata-publication-doi/metadata-publication-doi.component'; import { MetadataRegistrationDoiComponent } from './components/metadata-registration-doi/metadata-registration-doi.component'; +import { MetadataRegistryInfoComponent } from './components/metadata-registry-info/metadata-registry-info.component'; import { MetadataResourceInformationComponent } from './components/metadata-resource-information/metadata-resource-information.component'; import { MetadataSubjectsComponent } from './components/metadata-subjects/metadata-subjects.component'; import { MetadataTagsComponent } from './components/metadata-tags/metadata-tags.component'; import { MetadataTitleComponent } from './components/metadata-title/metadata-title.component'; +import { AffiliatedInstitutionsDialogComponent } from './dialogs/affiliated-institutions-dialog/affiliated-institutions-dialog.component'; +import { ContributorsDialogComponent } from './dialogs/contributors-dialog/contributors-dialog.component'; +import { DescriptionDialogComponent } from './dialogs/description-dialog/description-dialog.component'; +import { EditTitleDialogComponent } from './dialogs/edit-title-dialog/edit-title-dialog.component'; +import { FundingDialogComponent } from './dialogs/funding-dialog/funding-dialog.component'; +import { LicenseDialogComponent } from './dialogs/license-dialog/license-dialog.component'; +import { PublicationDoiDialogComponent } from './dialogs/publication-doi-dialog/publication-doi-dialog.component'; +import { ResourceInformationDialogComponent } from './dialogs/resource-information-dialog/resource-information-dialog.component'; +import { ResourceInfoTooltipComponent } from './dialogs/resource-tooltip-info/resource-tooltip-info.component'; import { MetadataComponent } from './metadata.component'; -import { MetadataSelectors } from './store'; +import { + GetCedarMetadataRecords, + GetCedarMetadataTemplates, + GetCustomItemMetadata, + GetResourceMetadata, + MetadataSelectors, + UpdateResourceDetails, + UpdateResourceLicense, +} from './store'; describe('MetadataComponent', () => { let component: MetadataComponent; let fixture: ComponentFixture; - let activatedRouteMock: ReturnType; + let store: Store; let routerMock: ReturnType; let customDialogServiceMock: ReturnType; let toastServiceMock: ReturnType; let customConfirmationServiceMock: ReturnType; + let signpostingServiceMock: ReturnType; + + const defaultResourceId = 'test-resource-id'; + const mockMetadata = { + ...MOCK_PROJECT_METADATA, + license: MOCK_LICENSE, + }; + + interface SetupOverrides extends BaseSetupOverrides { + resourceType?: ResourceType; + detectChanges?: boolean; + } - const mockMetadata = MOCK_PROJECT_METADATA; - const mockResourceId = 'test-resource-id'; + function setup(overrides: SetupOverrides = {}) { + const resourceType = overrides.resourceType ?? ResourceType.Project; + const resourceId = overrides.routeParams?.['id'] ?? defaultResourceId; - function setup(selectorOverrides?: SignalOverride[]) { - activatedRouteMock = ActivatedRouteMockBuilder.create() - .withId(mockResourceId) - .withData({ resourceType: ResourceType.Project }) + const activatedRouteMock = ActivatedRouteMockBuilder.create() + .withParentRoute({ + snapshot: { + data: { resourceType }, + }, + parent: { + snapshot: { + params: { id: resourceId }, + }, + }, + } as never) .build(); const defaultSignals: SignalOverride[] = [ { selector: MetadataSelectors.getResourceMetadata, value: mockMetadata }, { selector: MetadataSelectors.getLoading, value: false }, { selector: MetadataSelectors.getSubmitting, value: false }, + { selector: MetadataSelectors.getCustomItemMetadata, value: null }, { selector: MetadataSelectors.getCedarRecords, value: [] }, { selector: MetadataSelectors.getCedarTemplates, value: null }, + { selector: MetadataSelectors.hasWriteAccess, value: true }, + { selector: MetadataSelectors.hasAdminAccess, value: true }, + { selector: ContributorsSelectors.getBibliographicContributors, value: [] }, + { selector: ContributorsSelectors.isBibliographicContributorsLoading, value: false }, + { selector: ContributorsSelectors.hasMoreBibliographicContributors, value: false }, + { selector: SubjectsSelectors.getSelectedSubjects, value: [] }, + { selector: SubjectsSelectors.areSelectedSubjectsLoading, value: false }, + { selector: InstitutionsSelectors.getResourceInstitutions, value: [] }, + { selector: InstitutionsSelectors.areResourceInstitutionsLoading, value: false }, + { selector: InstitutionsSelectors.areResourceInstitutionsSubmitting, value: false }, + { selector: CollectionsSelectors.getCurrentProjectSubmissions, value: [] }, + { selector: CollectionsSelectors.getCurrentProjectSubmissionsLoading, value: false }, { selector: RegistrationProviderSelectors.getBrandedProvider, value: null }, { selector: UserSelectors.isProjectReadOnly, value: false }, ]; - const signals = mergeSignalOverrides(defaultSignals, selectorOverrides); - - Object.defineProperty(activatedRouteMock, 'parent', { - value: { - snapshot: { - data: { resourceType: ResourceType.Project }, - }, - }, - writable: true, - configurable: true, - }); routerMock = RouterMockBuilder.create().build(); - - customDialogServiceMock = CustomDialogServiceMockBuilder.create().withDefaultOpen().build(); - + customDialogServiceMock = CustomDialogServiceMockBuilder.create() + .withOpen( + vi.fn().mockReturnValue({ + onClose: { + pipe: vi.fn().mockReturnValue({ subscribe: vi.fn() }), + subscribe: vi.fn(), + }, + close: vi.fn(), + }) + ) + .build(); toastServiceMock = ToastServiceMockBuilder.create().build(); - customConfirmationServiceMock = CustomConfirmationServiceMockBuilder.create().build(); + signpostingServiceMock = SignpostingServiceMock.simple(); TestBed.configureTestingModule({ imports: [ @@ -100,7 +178,9 @@ describe('MetadataComponent', () => { MetadataDateInfoComponent, MetadataTagsComponent, MetadataTitleComponent, - MetadataRegistrationDoiComponent + MetadataRegistrationDoiComponent, + MetadataCollectionsComponent, + MetadataRegistryInfoComponent ), ], providers: [ @@ -110,166 +190,266 @@ describe('MetadataComponent', () => { MockProvider(CustomDialogService, customDialogServiceMock), MockProvider(ToastService, toastServiceMock), MockProvider(CustomConfirmationService, customConfirmationServiceMock), + MockProvider(SignpostingService, signpostingServiceMock), provideMockStore({ - signals: signals, + signals: mergeSignalOverrides(defaultSignals, overrides.selectorOverrides), }), ], }); + store = TestBed.inject(Store); fixture = TestBed.createComponent(MetadataComponent); component = fixture.componentInstance; + + if (overrides.detectChanges !== false) { + fixture.detectChanges(); + } } - it('should create', () => { + it('should load project metadata resources on init', () => { setup(); - expect(component).toBeTruthy(); - }); - it('should handle tab change for OSF tab', () => { - setup(); - const tabId = 'osf'; - const navigateSpy = vi.spyOn(routerMock, 'navigate'); + expect(store.dispatch).toHaveBeenCalledWith(new GetResourceMetadata(defaultResourceId, ResourceType.Project)); + expect(store.dispatch).toHaveBeenCalledWith(new GetCustomItemMetadata(defaultResourceId)); + expect(store.dispatch).toHaveBeenCalledWith( + new GetBibliographicContributors(defaultResourceId, ResourceType.Project) + ); + expect(store.dispatch).toHaveBeenCalledWith(new FetchResourceInstitutions(defaultResourceId, ResourceType.Project)); + expect(store.dispatch).toHaveBeenCalledWith(new GetCedarMetadataRecords(defaultResourceId, ResourceType.Project)); + expect(store.dispatch).toHaveBeenCalledWith(new GetCedarMetadataTemplates()); + expect(store.dispatch).toHaveBeenCalledWith(new FetchSelectedSubjects(defaultResourceId, ResourceType.Project)); + expect(store.dispatch).toHaveBeenCalledWith(new GetProjectSubmissions(defaultResourceId)); + expect(store.dispatch).toHaveBeenCalledWith(new FetchSubjects(ResourceType.Project)); + expect(signpostingServiceMock.addMetadataSignposting).toHaveBeenCalledWith(defaultResourceId); + }); - component.onTabChange(tabId); + it('should not fetch project submissions for registrations', () => { + setup({ resourceType: ResourceType.Registration }); - expect(component.selectedTab()).toBe(tabId); - expect(navigateSpy).toHaveBeenCalledTimes(0); + expect(store.dispatch).not.toHaveBeenCalledWith(new GetProjectSubmissions(defaultResourceId)); + expect(store.dispatch).toHaveBeenCalledWith(new FetchSubjects(ResourceType.Registration, 'osf')); }); - it('should toggle edit mode', () => { + it('should remove signposting tags on destroy', () => { setup(); - const initialReadonly = component.cedarFormReadonly(); - component.toggleEditMode(); + fixture.destroy(); - expect(component.cedarFormReadonly()).toBe(!initialReadonly); + expect(signpostingServiceMock.removeSignpostingLinkTags).toHaveBeenCalled(); }); - it('should handle tags changed', () => { - setup(); - const tags = ['tag1', 'tag2']; + it('should compute loading and resource type flags', () => { + setup({ + selectorOverrides: [{ selector: MetadataSelectors.getLoading, value: true }], + }); - expect(() => component.onTagsChanged(tags)).not.toThrow(); + expect(component.isLoading()).toBe(true); + expect(component.isProjectType()).toBe(true); + expect(component.isRegistrationType()).toBe(false); }); - it('should open edit contributor dialog', () => { + it('should hide edit doi for public projects that already have identifiers', () => { setup(); - const openSpy = vi.spyOn(customDialogServiceMock, 'open'); - expect(openSpy).toHaveBeenCalledTimes(0); - expect(() => component.openEditContributorDialog()).toThrow(); - expect(openSpy).toHaveBeenCalled(); + expect(component.hideEditDoi()).toBe(true); }); - it('should open edit title dialog', () => { - setup(); - const openSpy = vi.spyOn(customDialogServiceMock, 'open'); - - component.openEditTitleDialog(); + it('should mark tags and subjects read-only when project is read-only', () => { + setup({ + selectorOverrides: [{ selector: UserSelectors.isProjectReadOnly, value: true }], + }); - expect(openSpy).toHaveBeenCalled(); + expect(component.isTagsReadOnly()).toBe(true); + expect(component.isSubjectsReadOnly()).toBe(true); + expect(component.disabledButtonTooltip()).toBe('common.errorMessages.actionUnavailable'); }); - it('should open edit description dialog', () => { + it('should select osf tab without navigation', () => { setup(); - const openSpy = vi.spyOn(customDialogServiceMock, 'open'); + const navigateSpy = vi.spyOn(routerMock, 'navigate'); - component.openEditDescriptionDialog(); + component.onTabChange('osf'); - expect(openSpy).toHaveBeenCalled(); + expect(component.selectedTab()).toBe('osf'); + expect(navigateSpy).not.toHaveBeenCalled(); }); - it('should open edit resource information dialog', () => { + it('should toggle cedar edit mode', () => { setup(); - const openSpy = vi.spyOn(customDialogServiceMock, 'open'); + const initialReadonly = component.cedarFormReadonly(); - component.openEditResourceInformationDialog(); + component.toggleEditMode(); - expect(openSpy).toHaveBeenCalled(); + expect(component.cedarFormReadonly()).toBe(!initialReadonly); }); - it('should show resource info tooltip', () => { + it('should dispatch metadata update when tags change', () => { setup(); - const openSpy = vi.spyOn(customDialogServiceMock, 'open'); + (store.dispatch as ReturnType).mockClear(); - component.onShowResourceInfo(); + component.onTagsChanged(['tag1', 'tag2']); - expect(openSpy).toHaveBeenCalled(); + expect(store.dispatch).toHaveBeenCalledWith( + new UpdateResourceDetails(defaultResourceId, ResourceType.Project, { tags: ['tag1', 'tag2'] }) + ); }); - it('should open edit license dialog', () => { + it('should load more contributors', () => { setup(); - const openSpy = vi.spyOn(customDialogServiceMock, 'open'); + (store.dispatch as ReturnType).mockClear(); - component.openEditLicenseDialog(); + component.handleLoadMoreContributors(); - expect(openSpy).toHaveBeenCalled(); + expect(store.dispatch).toHaveBeenCalledWith( + new LoadMoreBibliographicContributors(defaultResourceId, ResourceType.Project) + ); }); - it('should open edit funding dialog', () => { + it('should fetch and update subjects', () => { setup(); - const openSpy = vi.spyOn(customDialogServiceMock, 'open'); + (store.dispatch as ReturnType).mockClear(); + + component.getSubjectChildren('parent-1'); + component.searchSubjects('psychology'); + component.updateSelectedSubjects([{ id: 'subject-1' } as never]); + + expect(store.dispatch).toHaveBeenCalledWith(new FetchChildrenSubjects('parent-1')); + expect(store.dispatch).toHaveBeenCalledWith( + new FetchSubjects(ResourceType.Project, component.provider, 'psychology') + ); + expect(store.dispatch).toHaveBeenCalledWith( + new UpdateResourceSubjects(defaultResourceId, ResourceType.Project, [{ id: 'subject-1' } as never]) + ); + }); - component.openEditFundingDialog(); + it('should open metadata edit dialogs with expected components', () => { + setup(); + const openSpy = customDialogServiceMock.open; - expect(openSpy).toHaveBeenCalled(); + component.openEditTitleDialog(); + component.openEditDescriptionDialog(); + component.openEditResourceInformationDialog(); + component.onShowResourceInfo(); + component.openEditFundingDialog(); + component.openEditAffiliatedInstitutionsDialog(); + component.openEditContributorDialog(); + + expect(openSpy).toHaveBeenCalledWith(EditTitleDialogComponent, expect.objectContaining({ width: '500px' })); + expect(openSpy).toHaveBeenCalledWith(DescriptionDialogComponent, expect.objectContaining({ width: '500px' })); + expect(openSpy).toHaveBeenCalledWith( + ResourceInformationDialogComponent, + expect.objectContaining({ width: '500px' }) + ); + expect(openSpy).toHaveBeenCalledWith(ResourceInfoTooltipComponent, expect.objectContaining({ width: '850px' })); + expect(openSpy).toHaveBeenCalledWith(FundingDialogComponent, expect.objectContaining({ width: '600px' })); + expect(openSpy).toHaveBeenCalledWith( + AffiliatedInstitutionsDialogComponent, + expect.objectContaining({ width: '500px' }) + ); + expect(openSpy).toHaveBeenCalledWith( + ContributorsDialogComponent, + expect.objectContaining({ + data: { + resourceId: defaultResourceId, + resourceType: ResourceType.Project, + }, + }) + ); }); - it('should open edit affiliated institutions dialog', () => { + it('should open license dialog with project licenses url', () => { setup(); - const openSpy = vi.spyOn(customDialogServiceMock, 'open'); - component.openEditAffiliatedInstitutionsDialog(); + component.openEditLicenseDialog(); - expect(openSpy).toHaveBeenCalled(); + expect(customDialogServiceMock.open).toHaveBeenCalledWith( + LicenseDialogComponent, + expect.objectContaining({ + header: 'project.metadata.license.dialog.header', + width: '600px', + data: { + metadata: mockMetadata, + licensesUrl: 'http://localhost:8000/v2/licenses/', + }, + }) + ); }); - it('should handle subject children fetch', () => { - setup(); - const parentId = 'parent-subject-id'; + it('should open license dialog with registry provider licenses link', () => { + const licensesLink = 'https://api.osf.io/v2/providers/registrations/osf/licenses/'; + setup({ + resourceType: ResourceType.Registration, + selectorOverrides: [ + { selector: RegistrationProviderSelectors.getBrandedProvider, value: { id: 'osf', licensesLink } }, + ], + }); - expect(() => component.getSubjectChildren(parentId)).not.toThrow(); + component.openEditLicenseDialog(); + + expect(customDialogServiceMock.open).toHaveBeenCalledWith( + LicenseDialogComponent, + expect.objectContaining({ + data: { + metadata: mockMetadata, + licensesUrl: licensesLink, + }, + }) + ); }); - it('should handle subject search', () => { + it('should update resource license when license dialog closes with a result', () => { setup(); - const searchTerm = 'test search'; + customDialogServiceMock.open.mockReturnValue( + CustomDialogServiceMock.dialogRefWithClose( + of({ + licenseId: MOCK_LICENSE.id, + licenseOptions: { year: '2024', copyrightHolders: 'Jane Doe' }, + }) + ) + ); + (store.dispatch as ReturnType).mockClear(); + (store.dispatch as ReturnType).mockReturnValue(of(undefined)); - expect(() => component.searchSubjects(searchTerm)).not.toThrow(); + component.openEditLicenseDialog(); + + expect(store.dispatch).toHaveBeenCalledWith( + new UpdateResourceLicense(defaultResourceId, ResourceType.Project, MOCK_LICENSE.id, { + year: '2024', + copyrightHolders: 'Jane Doe', + }) + ); + expect(toastServiceMock.showSuccess).toHaveBeenCalledWith('project.metadata.license.updated'); }); - it('should handle edit DOI for project', () => { + it('should confirm doi creation for projects', () => { setup(); - const confirmSpy = vi.spyOn(customConfirmationServiceMock, 'confirmDelete'); component.handleEditDoi(); - expect(confirmSpy).toHaveBeenCalled(); + expect(customConfirmationServiceMock.confirmDelete).toHaveBeenCalled(); }); - it('should open add record', () => { - setup(); - const navigateSpy = vi.spyOn(routerMock, 'navigate'); + it('should open publication doi dialog for registrations', () => { + setup({ resourceType: ResourceType.Registration }); - component.openAddRecord(); + component.handleEditDoi(); - expect(navigateSpy).toHaveBeenCalled(); + expect(customDialogServiceMock.open).toHaveBeenCalledWith( + PublicationDoiDialogComponent, + expect.objectContaining({ + header: 'project.metadata.doi.dialog.header', + data: mockMetadata.publicationDoi, + }) + ); }); - it('should handle cedar form change template', () => { + it('should navigate when opening add record or changing cedar template', () => { setup(); const navigateSpy = vi.spyOn(routerMock, 'navigate'); + component.openAddRecord(); component.onCedarFormChangeTemplate(); - expect(navigateSpy).toHaveBeenCalled(); - }); - - it('should handle isProjectReadOnly', () => { - setup([{ selector: UserSelectors.isProjectReadOnly, value: true }]); - - expect(component.isTagsReadOnly()).toBe(true); - expect(component.isSubjectsReadOnly()).toBe(true); - expect(component.disabledButtonTooltip()).toBe('common.errorMessages.actionUnavailable'); + expect(navigateSpy).toHaveBeenCalledTimes(2); }); }); diff --git a/src/app/features/metadata/metadata.component.ts b/src/app/features/metadata/metadata.component.ts index ebbde85c7..83ca93907 100644 --- a/src/app/features/metadata/metadata.component.ts +++ b/src/app/features/metadata/metadata.component.ts @@ -33,7 +33,6 @@ import { ContributorsSelectors, GetBibliographicContributors, LoadMoreBibliographicContributors, - UpdateContributorsSearchValue, } from '@osf/shared/stores/contributors'; import { FetchResourceInstitutions, @@ -74,6 +73,7 @@ import { LicenseDialogComponent } from './dialogs/license-dialog/license-dialog. import { PublicationDoiDialogComponent } from './dialogs/publication-doi-dialog/publication-doi-dialog.component'; import { ResourceInformationDialogComponent } from './dialogs/resource-information-dialog/resource-information-dialog.component'; import { ResourceInfoTooltipComponent } from './dialogs/resource-tooltip-info/resource-tooltip-info.component'; +import { LicenseDialogData, LicenseDialogResult } from './models/license-dialog.model'; import { CedarMetadataRecordModel, CedarMetadataTemplateModel, @@ -81,7 +81,6 @@ import { DialogValueModel, } from './models'; import { - CreateCedarMetadataRecord, CreateDoi, GetCedarMetadataRecords, GetCedarMetadataTemplates, @@ -184,14 +183,12 @@ export class MetadataComponent implements OnInit, OnDestroy { getCedarRecords: GetCedarMetadataRecords, getCedarTemplates: GetCedarMetadataTemplates, - createCedarRecord: CreateCedarMetadataRecord, updateCedarRecord: UpdateCedarMetadataRecord, fetchSubjects: FetchSubjects, fetchSelectedSubjects: FetchSelectedSubjects, fetchChildrenSubjects: FetchChildrenSubjects, updateResourceSubjects: UpdateResourceSubjects, - updateContributorsSearchValue: UpdateContributorsSearchValue, getProjectSubmissions: GetProjectSubmissions, }); @@ -308,7 +305,7 @@ export class MetadataComponent implements OnInit, OnDestroy { this.selectedTab.set(tab.id as MetadataResourceEnum); - if (tab.type === 'cedar') { + if (tab.type === MetadataResourceEnum.CEDAR) { this.selectedCedarRecord.set(null); this.selectedCedarTemplate.set(null); const currentRecordId = this.activeRoute.snapshot.paramMap.get('recordId'); @@ -466,24 +463,28 @@ export class MetadataComponent implements OnInit, OnDestroy { } openEditLicenseDialog(): void { + const licensesUrl = this.isProjectType() + ? `${this.environment.apiDomainUrl}/v2/licenses/` + : this.registryProvider()?.licensesLink; + + const data: LicenseDialogData = { metadata: this.metadata(), licensesUrl }; + this.customDialogService .open(LicenseDialogComponent, { header: 'project.metadata.license.dialog.header', width: '600px', - data: { - metadata: this.metadata(), - }, + data, }) .onClose.pipe( - filter((result) => !!result && result.licenseId), - switchMap((result) => { - return this.actions.updateResourceLicense( + filter((result): result is LicenseDialogResult => !!result?.licenseId), + switchMap((result) => + this.actions.updateResourceLicense( this.resourceId, this.resourceType(), result.licenseId, result.licenseOptions - ); - }) + ) + ) ) .subscribe(() => this.toastService.showSuccess('project.metadata.license.updated')); } diff --git a/src/app/features/metadata/models/cedar-editor-element.model.ts b/src/app/features/metadata/models/cedar-editor-element.model.ts index 1bba87eac..5cdfdf014 100644 --- a/src/app/features/metadata/models/cedar-editor-element.model.ts +++ b/src/app/features/metadata/models/cedar-editor-element.model.ts @@ -1,6 +1,10 @@ export interface CedarEditorElement extends HTMLElement { currentMetadata?: unknown; instanceObject?: unknown; + templateAndInstanceObject?: { + templateObject: unknown; + instanceObject: unknown; + }; dataQualityReport?: { isValid: boolean; }; diff --git a/src/app/features/metadata/models/license-dialog.model.ts b/src/app/features/metadata/models/license-dialog.model.ts new file mode 100644 index 000000000..9acc2bd90 --- /dev/null +++ b/src/app/features/metadata/models/license-dialog.model.ts @@ -0,0 +1,13 @@ +import { LicenseOptions } from '@osf/shared/models/license/license.model'; + +import { MetadataModel } from './metadata.model'; + +export interface LicenseDialogData { + metadata?: MetadataModel | null; + licensesUrl?: string; +} + +export interface LicenseDialogResult { + licenseId: string; + licenseOptions?: LicenseOptions; +} diff --git a/src/app/features/my-projects/constants/project-filter-options.const.ts b/src/app/features/my-projects/constants/project-filter-options.const.ts index 6b5aec3d7..fb349d621 100644 --- a/src/app/features/my-projects/constants/project-filter-options.const.ts +++ b/src/app/features/my-projects/constants/project-filter-options.const.ts @@ -1,5 +1,5 @@ import { ResourceSearchMode } from '@osf/shared/enums/resource-search-mode.enum'; -import { TabOption } from '@shared/models/tab-option.model'; +import { TabOption } from '@osf/shared/models/tab-option.model'; export const PROJECT_FILTER_OPTIONS: TabOption[] = [ { diff --git a/src/app/features/my-projects/my-projects.component.html b/src/app/features/my-projects/my-projects.component.html index b35cc624a..160f95d05 100644 --- a/src/app/features/my-projects/my-projects.component.html +++ b/src/app/features/my-projects/my-projects.component.html @@ -24,8 +24,9 @@ } @@ -43,7 +44,7 @@ [options]="projectFilterOption" [(selectedValue)]="selectedProjectFilterOption" [fullWidth]="true" - (changeValue)="onProjectFilterChange()" + (changeValue)="onFilterChange()" > @@ -69,7 +70,7 @@ [emptyMessageKey]="projectsEmptyMessageKey()" (pageChange)="onPageChange($event)" (sort)="onSort($event)" - (itemClick)="navigateToProject($event)" + (itemClick)="navigateToItem($event)" /> @@ -89,7 +90,7 @@ [isLoading]="isLoading()" (pageChange)="onPageChange($event)" (sort)="onSort($event)" - (itemClick)="navigateToRegistry($event)" + (itemClick)="navigateToItem($event)" /> @@ -109,7 +110,7 @@ [isLoading]="isLoading()" (pageChange)="onPageChange($event)" (sort)="onSort($event)" - (itemClick)="navigateToProject($event)" + (itemClick)="navigateToItem($event)" /> @@ -129,7 +130,7 @@ [isLoading]="isLoading()" (pageChange)="onPageChange($event)" (sort)="onSort($event)" - (itemClick)="navigateToProject($event)" + (itemClick)="navigateToItem($event)" /> diff --git a/src/app/features/my-projects/my-projects.component.spec.ts b/src/app/features/my-projects/my-projects.component.spec.ts index 3144bb074..0aa3c3eed 100644 --- a/src/app/features/my-projects/my-projects.component.spec.ts +++ b/src/app/features/my-projects/my-projects.component.spec.ts @@ -18,35 +18,46 @@ import { SortOrder } from '@osf/shared/enums/sort-order.enum'; import { IS_MEDIUM } from '@osf/shared/helpers/breakpoints.tokens'; import { CustomDialogService } from '@osf/shared/services/custom-dialog.service'; import { ProjectRedirectDialogService } from '@osf/shared/services/project-redirect-dialog.service'; -import { BookmarksSelectors, GetBookmarksCollectionId } from '@osf/shared/stores/bookmarks'; -import { ClearMyResources, MyResourcesSelectors } from '@osf/shared/stores/my-resources'; +import { BookmarksSelectors, GetAllMyBookmarks, GetBookmarksCollectionId } from '@osf/shared/stores/bookmarks'; +import { ClearMyResources, GetMyPreprints, GetMyProjects, MyResourcesSelectors } from '@osf/shared/stores/my-resources'; +import { MOCK_MY_RESOURCES_ITEM_PROJECT } from '@testing/mocks/my-resources.mock'; import { provideOSFCore } from '@testing/osf.testing.provider'; import { CustomDialogServiceMock, CustomDialogServiceMockType } from '@testing/providers/custom-dialog-provider.mock'; import { MyProjectsQueryServiceMock, MyProjectsQueryServiceMockType, } from '@testing/providers/my-projects-query.service.mock'; -import { - MyProjectsTableParamsServiceMock, - MyProjectsTableParamsServiceMockType, -} from '@testing/providers/my-projects-table-params.service.mock'; +import { MyProjectsTableParamsServiceMock } from '@testing/providers/my-projects-table-params.service.mock'; import { ProjectRedirectDialogServiceMock, ProjectRedirectDialogServiceMockType, } from '@testing/providers/project-redirect-dialog.service.mock'; import { ActivatedRouteMockBuilder } from '@testing/providers/route-provider.mock'; import { RouterMockBuilder, RouterMockType } from '@testing/providers/router-provider.mock'; -import { mergeSignalOverrides, provideMockStore, SignalOverride } from '@testing/providers/store-provider.mock'; +import { + BaseSetupOverrides, + mergeSignalOverrides, + provideMockStore, + SignalOverride, +} from '@testing/providers/store-provider.mock'; import { CreateProjectDialogComponent } from './components/create-project-dialog/create-project-dialog.component'; +import { ProjectDownloadMenuComponent } from './components/project-download-menu/project-download-menu.component'; import { PROJECT_FILTER_OPTIONS } from './constants/project-filter-options.const'; import { VISIBILITY_FILTER_OPTIONS } from './constants/visibility-filter-options.const'; import { MyProjectsQueryService } from './services/my-projects-query.service'; import { MyProjectsTableParamsService } from './services/my-projects-table-params.service'; +import { ProjectDownloadOptionsService } from './services/project-download-options.service'; import { MyProjectsTab } from './enums'; import { MyProjectsComponent } from './my-projects.component'; +interface SetupOverrides extends BaseSetupOverrides { + queryModelOverrides?: { search?: string }; + routeQueryParams?: Record; + rawParams?: Record; +} + describe('MyProjectsComponent', () => { let component: MyProjectsComponent; let fixture: ComponentFixture; @@ -55,20 +66,9 @@ describe('MyProjectsComponent', () => { let customDialogService: CustomDialogServiceMockType; let projectRedirectDialogService: ProjectRedirectDialogServiceMockType; let queryServiceMock: MyProjectsQueryServiceMockType; - let tableParamsServiceMock: MyProjectsTableParamsServiceMockType; - - const projectItem = { - id: 'p1', - type: 'nodes', - title: 'Project 1', - dateCreated: '2024-01-01', - dateModified: '2024-01-02', - isPublic: true, - contributors: [], - }; const defaultSignals: SignalOverride[] = [ - { selector: MyResourcesSelectors.getProjects, value: [projectItem] }, + { selector: MyResourcesSelectors.getProjects, value: [MOCK_MY_RESOURCES_ITEM_PROJECT] }, { selector: MyResourcesSelectors.getRegistrations, value: [] }, { selector: MyResourcesSelectors.getPreprints, value: [] }, { selector: MyResourcesSelectors.getTotalProjects, value: 1 }, @@ -80,32 +80,38 @@ describe('MyProjectsComponent', () => { { selector: UserSelectors.isProjectCreationDisabled, value: false }, ]; - function setup( - selectorOverrides?: SignalOverride[], - queryModelOverrides?: { search?: string }, - routeQueryParams: Record = { tab: '1', page: '1', size: '10' } - ) { + const defaultRawParams = { tab: '1', page: '1', size: '10' }; + + function setup(overrides: SetupOverrides = {}) { + const routeQueryParams = overrides.routeQueryParams ?? defaultRawParams; + const rawParams = overrides.rawParams ?? routeQueryParams; + routerMock = RouterMockBuilder.create().build(); customDialogService = CustomDialogServiceMock.simple(); projectRedirectDialogService = ProjectRedirectDialogServiceMock.simple(); queryServiceMock = MyProjectsQueryServiceMock.create() - .withRawParams({ tab: '1', page: '1', size: '10' }) + .withRawParams(rawParams) .withQueryModel({ - page: 1, - size: 10, - search: queryModelOverrides?.search ?? '', + page: Number(rawParams['page'] || 1), + size: Number(rawParams['size'] || 10), + search: overrides.queryModelOverrides?.search ?? '', sortColumn: '', sortOrder: SortOrder.Asc, }) .withSelectedTab(MyProjectsTab.Projects) .build(); - tableParamsServiceMock = MyProjectsTableParamsServiceMock.simple(); const routeMock = ActivatedRouteMockBuilder.create().withQueryParams(routeQueryParams).build(); TestBed.configureTestingModule({ imports: [ MyProjectsComponent, - ...MockComponents(SubHeaderComponent, MyProjectsTableComponent, SearchInputComponent, SelectComponent), + ...MockComponents( + SubHeaderComponent, + MyProjectsTableComponent, + ProjectDownloadMenuComponent, + SearchInputComponent, + SelectComponent + ), ], providers: [ provideOSFCore(), @@ -114,9 +120,10 @@ describe('MyProjectsComponent', () => { MockProvider(CustomDialogService, customDialogService), MockProvider(ProjectRedirectDialogService, projectRedirectDialogService), MockProvider(MyProjectsQueryService, queryServiceMock), - MockProvider(MyProjectsTableParamsService, tableParamsServiceMock), + MockProvider(MyProjectsTableParamsService, MyProjectsTableParamsServiceMock.simple()), + MockProvider(ProjectDownloadOptionsService, { clearCache: vi.fn() }), MockProvider(IS_MEDIUM, of(false)), - provideMockStore({ signals: mergeSignalOverrides(defaultSignals, selectorOverrides) }), + provideMockStore({ signals: mergeSignalOverrides(defaultSignals, overrides.selectorOverrides) }), ], }); @@ -130,52 +137,43 @@ describe('MyProjectsComponent', () => { vi.useRealTimers(); }); - it('should create', () => { + it('should init, load bookmarks collection id, and show default empty message', () => { setup(); + expect(component).toBeTruthy(); + expect(store.dispatch).toHaveBeenCalledWith(new GetBookmarksCollectionId()); + expect(component.projectsEmptyMessageKey()).toBe('myProjects.table.emptyState.all.both'); }); it('should disable project creation and show tooltip when isProjectCreationDisabled is true', () => { - setup([{ selector: UserSelectors.isProjectCreationDisabled, value: true }]); + setup({ selectorOverrides: [{ selector: UserSelectors.isProjectCreationDisabled, value: true }] }); expect(component.projectCreationDisabled()).toBe(true); expect(component.buttonTooltip()).toBe('myProjects.header.createProjectDisabledTooltip'); }); - it('should dispatch get bookmarks collection id on init', () => { - setup(); - expect(store.dispatch).toHaveBeenCalledWith(new GetBookmarksCollectionId()); - }); - - it('should delegate page changes to query service', () => { + it('should delegate page and sort changes to query service', () => { setup(); - component.onPageChange({ first: 20, rows: 10 } as { first: number; rows: number }); - - expect(queryServiceMock.handlePageChange).toHaveBeenCalledWith(20, 10, { tab: '1', page: '1', size: '10' }, 1); - }); - it('should delegate sort changes when field exists', () => { - setup(); - component.onSort({ field: 'title', order: SortOrder.Desc } as { field: string; order: SortOrder }); + component.onPageChange({ first: 20, rows: 10 }); + component.onSort({ field: 'title', order: SortOrder.Desc }); + component.onSort({ order: SortOrder.Asc }); - expect(queryServiceMock.handleSort).toHaveBeenCalledWith( - 'title', - SortOrder.Desc, - { tab: '1', page: '1', size: '10' }, - 1 - ); + expect(queryServiceMock.handlePageChange).toHaveBeenCalledWith(20, 10, defaultRawParams, 1); + expect(queryServiceMock.handleSort).toHaveBeenCalledTimes(1); + expect(queryServiceMock.handleSort).toHaveBeenCalledWith('title', SortOrder.Desc, defaultRawParams, 1); }); - it('should not delegate sort when field is missing', () => { + it('should switch tab for numeric values and ignore invalid ones', () => { setup(); - component.onSort({ field: undefined, order: SortOrder.Asc } as { field?: string; order: SortOrder }); + (store.dispatch as Mock).mockClear(); - expect(queryServiceMock.handleSort).not.toHaveBeenCalled(); - }); + component.onTabChange('not-a-number'); + component.onTabChange(null); + component.onTabChange(true); - it('should clear and switch tab when onTabChange receives numeric value', () => { - setup(); - (store.dispatch as Mock).mockClear(); + expect(store.dispatch).not.toHaveBeenCalledWith(new ClearMyResources()); + expect(queryServiceMock.handleTabSwitch).not.toHaveBeenCalled(); component.onTabChange(String(MyProjectsTab.Registrations)); @@ -183,151 +181,123 @@ describe('MyProjectsComponent', () => { expect(component.selectedTab()).toBe(MyProjectsTab.Registrations); expect(component.selectedProjectFilterOption()).toBe(PROJECT_FILTER_OPTIONS[0].value); expect(component.selectedVisibilityFilterOption()).toBe(VISIBILITY_FILTER_OPTIONS[0].value); - expect(queryServiceMock.handleTabSwitch).toHaveBeenCalledWith( - { tab: '1', page: '1', size: '10' }, - MyProjectsTab.Registrations - ); - }); - - it('should ignore invalid tab values', () => { - setup(); - (store.dispatch as Mock).mockClear(); - - component.onTabChange('not-a-number'); - - expect(store.dispatch).not.toHaveBeenCalledWith(new ClearMyResources()); - expect(queryServiceMock.handleTabSwitch).not.toHaveBeenCalled(); + expect(queryServiceMock.handleTabSwitch).toHaveBeenCalledWith(defaultRawParams, MyProjectsTab.Registrations); }); - it('should open create project dialog and redirect after close result', () => { + it('should open create project dialog and redirect only when project id is returned', () => { setup(); - const onClose$ = new Subject<{ project: { id: string } }>(); + const onClose$ = new Subject<{ project?: { id?: string } }>(); customDialogService.open.mockReturnValue(CustomDialogServiceMock.dialogRefWithClose(onClose$.asObservable())); component.createProject(); - onClose$.next({ project: { id: 'project-123' } }); + onClose$.next({ project: {} }); expect(customDialogService.open).toHaveBeenCalledWith(CreateProjectDialogComponent, { header: 'myProjects.header.createProject', width: '850px', }); - expect(projectRedirectDialogService.showProjectRedirectDialog).toHaveBeenCalledWith('project-123'); - }); - - it('should navigate to project and set active project', () => { - setup(); + expect(projectRedirectDialogService.showProjectRedirectDialog).not.toHaveBeenCalled(); - component.navigateToProject(projectItem); + onClose$.next({ project: { id: 'project-123' } }); - expect(component.activeProject()).toEqual(projectItem); - expect(routerMock.navigate).toHaveBeenCalledWith([projectItem.id]); + expect(projectRedirectDialogService.showProjectRedirectDialog).toHaveBeenCalledWith('project-123'); }); - it('should navigate to registry and set active project', () => { + it('should navigate to item', () => { setup(); - component.navigateToRegistry(projectItem); + component.navigateToItem(MOCK_MY_RESOURCES_ITEM_PROJECT); - expect(component.activeProject()).toEqual(projectItem); - expect(routerMock.navigate).toHaveBeenCalledWith([projectItem.id]); + expect(routerMock.navigate).toHaveBeenCalledWith([MOCK_MY_RESOURCES_ITEM_PROJECT.id]); }); - it('should fetch projects on project filter change', () => { + it('should fetch current tab data on filter change and reset page when needed', () => { setup(); - const getMyProjectsSpy = vi.spyOn(component.actions, 'getMyProjects').mockReturnValue(of(void 0)); + (store.dispatch as Mock).mockClear(); - component.onProjectFilterChange(); + component.onFilterChange(); + + expect(store.dispatch).toHaveBeenCalledWith( + new GetMyProjects( + 1, + 10, + { + searchValue: '', + searchFields: ['title', 'tags', 'description'], + sortColumn: '', + sortOrder: SortOrder.Asc, + }, + PROJECT_FILTER_OPTIONS[0].value, + VISIBILITY_FILTER_OPTIONS[0].value + ) + ); + expect(component.isLoading()).toBe(false); + + component.selectedTab.set(MyProjectsTab.Preprints); + (store.dispatch as Mock).mockClear(); + component.onFilterChange(); - expect(getMyProjectsSpy).toHaveBeenCalledWith( - 1, - 10, - { + expect(store.dispatch).toHaveBeenCalledWith( + new GetMyPreprints(1, 10, { searchValue: '', - searchFields: ['title', 'tags', 'description'], + searchFields: ['title', 'tags'], sortColumn: '', sortOrder: SortOrder.Asc, - }, - PROJECT_FILTER_OPTIONS[0].value, - undefined, - VISIBILITY_FILTER_OPTIONS[0].value + }) ); - expect(component.isLoading()).toBe(false); - }); - - it('should fetch projects on visibility filter change', () => { - setup(); - const getMyProjectsSpy = vi.spyOn(component.actions, 'getMyProjects').mockReturnValue(of(void 0)); - - component.onVisibilityFilterChange(); - - expect(getMyProjectsSpy).toHaveBeenCalled(); - expect(component.isLoading()).toBe(false); }); - it('should fetch preprints with preprint search fields', () => { - setup(); - component.selectedTab.set(MyProjectsTab.Preprints); - const getMyPreprintsSpy = vi.spyOn(component.actions, 'getMyPreprints').mockReturnValue(of(void 0)); + it('should reset page on filter change when not on first page', () => { + setup({ rawParams: { tab: '1', page: '3', size: '10' } }); + (store.dispatch as Mock).mockClear(); - component.onProjectFilterChange(); + component.onFilterChange(); - expect(getMyPreprintsSpy).toHaveBeenCalledWith(1, 10, { - searchValue: '', - searchFields: ['title', 'tags'], - sortColumn: '', - sortOrder: SortOrder.Asc, - }); + expect(queryServiceMock.updateParams).toHaveBeenCalledWith( + { page: 1 }, + { tab: '1', page: '3', size: '10' }, + MyProjectsTab.Projects + ); + expect(store.dispatch).not.toHaveBeenCalledWith(expect.any(GetMyProjects)); }); - it('should fetch bookmarks when collection id exists', () => { + it('should fetch bookmarks only when collection id exists', () => { setup(); component.selectedTab.set(MyProjectsTab.Bookmarks); - const getBookmarksSpy = vi.spyOn(component.actions, 'getMyBookmarks').mockReturnValue(of(void 0)); + (store.dispatch as Mock).mockClear(); - component.onProjectFilterChange(); + component.onFilterChange(); - expect(getBookmarksSpy).toHaveBeenCalledWith('bookmark-collection-id', { - searchValue: '', - searchFields: ['title', 'tags', 'description'], - sortColumn: '', - sortOrder: SortOrder.Asc, - }); + expect(store.dispatch).toHaveBeenCalledWith( + new GetAllMyBookmarks('bookmark-collection-id', { + searchValue: '', + searchFields: ['title', 'tags', 'description'], + sortColumn: '', + sortOrder: SortOrder.Asc, + }) + ); }); it('should not fetch bookmarks when collection id is missing', () => { - setup([{ selector: BookmarksSelectors.getBookmarksCollectionId, value: null }]); + setup({ selectorOverrides: [{ selector: BookmarksSelectors.getBookmarksCollectionId, value: null }] }); component.selectedTab.set(MyProjectsTab.Bookmarks); - const getBookmarksSpy = vi.spyOn(component.actions, 'getMyBookmarks').mockReturnValue(of(void 0)); + (store.dispatch as Mock).mockClear(); - component.onProjectFilterChange(); + component.onFilterChange(); - expect(getBookmarksSpy).not.toHaveBeenCalled(); + expect(store.dispatch).not.toHaveBeenCalledWith(expect.any(GetAllMyBookmarks)); expect(component.isLoading()).toBe(true); }); it('should compute no results message key when search is applied', () => { - setup(undefined, { search: 'alpha' }, { tab: '1', page: '1', size: '10', search: 'alpha' }); + setup({ + queryModelOverrides: { search: 'alpha' }, + routeQueryParams: { tab: '1', page: '1', size: '10', search: 'alpha' }, + }); expect(component.projectsEmptyMessageKey()).toBe('common.search.noResultsFound'); }); - it('should compute empty state message key when search is empty', () => { - setup(); - - expect(component.projectsEmptyMessageKey()).toBe('myProjects.table.emptyState.all.both'); - }); - - it('should not redirect when create project dialog closes without project id', () => { - setup(); - const onClose$ = new Subject<{ project?: { id?: string } }>(); - customDialogService.open.mockReturnValue(CustomDialogServiceMock.dialogRefWithClose(onClose$.asObservable())); - - component.createProject(); - onClose$.next({ project: {} }); - - expect(projectRedirectDialogService.showProjectRedirectDialog).not.toHaveBeenCalled(); - }); - it('should delegate search handling after debounce', () => { vi.useFakeTimers(); setup(); @@ -335,6 +305,6 @@ describe('MyProjectsComponent', () => { component.searchControl.setValue('alpha'); vi.advanceTimersByTime(300); - expect(queryServiceMock.handleSearch).toHaveBeenCalledWith('alpha', { tab: '1', page: '1', size: '10' }, 1); + expect(queryServiceMock.handleSearch).toHaveBeenCalledWith('alpha', defaultRawParams, 1); }); }); diff --git a/src/app/features/my-projects/my-projects.component.ts b/src/app/features/my-projects/my-projects.component.ts index c750509d8..acd2c2c87 100644 --- a/src/app/features/my-projects/my-projects.component.ts +++ b/src/app/features/my-projects/my-projects.component.ts @@ -6,7 +6,7 @@ import type { SortEvent } from 'primeng/api'; import { TablePageEvent } from 'primeng/table'; import { Tab, TabList, TabPanel, TabPanels, Tabs } from 'primeng/tabs'; -import { debounceTime, distinctUntilChanged, filter, tap } from 'rxjs'; +import { debounceTime, distinctUntilChanged, filter, finalize, tap } from 'rxjs'; import { isPlatformBrowser } from '@angular/common'; import { @@ -22,7 +22,7 @@ import { untracked, } from '@angular/core'; import { takeUntilDestroyed, toSignal } from '@angular/core/rxjs-interop'; -import { FormControl, FormsModule } from '@angular/forms'; +import { FormControl } from '@angular/forms'; import { ActivatedRoute, Router } from '@angular/router'; import { UserSelectors } from '@osf/core/store/user'; @@ -33,6 +33,7 @@ import { SubHeaderComponent } from '@osf/shared/components/sub-header/sub-header import { DEFAULT_TABLE_PARAMS } from '@osf/shared/constants/default-table-params.constants'; import { SortOrder } from '@osf/shared/enums/sort-order.enum'; import { IS_MEDIUM } from '@osf/shared/helpers/breakpoints.tokens'; +import { Primitive } from '@osf/shared/helpers/types.helper'; import { MyResourcesItem } from '@osf/shared/models/my-resources/my-resources-item.model'; import { MyResourcesSearchFilters } from '@osf/shared/models/my-resources/my-resources-search-filters.model'; import { CustomDialogService } from '@osf/shared/services/custom-dialog.service'; @@ -62,7 +63,6 @@ import { MyProjectsTab } from './enums'; @Component({ selector: 'osf-my-projects', imports: [ - FormsModule, Tab, TabList, TabPanel, @@ -80,17 +80,16 @@ import { MyProjectsTab } from './enums'; changeDetection: ChangeDetectionStrategy.OnPush, }) export class MyProjectsComponent implements OnInit { - readonly destroyRef = inject(DestroyRef); - readonly customDialogService = inject(CustomDialogService); - readonly router = inject(Router); - readonly route = inject(ActivatedRoute); - readonly projectRedirectDialogService = inject(ProjectRedirectDialogService); - readonly queryService = inject(MyProjectsQueryService); - readonly tableParamsService = inject(MyProjectsTableParamsService); - readonly downloadOptionsService = inject(ProjectDownloadOptionsService); - readonly platformId = inject(PLATFORM_ID); - readonly isBrowser = isPlatformBrowser(this.platformId); - readonly projectCreationDisabled = select(UserSelectors.isProjectCreationDisabled); + private readonly destroyRef = inject(DestroyRef); + private readonly customDialogService = inject(CustomDialogService); + private readonly router = inject(Router); + private readonly route = inject(ActivatedRoute); + private readonly projectRedirectDialogService = inject(ProjectRedirectDialogService); + private readonly queryService = inject(MyProjectsQueryService); + private readonly tableParamsService = inject(MyProjectsTableParamsService); + private readonly downloadOptionsService = inject(ProjectDownloadOptionsService); + private readonly platformId = inject(PLATFORM_ID); + private readonly isBrowser = isPlatformBrowser(this.platformId); readonly isLoading = signal(false); readonly isMedium = toSignal(inject(IS_MEDIUM)); @@ -103,28 +102,21 @@ export class MyProjectsComponent implements OnInit { readonly searchControl = new FormControl(''); - readonly appliedSearch = computed(() => { - const params = this.queryParams(); - return params ? this.queryService.toQueryModel(params).search || '' : ''; - }); - - readonly projectsEmptyMessageKey = computed(() => { - if (this.appliedSearch()) { - return 'common.search.noResultsFound'; - } - - return getMyProjectsEmptyMessageKey(this.selectedProjectFilterOption(), this.selectedVisibilityFilterOption()); - }); - readonly queryParams = toSignal(this.route.queryParams); - readonly currentPage = signal(1); - readonly currentPageSize = signal(DEFAULT_TABLE_PARAMS.rows); readonly selectedTab = signal(MyProjectsTab.Projects); - readonly activeProject = signal(null); readonly sortColumn = signal(undefined); readonly sortOrder = signal(SortOrder.Asc); readonly tableParams = signal({ ...DEFAULT_TABLE_PARAMS, firstRowIndex: 0 }); + private readonly actions = createDispatchMap({ + getBookmarksCollectionId: GetBookmarksCollectionId, + clearMyProjects: ClearMyResources, + getMyProjects: GetMyProjects, + getMyRegistrations: GetMyRegistrations, + getMyPreprints: GetMyPreprints, + getMyBookmarks: GetAllMyBookmarks, + }); + readonly projects = select(MyResourcesSelectors.getProjects); readonly registrations = select(MyResourcesSelectors.getRegistrations); readonly preprints = select(MyResourcesSelectors.getPreprints); @@ -135,18 +127,24 @@ export class MyProjectsComponent implements OnInit { readonly bookmarks = select(BookmarksSelectors.getBookmarks); readonly bookmarksCollectionId = select(BookmarksSelectors.getBookmarksCollectionId); readonly totalBookmarksCount = select(BookmarksSelectors.getBookmarksTotalCount); + readonly projectCreationDisabled = select(UserSelectors.isProjectCreationDisabled); + readonly isBookmarks = computed(() => this.selectedTab() === MyProjectsTab.Bookmarks); readonly buttonTooltip = computed(() => this.projectCreationDisabled() ? 'myProjects.header.createProjectDisabledTooltip' : '' ); - readonly actions = createDispatchMap({ - getBookmarksCollectionId: GetBookmarksCollectionId, - clearMyProjects: ClearMyResources, - getMyProjects: GetMyProjects, - getMyRegistrations: GetMyRegistrations, - getMyPreprints: GetMyPreprints, - getMyBookmarks: GetAllMyBookmarks, + readonly appliedSearch = computed(() => { + const params = this.queryParams(); + return params ? this.queryService.toQueryModel(params).search || '' : ''; + }); + + readonly projectsEmptyMessageKey = computed(() => { + if (this.appliedSearch()) { + return 'common.search.noResultsFound'; + } + + return getMyProjectsEmptyMessageKey(this.selectedProjectFilterOption(), this.selectedVisibilityFilterOption()); }); constructor() { @@ -173,7 +171,11 @@ export class MyProjectsComponent implements OnInit { } } - onTabChange(event: string | number | undefined): void { + onTabChange(event: Primitive): void { + if (event == null || typeof event === 'boolean') { + return; + } + const value = Number(event); if (!isNaN(value)) { @@ -186,22 +188,17 @@ export class MyProjectsComponent implements OnInit { } } - onProjectFilterChange(): void { - const params = this.queryParams(); + onFilterChange(): void { + const current = this.queryService.getRawParams(); + const queryParams = { ...this.queryService.toQueryModel(current), page: 1 }; - if (params) { - const queryParams = this.queryService.toQueryModel(params); - this.fetchDataForCurrentTab(queryParams); + if (Number(current['page'] || 1) !== 1) { + this.queryService.updateParams({ page: 1 }, current, this.selectedTab()); + return; } - } - - onVisibilityFilterChange(): void { - const params = this.queryParams(); - if (params) { - const queryParams = this.queryService.toQueryModel(params); - this.fetchDataForCurrentTab(queryParams); - } + this.updateComponentState(queryParams); + this.fetchDataForCurrentTab(queryParams); } createProject(): void { @@ -218,14 +215,8 @@ export class MyProjectsComponent implements OnInit { .subscribe(); } - navigateToProject(project: MyResourcesItem): void { - this.activeProject.set(project); - this.router.navigate([project.id]); - } - - navigateToRegistry(registry: MyResourcesItem): void { - this.activeProject.set(registry); - this.router.navigate([registry.id]); + navigateToItem(item: MyResourcesItem): void { + this.router.navigate([item.id]); } private setupCleanup(): void { @@ -247,7 +238,7 @@ export class MyProjectsComponent implements OnInit { effect(() => { const totalRecords = this.getTotalRecordsForCurrentTab(); untracked(() => { - this.updateTableParams({ totalRecords }); + this.tableParams.update((current) => ({ ...current, totalRecords })); }); }); } @@ -287,9 +278,7 @@ export class MyProjectsComponent implements OnInit { const params = this.queryParams(); if (!params) return; - const raw = params; - - if (!this.queryService.hasTabInUrl(raw)) { + if (!this.queryService.hasTabInUrl(params)) { untracked(() => { const current = this.queryParams() || {}; this.queryService.updateParams({ page: 1 }, current, this.selectedTab()); @@ -298,13 +287,13 @@ export class MyProjectsComponent implements OnInit { } untracked(() => { - const tabFromUrl = this.queryService.getTabFromUrl(raw); + const tabFromUrl = this.queryService.getTabFromUrl(params); if (tabFromUrl !== null && this.selectedTab() !== tabFromUrl) { this.selectedTab.set(tabFromUrl); } if (!this.isBookmarks()) { - const queryParams = this.queryService.toQueryModel(raw); + const queryParams = this.queryService.toQueryModel(params); this.updateComponentState(queryParams); this.fetchDataForCurrentTab(queryParams); } @@ -316,8 +305,6 @@ export class MyProjectsComponent implements OnInit { untracked(() => { const size = params.size || DEFAULT_TABLE_PARAMS.rows; - this.currentPage.set(params.page ?? 1); - this.currentPageSize.set(size); this.searchControl.setValue(params.search || '', { emitEvent: false }); this.sortColumn.set(params.sortColumn); this.sortOrder.set(params.sortOrder ?? SortOrder.Asc); @@ -326,20 +313,10 @@ export class MyProjectsComponent implements OnInit { const tableParams = this.tableParamsService.buildTableParams(size, totalRecords, this.isBookmarks()); tableParams.firstRowIndex = ((params.page ?? 1) - 1) * size; - this.tableParams.set({ - ...tableParams, - rows: size, - }); + this.tableParams.set({ ...tableParams, rows: size }); }); } - private updateTableParams(updates: Partial): void { - this.tableParams.update((current) => ({ - ...current, - ...updates, - })); - } - private fetchDataForCurrentTab(params: QueryParams): void { this.isLoading.set(true); const filters = this.createFilters(params); @@ -354,7 +331,6 @@ export class MyProjectsComponent implements OnInit { pageSize, filters, this.selectedProjectFilterOption(), - undefined, this.selectedVisibilityFilterOption() ); break; @@ -371,14 +347,12 @@ export class MyProjectsComponent implements OnInit { break; } - action$?.pipe(takeUntilDestroyed(this.destroyRef)).subscribe({ - complete: () => { - this.isLoading.set(false); - }, - error: () => { - this.isLoading.set(false); - }, - }); + action$ + ?.pipe( + finalize(() => this.isLoading.set(false)), + takeUntilDestroyed(this.destroyRef) + ) + .subscribe(); } private createFilters(params: QueryParams): MyResourcesSearchFilters { diff --git a/src/app/features/preprints/components/stepper/file-step/file-step.component.html b/src/app/features/preprints/components/stepper/file-step/file-step.component.html index e11ec2ac7..a2da41c20 100644 --- a/src/app/features/preprints/components/stepper/file-step/file-step.component.html +++ b/src/app/features/preprints/components/stepper/file-step/file-step.component.html @@ -7,22 +7,20 @@

{{ 'preprints.preprintStepper.file.title' | translate }}

| translate: { preprintWord: provider().preprintWord | titlecase } }}

-

{{ 'preprints.preprintStepper.file.note' | translate }}

-@if (!preprintHasPrimaryFile() || versionFileMode()) { +@if (preprint() && !preprintHasPrimaryFile()) {
{{ 'preprints.preprintStepper.file.title' | translate }}

[styleClass]="isFileSourceSelected() ? 'w-full cursor-not-allowed' : 'w-full'" [label]="'preprints.preprintStepper.file.selectFromProject' | translate" severity="secondary" - [disabled]="isFileSourceSelected() || versionFileMode()" - [pTooltip]="'preprints.preprintStepper.file.tooltips.projectDisabled' | translate" - tooltipPosition="top" + [disabled]="isFileSourceSelected()" (onClick)="selectFileSource(PreprintFileSource.Project)" /> } -@if (selectedFileSource() === PreprintFileSource.Computer) { +@if (selectedFileSource() === PreprintFileSource.Computer && !preprintFile() && !isPreprintFileLoading()) {
@if (!fileUploadLink()) { - } @else if ((!preprintFile() && !isPreprintFileLoading()) || versionFileMode()) { + } @else { @@ -63,39 +59,37 @@

{{ 'preprints.preprintStepper.file.title' | translate }}

@if (selectedFileSource() === PreprintFileSource.Project && !preprintFile() && !isPreprintFileLoading()) { -
-

- {{ 'preprints.preprintStepper.projectSelection.description' | translate }} -

-

- {{ 'preprints.preprintStepper.projectSelection.subDescription' | translate }} -

+

+ {{ 'preprints.preprintStepper.projectSelection.description' | translate }} +

+

+ {{ 'preprints.preprintStepper.projectSelection.subDescription' | translate }} +

- -
+
- @if (selectedProjectId()) { + @if (selectedProjectId() && currentFolder(); as folder) { {{ 'preprints.preprintStepper.file.title' | translate }} } -@if (!versionFileMode()) { -
- @if (isPreprintFileLoading()) { - - } @else if (preprintFile()) { -
-
- -

{{ preprintFile()!.name }}

-
-
- } -
-} +
+ @if (isPreprintFileLoading()) { + + } @else if (preprintFile(); as file) { +
+
+ +

{{ file.name }}

+
+ + @if (canDeletePrimaryFile()) { + + } +
+ } +
{{ 'preprints.preprintStepper.file.title' | translate }} class="w-6 md:w-9rem" styleClass="w-full" [label]="'common.buttons.next' | translate" - [disabled]="!canProceedToNext()" - [pTooltip]=" - !canProceedToNext() ? ('preprints.preprintStepper.common.validation.fillRequiredFields' | translate) : '' - " + [disabled]="!preprintFile()" + [pTooltip]="!preprintFile() ? ('preprints.preprintStepper.common.validation.fillRequiredFields' | translate) : ''" tooltipPosition="top" (onClick)="nextButtonClicked()" /> diff --git a/src/app/features/preprints/components/stepper/file-step/file-step.component.spec.ts b/src/app/features/preprints/components/stepper/file-step/file-step.component.spec.ts index 0c72697f5..33580c85e 100644 --- a/src/app/features/preprints/components/stepper/file-step/file-step.component.spec.ts +++ b/src/app/features/preprints/components/stepper/file-step/file-step.component.spec.ts @@ -8,16 +8,16 @@ import { Mock } from 'vitest'; import { ComponentFixture, TestBed } from '@angular/core/testing'; -import { PreprintFileSource } from '@osf/features/preprints/enums'; -import { PreprintModel, PreprintProviderDetails } from '@osf/features/preprints/models'; +import { PreprintFileSource, ReviewsState } from '@osf/features/preprints/enums'; +import { PreprintProviderDetails } from '@osf/features/preprints/models'; import { CopyFileFromProject, + DeletePreprintFile, FetchAvailableProjects, FetchPreprintFilesLinks, FetchPreprintPrimaryFile, FetchProjectFilesByLink, PreprintStepperSelectors, - ReuploadFile, SetPreprintStepperCurrentFolder, SetProjectRootFolder, SetSelectedPreprintFileSource, @@ -25,30 +25,58 @@ import { } from '@osf/features/preprints/store/preprint-stepper'; import { FilesTreeComponent } from '@osf/shared/components/files-tree/files-tree.component'; import { IconComponent } from '@osf/shared/components/icon/icon.component'; -import { FileModel } from '@osf/shared/models/files/file.model'; import { FileFolderModel } from '@osf/shared/models/files/file-folder.model'; +import { CustomConfirmationService } from '@osf/shared/services/custom-confirmation.service'; import { ToastService } from '@osf/shared/services/toast.service'; +import { FileModelMock } from '@testing/mocks/file.model.mock'; import { OSF_FILE_MOCK } from '@testing/mocks/osf-file.mock'; import { PREPRINT_MOCK } from '@testing/mocks/preprint.mock'; import { PREPRINT_PROVIDER_DETAILS_MOCK } from '@testing/mocks/preprint-provider-details'; import { provideOSFCore } from '@testing/osf.testing.provider'; -import { mergeSignalOverrides, provideMockStore, SignalOverride } from '@testing/providers/store-provider.mock'; +import { + CustomConfirmationServiceMock, + CustomConfirmationServiceMockType, +} from '@testing/providers/custom-confirmation-provider.mock'; +import { + BaseSetupOverrides, + mergeSignalOverrides, + provideMockStore, + SignalOverride, +} from '@testing/providers/store-provider.mock'; import { ToastServiceMock, ToastServiceMockType } from '@testing/providers/toast-provider.mock'; import { FileStepComponent } from './file-step.component'; +interface SetupOverrides extends BaseSetupOverrides { + provider?: PreprintProviderDetails; + detectChanges?: boolean; +} + describe('FileStepComponent', () => { let component: FileStepComponent; let fixture: ComponentFixture; let store: Store; let toastServiceMock: ToastServiceMockType; + let confirmationMock: CustomConfirmationServiceMockType; const originalPointerEvent = (globalThis as unknown as { PointerEvent?: typeof Event }).PointerEvent; const mockProvider: PreprintProviderDetails = PREPRINT_PROVIDER_DETAILS_MOCK; - const mockPreprint: PreprintModel = PREPRINT_MOCK; - const mockProjectFiles: FileFolderModel[] = [OSF_FILE_MOCK]; - const mockPreprintFile: FileFolderModel = OSF_FILE_MOCK; + const mockPreprint = { ...PREPRINT_MOCK, reviewsState: ReviewsState.Initial }; + const mockPreprintFile = FileModelMock.simple({ + id: 'file-123', + name: 'example.pdf', + links: { + info: '', + move: 'move', + upload: '', + delete: '/v2/files/file-123/', + download: '', + render: '', + html: '', + self: '', + }, + }); const mockCurrentFolder: FileFolderModel = OSF_FILE_MOCK; const mockAvailableProjects = [ { id: 'project-1', name: 'Test Project 1' }, @@ -63,31 +91,32 @@ describe('FileStepComponent', () => { { selector: PreprintStepperSelectors.isPreprintFilesLoading, value: false }, { selector: PreprintStepperSelectors.getAvailableProjects, value: mockAvailableProjects }, { selector: PreprintStepperSelectors.areAvailableProjectsLoading, value: false }, - { selector: PreprintStepperSelectors.getProjectFiles, value: mockProjectFiles }, + { selector: PreprintStepperSelectors.getProjectFiles, value: [OSF_FILE_MOCK] }, { selector: PreprintStepperSelectors.getFilesTotalCount, value: 1 }, { selector: PreprintStepperSelectors.areProjectFilesLoading, value: false }, { selector: PreprintStepperSelectors.getCurrentFolder, value: mockCurrentFolder }, { selector: PreprintStepperSelectors.isCurrentFolderLoading, value: false }, ]; - function setup(overrides?: { - selectorOverrides?: SignalOverride[]; - provider?: PreprintProviderDetails; - detectChanges?: boolean; - }) { - const signals = mergeSignalOverrides(defaultSignals, overrides?.selectorOverrides); + function setup(overrides: SetupOverrides = {}) { toastServiceMock = ToastServiceMock.simple(); + confirmationMock = CustomConfirmationServiceMock.simple(); TestBed.configureTestingModule({ imports: [FileStepComponent, ...MockComponents(IconComponent, FilesTreeComponent)], - providers: [provideOSFCore(), MockProvider(ToastService, toastServiceMock), provideMockStore({ signals })], + providers: [ + provideOSFCore(), + MockProvider(ToastService, toastServiceMock), + MockProvider(CustomConfirmationService, confirmationMock), + provideMockStore({ signals: mergeSignalOverrides(defaultSignals, overrides.selectorOverrides) }), + ], }); store = TestBed.inject(Store); fixture = TestBed.createComponent(FileStepComponent); component = fixture.componentInstance; - fixture.componentRef.setInput('provider', overrides?.provider ?? mockProvider); - if (overrides?.detectChanges ?? true) { + fixture.componentRef.setInput('provider', overrides.provider ?? mockProvider); + if (overrides.detectChanges ?? true) { fixture.detectChanges(); } } @@ -110,46 +139,97 @@ describe('FileStepComponent', () => { vi.useRealTimers(); }); - it('should create', () => { - setup(); - expect(component).toBeTruthy(); - }); - - it('should compute state values', () => { + it('should create and expose default computed state', () => { setup({ detectChanges: false }); + + expect(component).toBeTruthy(); + expect(component.showDeleteButton()).toBe(false); expect(component.preprintHasPrimaryFile()).toBe(true); + expect(component.canDeletePrimaryFile()).toBe(true); expect(component.isFileSourceSelected()).toBe(false); - expect(component.canProceedToNext()).toBe(true); expect(component.cancelSourceOptionButtonVisible()).toBe(false); + + fixture.componentRef.setInput('showDeleteButton', true); + expect(component.showDeleteButton()).toBe(true); }); - it('should dispatch fetch links and primary file fetch in ngOnInit', () => { + it('should disallow delete for non-initial and non-rejected review states', () => { setup({ - selectorOverrides: [{ selector: PreprintStepperSelectors.getPreprintFile, value: null }], + selectorOverrides: [ + { + selector: PreprintStepperSelectors.getPreprint, + value: { ...mockPreprint, reviewsState: ReviewsState.Pending }, + }, + ], + detectChanges: false, + }); + + expect(component.canDeletePrimaryFile()).toBe(false); + }); + + it('should allow delete for rejected review state', () => { + setup({ + selectorOverrides: [ + { + selector: PreprintStepperSelectors.getPreprint, + value: { ...mockPreprint, reviewsState: ReviewsState.Rejected }, + }, + ], detectChanges: false, }); - component.ngOnInit(); + expect(component.canDeletePrimaryFile()).toBe(true); + }); + + it('should show cancel source button when source selected and file missing', () => { + setup({ + selectorOverrides: [ + { selector: PreprintStepperSelectors.getPreprintFile, value: null }, + { selector: PreprintStepperSelectors.getSelectedFileSource, value: PreprintFileSource.Computer }, + ], + detectChanges: false, + }); + + expect(component.cancelSourceOptionButtonVisible()).toBe(true); + }); + + it('should dispatch fetch links and skip primary file when file is already loaded', () => { + setup(); + + expect(store.dispatch).toHaveBeenCalledWith(new FetchPreprintFilesLinks()); + expect(store.dispatch).not.toHaveBeenCalledWith(expect.any(FetchPreprintPrimaryFile)); + }); + + it('should dispatch fetch links and primary file when primary file id exists without loaded file', () => { + setup({ + selectorOverrides: [{ selector: PreprintStepperSelectors.getPreprintFile, value: null }], + }); expect(store.dispatch).toHaveBeenCalledWith(new FetchPreprintFilesLinks()); expect(store.dispatch).toHaveBeenCalledWith(new FetchPreprintPrimaryFile()); }); - it('should not dispatch primary file fetch in ngOnInit without primary file id', () => { + it('should dispatch fetch links only when primary file id is missing', () => { setup({ selectorOverrides: [ { selector: PreprintStepperSelectors.getPreprint, value: { ...mockPreprint, primaryFileId: null } }, ], - detectChanges: false, }); - component.ngOnInit(); - expect(store.dispatch).toHaveBeenCalledWith(new FetchPreprintFilesLinks()); expect(store.dispatch).not.toHaveBeenCalledWith(expect.any(FetchPreprintPrimaryFile)); }); - it('should dispatch available projects from debounced projectNameControl value', () => { + it('should skip init fetches when preprint is missing', () => { + setup({ + selectorOverrides: [{ selector: PreprintStepperSelectors.getPreprint, value: null }], + }); + + expect(store.dispatch).not.toHaveBeenCalledWith(expect.any(FetchPreprintFilesLinks)); + expect(store.dispatch).not.toHaveBeenCalledWith(expect.any(FetchPreprintPrimaryFile)); + }); + + it('should dispatch available projects from debounced project search', () => { vi.useFakeTimers(); setup(); (store.dispatch as Mock).mockClear(); @@ -172,7 +252,7 @@ describe('FileStepComponent', () => { expect(store.dispatch).not.toHaveBeenCalledWith(new FetchAvailableProjects('project-1')); }); - it('should handle selectFileSource for project and computer source', () => { + it('should select file source and fetch projects only for project source', () => { setup({ detectChanges: false }); component.selectFileSource(PreprintFileSource.Project); @@ -186,25 +266,19 @@ describe('FileStepComponent', () => { expect(store.dispatch).not.toHaveBeenCalledWith(new FetchAvailableProjects(null)); }); - it('should emit backClicked', () => { + it('should emit back and delete outputs', () => { setup({ detectChanges: false }); - const emitSpy = vi.spyOn(component.backClicked, 'emit'); + const backSpy = vi.spyOn(component.backClicked, 'emit'); + const deleteSpy = vi.spyOn(component.deleteClicked, 'emit'); component.backButtonClicked(); - - expect(emitSpy).toHaveBeenCalled(); - }); - - it('should emit deleteClicked when deletePreprint is called', () => { - setup({ detectChanges: false }); - const emitSpy = vi.spyOn(component.deleteClicked, 'emit'); - component.deletePreprint(); - expect(emitSpy).toHaveBeenCalled(); + expect(backSpy).toHaveBeenCalled(); + expect(deleteSpy).toHaveBeenCalled(); }); - it('should handle nextButtonClicked for allowed and blocked states', () => { + it('should emit next and show success when file and primary file id exist', () => { setup({ detectChanges: false }); const emitSpy = vi.spyOn(component.nextClicked, 'emit'); @@ -213,57 +287,45 @@ describe('FileStepComponent', () => { expect(toastServiceMock.showSuccess).toHaveBeenCalledWith( 'preprints.preprintStepper.common.successMessages.preprintSaved' ); - expect(emitSpy).toHaveBeenCalledTimes(1); - - component.versionFileMode.set(true); - toastServiceMock.showSuccess.mockClear(); - - component.nextButtonClicked(); - - expect(toastServiceMock.showSuccess).not.toHaveBeenCalled(); - expect(emitSpy).toHaveBeenCalledTimes(1); + expect(emitSpy).toHaveBeenCalled(); + }); - vi.spyOn(component, 'preprint').mockReturnValue({ ...mockPreprint, primaryFileId: null } as PreprintModel); - component.versionFileMode.set(false); + it('should block next when file requirements are missing', () => { + setup({ + selectorOverrides: [{ selector: PreprintStepperSelectors.getPreprintFile, value: null }], + detectChanges: false, + }); + const emitSpy = vi.spyOn(component.nextClicked, 'emit'); component.nextButtonClicked(); expect(toastServiceMock.showSuccess).not.toHaveBeenCalled(); - expect(emitSpy).toHaveBeenCalledTimes(1); + expect(emitSpy).not.toHaveBeenCalled(); }); - it('should skip file upload dispatches when no file is selected', () => { + it('should upload selected file', () => { setup({ detectChanges: false }); - + const file = new File(['content'], 'upload.pdf'); const input = document.createElement('input'); - Object.defineProperty(input, 'files', { value: [] }); + Object.defineProperty(input, 'files', { value: [file] }); + component.onFileSelected({ target: input } as unknown as Event); - expect(store.dispatch).not.toHaveBeenCalledWith(expect.any(UploadFile)); - expect(store.dispatch).not.toHaveBeenCalledWith(expect.any(ReuploadFile)); + expect(store.dispatch).toHaveBeenCalledWith(new UploadFile(file)); + expect(store.dispatch).not.toHaveBeenCalledWith(expect.any(FetchPreprintPrimaryFile)); }); - it('should handle upload and reupload flows in onFileSelected', () => { + it('should skip upload when no file is selected', () => { setup({ detectChanges: false }); - const file = new File(['file-body'], 'test.txt'); const input = document.createElement('input'); - Object.defineProperty(input, 'files', { value: [file] }); - - component.onFileSelected({ target: input } as unknown as Event); - expect(store.dispatch).toHaveBeenCalledWith(new UploadFile(file)); - expect(store.dispatch).toHaveBeenCalledWith(new FetchPreprintPrimaryFile()); - - (store.dispatch as Mock).mockClear(); - component.versionFileMode.set(true); + Object.defineProperty(input, 'files', { value: [] }); component.onFileSelected({ target: input } as unknown as Event); - expect(store.dispatch).toHaveBeenCalledWith(new ReuploadFile(file)); - expect(store.dispatch).toHaveBeenCalledWith(new FetchPreprintPrimaryFile()); - expect(component.versionFileMode()).toBe(false); + expect(store.dispatch).not.toHaveBeenCalledWith(expect.any(UploadFile)); }); - it('should handle selectProject with and without current folder files link', () => { + it('should select project and load files when folder link exists', () => { setup({ detectChanges: false }); component.selectProject({ @@ -271,12 +333,16 @@ describe('FileStepComponent', () => { originalEvent: new PointerEvent('click'), } as SelectChangeEvent); + expect(component.selectedProjectId()).toBe('project-1'); expect(store.dispatch).toHaveBeenCalledWith(new SetProjectRootFolder('project-1')); expect(store.dispatch).toHaveBeenCalledWith(new FetchProjectFilesByLink(mockCurrentFolder.links.filesLink, 1)); - expect(component.selectedProjectId()).toBe('project-1'); + }); - vi.spyOn(component, 'currentFolder').mockReturnValue(null); - (store.dispatch as Mock).mockClear(); + it('should select project without loading files when folder link is missing', () => { + setup({ + selectorOverrides: [{ selector: PreprintStepperSelectors.getCurrentFolder, value: null }], + detectChanges: false, + }); component.selectProject({ value: 'project-1', @@ -287,7 +353,7 @@ describe('FileStepComponent', () => { expect(store.dispatch).not.toHaveBeenCalledWith(expect.any(FetchProjectFilesByLink)); }); - it('should return early in selectProject when original event is not pointer event', () => { + it('should ignore project selection when original event is not a pointer event', () => { setup({ detectChanges: false }); component.selectProject({ @@ -298,39 +364,97 @@ describe('FileStepComponent', () => { expect(store.dispatch).not.toHaveBeenCalledWith(expect.any(SetProjectRootFolder)); }); - it('should dispatch copy file from project and preprint file fetch', () => { + it('should copy project file', () => { setup({ detectChanges: false }); - const projectFile = OSF_FILE_MOCK as unknown as FileModel; + const projectFile = FileModelMock.simple({ id: 'project-file-1' }); component.selectProjectFile(projectFile); expect(store.dispatch).toHaveBeenCalledWith(new CopyFileFromProject(projectFile)); - expect(store.dispatch).toHaveBeenCalledWith(new FetchPreprintPrimaryFile()); + expect(store.dispatch).not.toHaveBeenCalledWith(expect.any(FetchPreprintPrimaryFile)); }); - it('should handle cancelButtonClicked for file present and file missing states', () => { + it('should confirm delete preprint file and clear project selection on confirm', () => { setup({ detectChanges: false }); + component.selectedProjectId.set('project-1'); + component.projectNameControl.setValue('project-1', { emitEvent: false }); - component.cancelButtonClicked(); - expect(store.dispatch).not.toHaveBeenCalledWith(new SetSelectedPreprintFileSource(PreprintFileSource.None)); + component.deletePreprintFile(); + + expect(confirmationMock.confirmDelete).toHaveBeenCalledWith({ + headerKey: 'files.dialogs.deleteFile.title', + messageParams: { name: mockPreprintFile.name }, + messageKey: 'files.dialogs.deleteFile.message', + onConfirm: expect.any(Function), + }); + + const { onConfirm } = confirmationMock.confirmDelete.mock.calls[0][0]; + onConfirm(); - vi.spyOn(component, 'preprintFile').mockReturnValue(null); + expect(store.dispatch).toHaveBeenCalledWith(new DeletePreprintFile(mockPreprintFile.links.delete)); + expect(component.selectedProjectId()).toBeNull(); + expect(component.projectNameControl.value).toBeNull(); + expect(toastServiceMock.showSuccess).toHaveBeenCalledWith('files.dialogs.deleteFile.success'); + }); + + it('should skip delete preprint file when file is missing', () => { + setup({ + selectorOverrides: [{ selector: PreprintStepperSelectors.getPreprintFile, value: null }], + detectChanges: false, + }); + + component.deletePreprintFile(); + + expect(confirmationMock.confirmDelete).not.toHaveBeenCalled(); + }); + + it('should skip delete preprint file when review state does not allow delete', () => { + setup({ + selectorOverrides: [ + { + selector: PreprintStepperSelectors.getPreprint, + value: { ...mockPreprint, reviewsState: ReviewsState.Pending }, + }, + ], + detectChanges: false, + }); + + component.deletePreprintFile(); + + expect(confirmationMock.confirmDelete).not.toHaveBeenCalled(); + }); + + it('should reset file source and project selection on cancel when file is missing', () => { + setup({ + selectorOverrides: [{ selector: PreprintStepperSelectors.getPreprintFile, value: null }], + detectChanges: false, + }); + component.selectedProjectId.set('project-1'); + component.projectNameControl.setValue('project-1', { emitEvent: false }); (store.dispatch as Mock).mockClear(); component.cancelButtonClicked(); + + expect(component.selectedProjectId()).toBeNull(); + expect(component.projectNameControl.value).toBeNull(); expect(store.dispatch).toHaveBeenCalledWith(new SetSelectedPreprintFileSource(PreprintFileSource.None)); }); - it('should handle setCurrentFolder for unchanged and changed folders', () => { + it('should keep file source on cancel when file is present', () => { + setup({ detectChanges: false }); + + component.cancelButtonClicked(); + + expect(store.dispatch).not.toHaveBeenCalledWith(new SetSelectedPreprintFileSource(PreprintFileSource.None)); + }); + + it('should set current folder only when folder id changes', () => { setup({ detectChanges: false }); component.setCurrentFolder(mockCurrentFolder); expect(store.dispatch).not.toHaveBeenCalledWith(new SetPreprintStepperCurrentFolder(mockCurrentFolder)); - expect(store.dispatch).not.toHaveBeenCalledWith(new FetchProjectFilesByLink(mockCurrentFolder.links.filesLink, 1)); - (store.dispatch as Mock).mockClear(); const nextFolder = { ...mockCurrentFolder, id: 'folder-2' } as FileFolderModel; - component.setCurrentFolder(nextFolder); expect(store.dispatch).toHaveBeenCalledWith(new SetPreprintStepperCurrentFolder(nextFolder)); @@ -344,19 +468,4 @@ describe('FileStepComponent', () => { expect(store.dispatch).toHaveBeenCalledWith(new FetchProjectFilesByLink('/v2/nodes/node-456/files/', 3)); }); - - it('should default showDeleteButton to false', () => { - setup(); - - expect(component.showDeleteButton()).toBe(false); - }); - - it('should update showDeleteButton when input changes', () => { - setup(); - - fixture.componentRef.setInput('showDeleteButton', true); - fixture.detectChanges(); - - expect(component.showDeleteButton()).toBe(true); - }); }); diff --git a/src/app/features/preprints/components/stepper/file-step/file-step.component.ts b/src/app/features/preprints/components/stepper/file-step/file-step.component.ts index 854f901b5..48ac4a585 100644 --- a/src/app/features/preprints/components/stepper/file-step/file-step.component.ts +++ b/src/app/features/preprints/components/stepper/file-step/file-step.component.ts @@ -16,25 +16,27 @@ import { Component, computed, DestroyRef, + effect, inject, input, OnInit, output, signal, + untracked, } from '@angular/core'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { FormControl, ReactiveFormsModule } from '@angular/forms'; -import { PreprintFileSource } from '@osf/features/preprints/enums'; +import { PreprintFileSource, ReviewsState } from '@osf/features/preprints/enums'; import { PreprintProviderDetails } from '@osf/features/preprints/models'; import { CopyFileFromProject, + DeletePreprintFile, FetchAvailableProjects, FetchPreprintFilesLinks, FetchPreprintPrimaryFile, FetchProjectFilesByLink, PreprintStepperSelectors, - ReuploadFile, SetPreprintStepperCurrentFolder, SetProjectRootFolder, SetSelectedPreprintFileSource, @@ -47,6 +49,7 @@ import { StringOrNull } from '@osf/shared/helpers/types.helper'; import { FileModel } from '@osf/shared/models/files/file.model'; import { FileFolderModel } from '@osf/shared/models/files/file-folder.model'; import { FilePageLinkModel } from '@osf/shared/models/files/file-page-link.model'; +import { CustomConfirmationService } from '@osf/shared/services/custom-confirmation.service'; import { ToastService } from '@osf/shared/services/toast.service'; @Component({ @@ -70,14 +73,15 @@ import { ToastService } from '@osf/shared/services/toast.service'; changeDetection: ChangeDetectionStrategy.OnPush, }) export class FileStepComponent implements OnInit { - private toastService = inject(ToastService); - private destroyRef = inject(DestroyRef); + private readonly toastService = inject(ToastService); + private readonly destroyRef = inject(DestroyRef); + private readonly customConfirmationService = inject(CustomConfirmationService); private actions = createDispatchMap({ setSelectedFileSource: SetSelectedPreprintFileSource, getPreprintFilesLinks: FetchPreprintFilesLinks, + deletePreprintFile: DeletePreprintFile, uploadFile: UploadFile, - reuploadFile: ReuploadFile, fetchPreprintFile: FetchPreprintPrimaryFile, getAvailableProjects: FetchAvailableProjects, setProjectRootFolder: SetProjectRootFolder, @@ -88,50 +92,71 @@ export class FileStepComponent implements OnInit { readonly PreprintFileSource = PreprintFileSource; - provider = input.required(); - showDeleteButton = input(false); - preprint = select(PreprintStepperSelectors.getPreprint); - selectedFileSource = select(PreprintStepperSelectors.getSelectedFileSource); - fileUploadLink = select(PreprintStepperSelectors.getUploadLink); + readonly provider = input.required(); + readonly showDeleteButton = input(false); - preprintFile = select(PreprintStepperSelectors.getPreprintFile); - isPreprintFileLoading = select(PreprintStepperSelectors.isPreprintFilesLoading); + readonly nextClicked = output(); + readonly backClicked = output(); + readonly deleteClicked = output(); - availableProjects = select(PreprintStepperSelectors.getAvailableProjects); - areAvailableProjectsLoading = select(PreprintStepperSelectors.areAvailableProjectsLoading); + readonly preprint = select(PreprintStepperSelectors.getPreprint); + readonly selectedFileSource = select(PreprintStepperSelectors.getSelectedFileSource); + readonly fileUploadLink = select(PreprintStepperSelectors.getUploadLink); - projectFiles = select(PreprintStepperSelectors.getProjectFiles); - filesTotalCount = select(PreprintStepperSelectors.getFilesTotalCount); - areProjectFilesLoading = select(PreprintStepperSelectors.areProjectFilesLoading); + readonly preprintFile = select(PreprintStepperSelectors.getPreprintFile); + readonly isPreprintFileLoading = select(PreprintStepperSelectors.isPreprintFilesLoading); - currentFolder = select(PreprintStepperSelectors.getCurrentFolder); - isCurrentFolderLoading = select(PreprintStepperSelectors.isCurrentFolderLoading); - selectedProjectId = signal(null); + readonly availableProjects = select(PreprintStepperSelectors.getAvailableProjects); + readonly areAvailableProjectsLoading = select(PreprintStepperSelectors.areAvailableProjectsLoading); - versionFileMode = signal(false); + readonly projectFiles = select(PreprintStepperSelectors.getProjectFiles); + readonly filesTotalCount = select(PreprintStepperSelectors.getFilesTotalCount); + readonly areProjectFilesLoading = select(PreprintStepperSelectors.areProjectFilesLoading); - preprintHasPrimaryFile = computed(() => !!this.preprint()?.primaryFileId); + readonly currentFolder = select(PreprintStepperSelectors.getCurrentFolder); + readonly isCurrentFolderLoading = select(PreprintStepperSelectors.isCurrentFolderLoading); + readonly selectedProjectId = signal(null); - cancelSourceOptionButtonVisible = computed( + readonly preprintId = computed(() => this.preprint()?.id ?? null); + readonly primaryFileId = computed(() => this.preprint()?.primaryFileId ?? null); + readonly preprintHasPrimaryFile = computed(() => !!this.primaryFileId()); + + readonly canDeletePrimaryFile = computed(() => { + const reviewsState = this.preprint()?.reviewsState; + return reviewsState === ReviewsState.Initial || reviewsState === ReviewsState.Rejected; + }); + + readonly cancelSourceOptionButtonVisible = computed( () => !this.preprintFile() && this.selectedFileSource() !== PreprintFileSource.None && !this.isPreprintFileLoading() ); - projectNameControl = new FormControl(null); + readonly projectNameControl = new FormControl(null); - nextClicked = output(); - backClicked = output(); - deleteClicked = output(); + readonly isFileSourceSelected = computed(() => this.selectedFileSource() !== PreprintFileSource.None); - isFileSourceSelected = computed(() => this.selectedFileSource() !== PreprintFileSource.None); - canProceedToNext = computed(() => !!this.preprintFile() && !this.versionFileMode()); + constructor() { + effect(() => { + if (!this.preprintId()) { + return; + } - ngOnInit() { - this.actions.getPreprintFilesLinks(); + this.actions.getPreprintFilesLinks(); + }); + + effect(() => { + if (!this.primaryFileId()) { + return; + } + + if (untracked(() => this.preprintFile())) { + return; + } - if (this.preprintHasPrimaryFile() && !this.preprintFile()) { this.actions.fetchPreprintFile(); - } + }); + } + ngOnInit() { this.projectNameControl.valueChanges .pipe(debounceTime(500), distinctUntilChanged(), takeUntilDestroyed(this.destroyRef)) .subscribe((projectNameOrId) => { @@ -156,7 +181,7 @@ export class FileStepComponent implements OnInit { } nextButtonClicked() { - if (!this.canProceedToNext() || !this.preprint()?.primaryFileId) { + if (!this.preprintFile() || !this.primaryFileId()) { return; } @@ -173,14 +198,7 @@ export class FileStepComponent implements OnInit { const file = input.files?.[0]; if (!file) return; - const isVersionFileMode = this.versionFileMode(); - - if (isVersionFileMode) { - this.versionFileMode.set(false); - } - - const uploadAction = isVersionFileMode ? this.actions.reuploadFile(file) : this.actions.uploadFile(file); - uploadAction.subscribe(() => this.actions.fetchPreprintFile()); + this.actions.uploadFile(file).pipe(takeUntilDestroyed(this.destroyRef)).subscribe(); } selectProject(event: SelectChangeEvent) { @@ -200,13 +218,38 @@ export class FileStepComponent implements OnInit { } else { return EMPTY; } - }) + }), + takeUntilDestroyed(this.destroyRef) ) .subscribe(); } selectProjectFile(file: FileModel) { - this.actions.copyFileFromProject(file).subscribe(() => this.actions.fetchPreprintFile()); + this.actions.copyFileFromProject(file).pipe(takeUntilDestroyed(this.destroyRef)).subscribe(); + } + + deletePreprintFile() { + const file = this.preprintFile(); + + if (!file || !this.canDeletePrimaryFile()) { + return; + } + + this.customConfirmationService.confirmDelete({ + headerKey: 'files.dialogs.deleteFile.title', + messageParams: { name: file.name }, + messageKey: 'files.dialogs.deleteFile.message', + onConfirm: () => { + this.actions + .deletePreprintFile(file.links.delete) + .pipe(takeUntilDestroyed(this.destroyRef)) + .subscribe(() => { + this.selectedProjectId.set(null); + this.projectNameControl.setValue(null, { emitEvent: false }); + this.toastService.showSuccess('files.dialogs.deleteFile.success'); + }); + }, + }); } cancelButtonClicked() { @@ -214,6 +257,8 @@ export class FileStepComponent implements OnInit { return; } + this.selectedProjectId.set(null); + this.projectNameControl.setValue(null, { emitEvent: false }); this.actions.setSelectedFileSource(PreprintFileSource.None); } diff --git a/src/app/features/preprints/components/stepper/preprints-metadata-step/preprints-metadata-step.component.html b/src/app/features/preprints/components/stepper/preprints-metadata-step/preprints-metadata-step.component.html index 11247062e..0f7f06e0e 100644 --- a/src/app/features/preprints/components/stepper/preprints-metadata-step/preprints-metadata-step.component.html +++ b/src/app/features/preprints/components/stepper/preprints-metadata-step/preprints-metadata-step.component.html @@ -12,7 +12,7 @@

{{ 'common.labels.metadata' | translate }}

{{ 'common.labels.license' | translate }}

{{ 'shared.license.description' | translate }}

-

+

{{ 'shared.license.helpText' | translate }} {{ 'common.links.helpGuide' | translate }}. @@ -23,7 +23,6 @@

{{ 'common.labels.license' | translate }}

[licenses]="licenses()" [selectedLicenseId]="createdPreprint()?.licenseId || defaultLicense()" [selectedLicenseOptions]="createdPreprint()?.licenseOptions" - [fullWidthSelect]="true" (createLicense)="createLicense($event)" (selectLicense)="selectLicense($event)" /> diff --git a/src/app/features/preprints/components/stepper/preprints-metadata-step/preprints-metadata-step.component.spec.ts b/src/app/features/preprints/components/stepper/preprints-metadata-step/preprints-metadata-step.component.spec.ts index 31c91ba80..26fa5a6d3 100644 --- a/src/app/features/preprints/components/stepper/preprints-metadata-step/preprints-metadata-step.component.spec.ts +++ b/src/app/features/preprints/components/stepper/preprints-metadata-step/preprints-metadata-step.component.spec.ts @@ -109,7 +109,7 @@ describe('PreprintsMetadataStepComponent', () => { it('should dispatch fetch licenses on init', () => { setup(); - expect(store.dispatch).toHaveBeenCalledWith(new FetchLicenses(mockProvider.id)); + expect(store.dispatch).toHaveBeenCalledWith(new FetchLicenses(mockProvider.licensesLink)); }); it('should auto-select default license and dispatch save when license has no required fields', () => { diff --git a/src/app/features/preprints/components/stepper/preprints-metadata-step/preprints-metadata-step.component.ts b/src/app/features/preprints/components/stepper/preprints-metadata-step/preprints-metadata-step.component.ts index 45b99d832..85e60c466 100644 --- a/src/app/features/preprints/components/stepper/preprints-metadata-step/preprints-metadata-step.component.ts +++ b/src/app/features/preprints/components/stepper/preprints-metadata-step/preprints-metadata-step.component.ts @@ -29,7 +29,7 @@ import { CustomValidators } from '@osf/shared/helpers/custom-form-validators.hel import { findChangedFields } from '@osf/shared/helpers/find-changed-fields'; import { CustomConfirmationService } from '@osf/shared/services/custom-confirmation.service'; import { ToastService } from '@osf/shared/services/toast.service'; -import { LicenseModel, LicenseOptions } from '@shared/models/license/license.model'; +import { LicenseDetails, LicenseModel } from '@shared/models/license/license.model'; import { PreprintsAffiliatedInstitutionsComponent } from './preprints-affiliated-institutions/preprints-affiliated-institutions.component'; import { PreprintsContributorsComponent } from './preprints-contributors/preprints-contributors.component'; @@ -104,7 +104,7 @@ export class PreprintsMetadataStepComponent implements OnInit { } ngOnInit() { - this.actions.fetchLicenses(this.provider().id); + this.actions.fetchLicenses(this.provider().licensesLink); this.initForm(); } @@ -160,7 +160,7 @@ export class PreprintsMetadataStepComponent implements OnInit { this.deleteClicked.emit(); } - createLicense(licenseDetails: { id: string; licenseOptions: LicenseOptions }) { + createLicense(licenseDetails: LicenseDetails) { this.actions.saveLicense(licenseDetails.id, licenseDetails.licenseOptions); } diff --git a/src/app/features/preprints/components/stepper/review-step/review-step.component.spec.ts b/src/app/features/preprints/components/stepper/review-step/review-step.component.spec.ts index 113a240f3..ffd0ad84c 100644 --- a/src/app/features/preprints/components/stepper/review-step/review-step.component.spec.ts +++ b/src/app/features/preprints/components/stepper/review-step/review-step.component.spec.ts @@ -1,13 +1,15 @@ import { Store } from '@ngxs/store'; -import { MockComponents, MockPipe, MockProvider } from 'ng-mocks'; +import { MockComponents, MockProvider } from 'ng-mocks'; + +import { Mock } from 'vitest'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { Router } from '@angular/router'; +import { UserSelectors } from '@osf/core/store/user'; import { PreprintProviderDetails } from '@osf/features/preprints/models'; import { - FetchLicenses, FetchPreprintProject, PreprintStepperSelectors, SubmitPreprint, @@ -17,8 +19,8 @@ import { import { AffiliatedInstitutionsViewComponent } from '@osf/shared/components/affiliated-institutions-view/affiliated-institutions-view.component'; import { ContributorsListComponent } from '@osf/shared/components/contributors-list/contributors-list.component'; import { LicenseDisplayComponent } from '@osf/shared/components/license-display/license-display.component'; +import { TruncatedTextComponent } from '@osf/shared/components/truncated-text/truncated-text.component'; import { ResourceType } from '@osf/shared/enums/resource-type.enum'; -import { InterpolatePipe } from '@osf/shared/pipes/interpolate.pipe'; import { ToastService } from '@osf/shared/services/toast.service'; import { ContributorsSelectors, @@ -26,6 +28,7 @@ import { LoadMoreBibliographicContributors, } from '@osf/shared/stores/contributors'; import { FetchResourceInstitutions, InstitutionsSelectors } from '@osf/shared/stores/institutions'; +import { FetchLicense, LicensesSelectors } from '@osf/shared/stores/licenses'; import { FetchSelectedSubjects, SubjectsSelectors } from '@osf/shared/stores/subjects'; import { MOCK_CONTRIBUTOR } from '@testing/mocks/contributors.mock'; @@ -37,13 +40,23 @@ import { PREPRINT_PROVIDER_DETAILS_MOCK } from '@testing/mocks/preprint-provider import { SUBJECTS_MOCK } from '@testing/mocks/subject.mock'; import { provideOSFCore } from '@testing/osf.testing.provider'; import { RouterMockBuilder, RouterMockType } from '@testing/providers/router-provider.mock'; -import { mergeSignalOverrides, provideMockStore, SignalOverride } from '@testing/providers/store-provider.mock'; +import { + BaseSetupOverrides, + mergeSignalOverrides, + provideMockStore, + SignalOverride, +} from '@testing/providers/store-provider.mock'; import { ToastServiceMock, ToastServiceMockType } from '@testing/providers/toast-provider.mock'; import { ReviewsState } from '../../../enums'; import { ReviewStepComponent } from './review-step.component'; +interface SetupOverrides extends BaseSetupOverrides { + provider?: PreprintProviderDetails; + detectChanges?: boolean; +} + describe('ReviewStepComponent', () => { let component: ReviewStepComponent; let fixture: ComponentFixture; @@ -59,43 +72,45 @@ describe('ReviewStepComponent', () => { { selector: PreprintStepperSelectors.getPreprint, value: mockPreprint }, { selector: PreprintStepperSelectors.getPreprintFile, value: mockPreprintFile }, { selector: PreprintStepperSelectors.isPreprintSubmitting, value: false }, - { selector: PreprintStepperSelectors.getPreprintLicense, value: MOCK_LICENSE }, + { selector: LicensesSelectors.getLicense, value: MOCK_LICENSE }, { selector: PreprintStepperSelectors.getPreprintProject, value: { id: 'project-id', name: 'Test Project' } }, { selector: ContributorsSelectors.getBibliographicContributors, value: [MOCK_CONTRIBUTOR] }, { selector: ContributorsSelectors.isBibliographicContributorsLoading, value: false }, { selector: ContributorsSelectors.hasMoreBibliographicContributors, value: false }, { selector: SubjectsSelectors.getSelectedSubjects, value: SUBJECTS_MOCK }, { selector: InstitutionsSelectors.getResourceInstitutions, value: [MOCK_INSTITUTION] }, + { selector: UserSelectors.isProjectCreationDisabled, value: false }, ]; - function setup(overrides?: { - selectorOverrides?: SignalOverride[]; - provider?: PreprintProviderDetails; - detectChanges?: boolean; - }) { - const signals = mergeSignalOverrides(defaultSignals, overrides?.selectorOverrides); + function setup(overrides: SetupOverrides = {}) { routerMock = RouterMockBuilder.create().build(); toastMock = ToastServiceMock.simple(); TestBed.configureTestingModule({ imports: [ ReviewStepComponent, - ...MockComponents(AffiliatedInstitutionsViewComponent, ContributorsListComponent, LicenseDisplayComponent), - MockPipe(InterpolatePipe), + ...MockComponents( + AffiliatedInstitutionsViewComponent, + ContributorsListComponent, + LicenseDisplayComponent, + TruncatedTextComponent + ), ], providers: [ provideOSFCore(), MockProvider(Router, routerMock), MockProvider(ToastService, toastMock), - provideMockStore({ signals }), + provideMockStore({ + signals: mergeSignalOverrides(defaultSignals, overrides.selectorOverrides), + }), ], }); store = TestBed.inject(Store); fixture = TestBed.createComponent(ReviewStepComponent); component = fixture.componentInstance; - fixture.componentRef.setInput('provider', overrides && 'provider' in overrides ? overrides.provider : mockProvider); - if (overrides?.detectChanges ?? true) { + fixture.componentRef.setInput('provider', 'provider' in overrides ? overrides.provider : mockProvider); + if (overrides.detectChanges ?? true) { fixture.detectChanges(); } } @@ -103,7 +118,7 @@ describe('ReviewStepComponent', () => { it('should dispatch initial fetch actions when preprint exists', () => { setup(); - expect(store.dispatch).toHaveBeenCalledWith(new FetchLicenses(mockProvider.id)); + expect(store.dispatch).toHaveBeenCalledWith(new FetchLicense(mockPreprint.licenseId ?? undefined)); expect(store.dispatch).toHaveBeenCalledWith(new FetchPreprintProject()); expect(store.dispatch).toHaveBeenCalledWith( new GetBibliographicContributors(mockPreprint.id, ResourceType.Preprint) @@ -112,13 +127,13 @@ describe('ReviewStepComponent', () => { expect(store.dispatch).toHaveBeenCalledWith(new FetchResourceInstitutions(mockPreprint.id, ResourceType.Preprint)); }); - it('should skip preprint-dependent fetches when preprint is missing', () => { + it('should skip fetches when preprint is missing', () => { setup({ selectorOverrides: [{ selector: PreprintStepperSelectors.getPreprint, value: null }], }); - expect(store.dispatch).toHaveBeenCalledWith(new FetchLicenses(mockProvider.id)); - expect(store.dispatch).toHaveBeenCalledWith(new FetchPreprintProject()); + expect(store.dispatch).not.toHaveBeenCalledWith(expect.any(FetchLicense)); + expect(store.dispatch).not.toHaveBeenCalledWith(expect.any(FetchPreprintProject)); expect(store.dispatch).not.toHaveBeenCalledWith(expect.any(GetBibliographicContributors)); expect(store.dispatch).not.toHaveBeenCalledWith(expect.any(FetchSelectedSubjects)); expect(store.dispatch).not.toHaveBeenCalledWith(expect.any(FetchResourceInstitutions)); @@ -145,7 +160,7 @@ describe('ReviewStepComponent', () => { expect(routerMock.navigateByUrl).toHaveBeenCalledWith('/preprints'); }); - it('should return early in submitPreprint when required data is missing', () => { + it('should return early in submitPreprint when preprint is missing', () => { setup({ selectorOverrides: [{ selector: PreprintStepperSelectors.getPreprint, value: null }], detectChanges: false, @@ -159,13 +174,13 @@ describe('ReviewStepComponent', () => { }); it('should return early in submitPreprint when no file id is available', () => { - const preprintWithoutPrimaryFileId = { ...mockPreprint, primaryFileId: null }; setup({ selectorOverrides: [ - { selector: PreprintStepperSelectors.getPreprint, value: preprintWithoutPrimaryFileId }, + { selector: PreprintStepperSelectors.getPreprint, value: { ...mockPreprint, primaryFileId: null } }, { selector: PreprintStepperSelectors.getPreprintFile, value: null }, ], }); + (store.dispatch as Mock).mockClear(); component.submitPreprint(); @@ -178,6 +193,7 @@ describe('ReviewStepComponent', () => { setup({ provider: { ...mockProvider, reviewsWorkflow: null }, }); + (store.dispatch as Mock).mockClear(); component.submitPreprint(); @@ -190,10 +206,15 @@ describe('ReviewStepComponent', () => { }); it('should submit preprint when workflow exists and reviews state is not accepted', () => { - const preprintPending = { ...mockPreprint, reviewsState: ReviewsState.Pending }; setup({ - selectorOverrides: [{ selector: PreprintStepperSelectors.getPreprint, value: preprintPending }], + selectorOverrides: [ + { + selector: PreprintStepperSelectors.getPreprint, + value: { ...mockPreprint, reviewsState: ReviewsState.Pending }, + }, + ], }); + (store.dispatch as Mock).mockClear(); component.submitPreprint(); @@ -206,10 +227,15 @@ describe('ReviewStepComponent', () => { }); it('should skip submit/update when reviews state is accepted and still navigate', () => { - const preprintAccepted = { ...mockPreprint, reviewsState: ReviewsState.Accepted }; setup({ - selectorOverrides: [{ selector: PreprintStepperSelectors.getPreprint, value: preprintAccepted }], + selectorOverrides: [ + { + selector: PreprintStepperSelectors.getPreprint, + value: { ...mockPreprint, reviewsState: ReviewsState.Accepted }, + }, + ], }); + (store.dispatch as Mock).mockClear(); component.submitPreprint(); @@ -222,8 +248,9 @@ describe('ReviewStepComponent', () => { expect(routerMock.navigate).toHaveBeenCalledWith(['/preprints', mockProvider.id, mockPreprint.id]); }); - it('should load more contributors when preprint id exists', () => { + it('should load more contributors', () => { setup(); + (store.dispatch as Mock).mockClear(); component.loadMoreContributors(); @@ -232,19 +259,6 @@ describe('ReviewStepComponent', () => { ); }); - it('should load more contributors with undefined id when preprint is missing', () => { - setup({ - selectorOverrides: [{ selector: PreprintStepperSelectors.getPreprint, value: null }], - detectChanges: false, - }); - - component.loadMoreContributors(); - - expect(store.dispatch).toHaveBeenCalledWith( - new LoadMoreBibliographicContributors(undefined, ResourceType.Preprint) - ); - }); - it('should emit deleteClicked when deletePreprint is called', () => { setup({ detectChanges: false }); const emitSpy = vi.spyOn(component.deleteClicked, 'emit'); @@ -253,19 +267,4 @@ describe('ReviewStepComponent', () => { expect(emitSpy).toHaveBeenCalled(); }); - - it('should default showDeleteButton to false', () => { - setup(); - - expect(component.showDeleteButton()).toBe(false); - }); - - it('should update showDeleteButton when input changes', () => { - setup(); - - fixture.componentRef.setInput('showDeleteButton', true); - fixture.detectChanges(); - - expect(component.showDeleteButton()).toBe(true); - }); }); diff --git a/src/app/features/preprints/components/stepper/review-step/review-step.component.ts b/src/app/features/preprints/components/stepper/review-step/review-step.component.ts index d20ecd05b..e23a80cf5 100644 --- a/src/app/features/preprints/components/stepper/review-step/review-step.component.ts +++ b/src/app/features/preprints/components/stepper/review-step/review-step.component.ts @@ -16,7 +16,6 @@ import { UserSelectors } from '@osf/core/store/user'; import { ApplicabilityStatus, PreregLinkInfo, ReviewsState } from '@osf/features/preprints/enums'; import { PreprintProviderDetails } from '@osf/features/preprints/models'; import { - FetchLicenses, FetchPreprintProject, PreprintStepperSelectors, SubmitPreprint, @@ -35,6 +34,7 @@ import { LoadMoreBibliographicContributors, } from '@shared/stores/contributors'; import { FetchResourceInstitutions, InstitutionsSelectors } from '@shared/stores/institutions'; +import { FetchLicense, LicensesSelectors } from '@shared/stores/licenses'; import { FetchSelectedSubjects, SubjectsSelectors } from '@shared/stores/subjects'; @Component({ @@ -66,7 +66,7 @@ export class ReviewStepComponent implements OnInit { private readonly actions = createDispatchMap({ getBibliographicContributors: GetBibliographicContributors, fetchSubjects: FetchSelectedSubjects, - fetchLicenses: FetchLicenses, + fetchLicense: FetchLicense, fetchPreprintProject: FetchPreprintProject, submitPreprint: SubmitPreprint, fetchResourceInstitutions: FetchResourceInstitutions, @@ -84,7 +84,7 @@ export class ReviewStepComponent implements OnInit { readonly hasMoreBibliographicContributors = select(ContributorsSelectors.hasMoreBibliographicContributors); readonly subjects = select(SubjectsSelectors.getSelectedSubjects); readonly affiliatedInstitutions = select(InstitutionsSelectors.getResourceInstitutions); - readonly license = select(PreprintStepperSelectors.getPreprintLicense); + readonly license = select(LicensesSelectors.getLicense); readonly preprintProject = select(PreprintStepperSelectors.getPreprintProject); readonly isProjectCreationDisabled = select(UserSelectors.isProjectCreationDisabled); readonly licenseOptionsRecord = computed(() => (this.preprint()?.licenseOptions ?? {}) as Record); @@ -93,17 +93,16 @@ export class ReviewStepComponent implements OnInit { readonly PreregLinkInfo = PreregLinkInfo; ngOnInit(): void { - this.actions.fetchLicenses(this.provider().id); - this.actions.fetchPreprintProject(); - - const preprintId = this.preprint()?.id; - if (!preprintId) { + const preprint = this.preprint(); + if (!preprint?.id) { return; } - this.actions.getBibliographicContributors(preprintId, ResourceType.Preprint); - this.actions.fetchSubjects(preprintId, ResourceType.Preprint); - this.actions.fetchResourceInstitutions(preprintId, ResourceType.Preprint); + this.actions.fetchLicense(preprint.licenseId ?? undefined); + this.actions.getBibliographicContributors(preprint.id, ResourceType.Preprint); + this.actions.fetchSubjects(preprint.id, ResourceType.Preprint); + this.actions.fetchResourceInstitutions(preprint.id, ResourceType.Preprint); + this.actions.fetchPreprintProject(); } submitPreprint(): void { diff --git a/src/app/features/preprints/mappers/preprint-providers.mapper.ts b/src/app/features/preprints/mappers/preprint-providers.mapper.ts index bbb1eb94d..6a94b1742 100644 --- a/src/app/features/preprints/mappers/preprint-providers.mapper.ts +++ b/src/app/features/preprints/mappers/preprint-providers.mapper.ts @@ -29,6 +29,7 @@ export class PreprintProvidersMapper { facebookAppId: response.attributes.facebook_app_id, reviewsCommentsPrivate: response.attributes.reviews_comments_private, reviewsCommentsAnonymous: response.attributes.reviews_comments_anonymous, + licensesLink: response.relationships?.licenses_acceptable?.links?.related?.href ?? '', }; } diff --git a/src/app/features/preprints/mappers/preprints.mapper.ts b/src/app/features/preprints/mappers/preprints.mapper.ts index 952817c24..78ee46cb7 100644 --- a/src/app/features/preprints/mappers/preprints.mapper.ts +++ b/src/app/features/preprints/mappers/preprints.mapper.ts @@ -54,6 +54,7 @@ export class PreprintsMapper { isPublic: response.attributes.public, version: response.attributes.version, isLatestVersion: response.attributes.is_latest_version, + isMigrated: !!response.attributes.is_migrated, isPreprintOrphan: response.attributes.is_preprint_orphan, primaryFileId: response.relationships.primary_file?.data?.id || null, nodeId: response.relationships.node?.data?.id, @@ -109,6 +110,7 @@ export class PreprintsMapper { isPublic: data.attributes.public, version: data.attributes.version, isLatestVersion: data.attributes.is_latest_version, + isMigrated: !!data.attributes.is_migrated, isPreprintOrphan: data.attributes.is_preprint_orphan, primaryFileId: data.relationships.primary_file?.data?.id || null, nodeId: data.relationships.node?.data?.id, @@ -168,6 +170,7 @@ export class PreprintsMapper { dateModified: preprintData.attributes.date_modified, contributors: ContributorsMapper.getContributors(preprintData.embeds?.bibliographic_contributors?.data), providerId: preprintData.relationships.provider.data.id, + isMigrated: !!preprintData.attributes?.is_migrated, })), totalCount: response.meta.total, }; diff --git a/src/app/features/preprints/models/preprint-provider-json-api.model.ts b/src/app/features/preprints/models/preprint-provider-json-api.model.ts index 0ed0cb67f..e24d0f546 100644 --- a/src/app/features/preprints/models/preprint-provider-json-api.model.ts +++ b/src/app/features/preprints/models/preprint-provider-json-api.model.ts @@ -3,6 +3,7 @@ import { StringOrNull } from '@osf/shared/helpers/types.helper'; import { BrandDataJsonApi } from '@osf/shared/models/brand/brand-json-api.model'; import { Embed } from '@osf/shared/models/common/json-api/embeds.model'; import { ResourceLinksJsonApi } from '@osf/shared/models/common/json-api/links.model'; +import { ToManyRel } from '@osf/shared/models/common/json-api/relationships.model'; import { JsonApiResource } from '@osf/shared/models/common/json-api/resource.model'; import { ItemResponse, ListResponse } from '@osf/shared/models/common/json-api/responses.model'; @@ -18,6 +19,9 @@ export interface PreprintProviderDetailsJsonApi extends JsonApiResource< PreprintProviderAttributesJsonApi > { embeds?: PreprintProviderEmbedsJsonApi; + relationships?: { + licenses_acceptable?: Pick, 'links'>; + }; links: ResourceLinksJsonApi; } diff --git a/src/app/features/preprints/models/preprint-provider.model.ts b/src/app/features/preprints/models/preprint-provider.model.ts index 362917430..0154ebf3c 100644 --- a/src/app/features/preprints/models/preprint-provider.model.ts +++ b/src/app/features/preprints/models/preprint-provider.model.ts @@ -28,6 +28,7 @@ export interface PreprintProviderDetails { facebookAppId: StringOrNull; reviewsCommentsPrivate: StringOrNull; reviewsCommentsAnonymous: StringOrNull; + licensesLink?: string; } export interface PreprintProviderShortInfo { diff --git a/src/app/features/preprints/models/preprint.model.ts b/src/app/features/preprints/models/preprint.model.ts index e966e60ce..bdb84aa44 100644 --- a/src/app/features/preprints/models/preprint.model.ts +++ b/src/app/features/preprints/models/preprint.model.ts @@ -26,6 +26,7 @@ export interface PreprintModel { isPublic: boolean; version: number; isLatestVersion: boolean; + isMigrated: boolean; isPreprintOrphan: boolean; withdrawalJustification: StringOrNull; nodeId: StringOrNull; @@ -60,6 +61,7 @@ export interface PreprintShortInfo { dateModified: string; contributors: ContributorModel[]; providerId: string; + isMigrated: boolean; } export interface PreprintShortInfoWithTotalCount { diff --git a/src/app/features/preprints/pages/my-preprints/my-preprints.component.html b/src/app/features/preprints/pages/my-preprints/my-preprints.component.html index 67234dbe3..ceadb83ce 100644 --- a/src/app/features/preprints/pages/my-preprints/my-preprints.component.html +++ b/src/app/features/preprints/pages/my-preprints/my-preprints.component.html @@ -25,9 +25,7 @@ paginatorDropdownAppendTo="body" [resizableColumns]="true" [scrollable]="true" - [sortMode]="'single'" [lazy]="true" - [lazyLoadOnInit]="true" (onPage)="onPageChange($event)" (onSort)="onSort($event)" [sortField]="sortColumn()" @@ -51,7 +49,12 @@ @if (item?.id) { - {{ item.title }} + +
+ {{ item.title }} + +
+ diff --git a/src/app/features/preprints/pages/my-preprints/my-preprints.component.scss b/src/app/features/preprints/pages/my-preprints/my-preprints.component.scss deleted file mode 100644 index e69de29bb..000000000 diff --git a/src/app/features/preprints/pages/my-preprints/my-preprints.component.ts b/src/app/features/preprints/pages/my-preprints/my-preprints.component.ts index 79a9f5cac..9b29f5e79 100644 --- a/src/app/features/preprints/pages/my-preprints/my-preprints.component.ts +++ b/src/app/features/preprints/pages/my-preprints/my-preprints.component.ts @@ -24,6 +24,7 @@ import { FormControl } from '@angular/forms'; import { ActivatedRoute, Router } from '@angular/router'; import { ContributorsListShortenerComponent } from '@osf/shared/components/contributors-list-shortener/contributors-list-shortener.component'; +import { MigratedLabelComponent } from '@osf/shared/components/migrated-label/migrated-label.component'; import { SearchInputComponent } from '@osf/shared/components/search-input/search-input.component'; import { SubHeaderComponent } from '@osf/shared/components/sub-header/sub-header.component'; import { DEFAULT_TABLE_PARAMS } from '@osf/shared/constants/default-table-params.constants'; @@ -47,9 +48,9 @@ import { FetchMyPreprints, MyPreprintsSelectors } from '../../store/my-preprints DatePipe, TranslatePipe, TitleCasePipe, + MigratedLabelComponent, ], templateUrl: './my-preprints.component.html', - styleUrl: './my-preprints.component.scss', changeDetection: ChangeDetectionStrategy.OnPush, }) export class MyPreprintsComponent { diff --git a/src/app/features/preprints/pages/preprint-details/preprint-details.component.html b/src/app/features/preprints/pages/preprint-details/preprint-details.component.html index 0c60a008f..2c18f3011 100644 --- a/src/app/features/preprints/pages/preprint-details/preprint-details.component.html +++ b/src/app/features/preprints/pages/preprint-details/preprint-details.component.html @@ -1,3 +1,6 @@ +@let provider = preprintProvider(); +@let isMigrated = !!preprint()?.isMigrated; +
@@ -10,12 +13,12 @@
@@ -24,7 +27,7 @@

{{ preprint()?.title }}

} - @if (moderationMode()) { + @if (moderationMode() && !isMigrated) { @if ( isPreprintLoading() || areReviewActionsLoading() || @@ -32,9 +35,9 @@

{{ preprint()?.title }}

areRequestActionsLoading() ) { - } @else { + } @else if (provider) { {{ preprint()?.title }} class="w-full md:w-11rem" styleClass="w-full" [label]="editButtonLabel() | translate" + [disabled]="isMigrated" (onClick)="editPreprintClicked()" /> } @@ -64,6 +68,7 @@

{{ preprint()?.title }}

class="w-full md:w-11rem" styleClass="w-full" [label]="'common.buttons.createNewVersion' | translate" + [disabled]="isMigrated" (onClick)="createNewVersionClicked()" /> } @@ -73,32 +78,39 @@

{{ preprint()?.title }}

styleClass="w-full" [label]="'common.buttons.withdraw' | translate" severity="danger" + [disabled]="isMigrated" (onClick)="handleWithdrawClicked()" /> } - + }
+ @if (isMigrated) { + + {{ 'preprints.details.migratedBanner' | translate }} + + } + @if (isOsfPreprint()) { } - @if (moderationStatusBannerVisible()) { + @if (moderationStatusBannerVisible() && provider) { } - @if (statusBannerVisible()) { + @if (statusBannerVisible() && provider) { {{ preprint()?.title }} @if (!preprint()?.dateWithdrawn) {
- +
@@ -129,7 +141,7 @@

{{ preprint()?.title }}

} @else { } diff --git a/src/app/features/preprints/pages/preprint-details/preprint-details.component.ts b/src/app/features/preprints/pages/preprint-details/preprint-details.component.ts index d454e1bb2..105c63ed0 100644 --- a/src/app/features/preprints/pages/preprint-details/preprint-details.component.ts +++ b/src/app/features/preprints/pages/preprint-details/preprint-details.component.ts @@ -3,6 +3,7 @@ import { createDispatchMap, select, Store } from '@ngxs/store'; import { TranslatePipe, TranslateService } from '@ngx-translate/core'; import { Button } from 'primeng/button'; +import { Message } from 'primeng/message'; import { Skeleton } from 'primeng/skeleton'; import { catchError, EMPTY, filter, map } from 'rxjs'; @@ -68,6 +69,7 @@ import { CreateNewVersion, PreprintStepperSelectors } from '../../store/preprint imports: [ Button, Skeleton, + Message, PreprintFileSectionComponent, ShareAndDownloadComponent, GeneralInformationComponent, @@ -147,7 +149,6 @@ export class PreprintDetailsComponent implements OnInit, OnDestroy { }); latestAction = computed(() => { - // banners and the decision dialog describe the last decision, and a spam report is not one const actions = this.reviewActions().filter((action) => action.trigger !== ReviewActionTrigger.ReportSpam); return actions.length > 0 ? actions[0] : null; }); @@ -323,16 +324,20 @@ export class PreprintDetailsComponent implements OnInit, OnDestroy { } handleWithdrawClicked(): void { + const provider = this.preprintProvider(); + const preprint = this.preprint(); + + if (!provider || !preprint || preprint.isMigrated) { + return; + } + this.customDialogService .open(PreprintWithdrawDialogComponent, { header: this.translateService.instant('preprints.details.withdrawDialog.title', { - preprintWord: this.preprintProvider()!.preprintWord, + preprintWord: provider.preprintWord, }), width: '700px', - data: { - preprint: this.preprint(), - provider: this.preprintProvider(), - }, + data: { preprint, provider }, }) .onClose.pipe(takeUntilDestroyed(this.destroyRef), filter(Boolean)) .subscribe(() => this.fetchPreprint(this.preprintId())); @@ -342,7 +347,7 @@ export class PreprintDetailsComponent implements OnInit, OnDestroy { const providerId = this.providerId(); const preprintId = this.preprintId(); - if (!providerId || !preprintId) { + if (!providerId || !preprintId || this.preprint()?.isMigrated) { return; } @@ -352,7 +357,7 @@ export class PreprintDetailsComponent implements OnInit, OnDestroy { createNewVersionClicked(): void { const preprintId = this.preprintId(); - if (!preprintId) { + if (!preprintId || this.preprint()?.isMigrated) { return; } diff --git a/src/app/features/preprints/services/preprint-licenses.service.spec.ts b/src/app/features/preprints/services/preprint-licenses.service.spec.ts new file mode 100644 index 000000000..7010e187e --- /dev/null +++ b/src/app/features/preprints/services/preprint-licenses.service.spec.ts @@ -0,0 +1,102 @@ +import { MockProvider } from 'ng-mocks'; + +import { firstValueFrom, of } from 'rxjs'; + +import { TestBed } from '@angular/core/testing'; + +import { PreprintsMapper } from '@osf/features/preprints/mappers'; +import { LicenseOptions } from '@osf/shared/models/license/license.model'; +import { PreprintDataJsonApi } from '@osf/shared/models/preprints/preprint-json-api.model'; +import { JsonApiService } from '@osf/shared/services/json-api.service'; + +import { PREPRINT_MOCK } from '@testing/mocks/preprint.mock'; +import { MOCK_API_URL, provideMockEnvironment } from '@testing/providers/environment.provider.mock'; +import { JsonApiServiceMock, JsonApiServiceMockType } from '@testing/providers/json-api.service.mock'; + +import { PreprintLicensesService } from './preprint-licenses.service'; + +describe('PreprintLicensesService', () => { + let service: PreprintLicensesService; + let jsonApiService: JsonApiServiceMockType; + + const preprintId = 'preprint-1'; + const licenseId = 'license-123'; + const apiResponse = { id: preprintId } as PreprintDataJsonApi; + + function setup() { + jsonApiService = JsonApiServiceMock.simple(); + + TestBed.configureTestingModule({ + providers: [PreprintLicensesService, MockProvider(JsonApiService, jsonApiService), provideMockEnvironment()], + }); + + service = TestBed.inject(PreprintLicensesService); + } + + it('should expose apiUrl from environment', () => { + setup(); + + expect(service.apiUrl).toBe(MOCK_API_URL); + }); + + it('updatePreprintLicense should patch without license_record when options are omitted', async () => { + setup(); + const mapperSpy = vi.spyOn(PreprintsMapper, 'fromPreprintJsonApi').mockReturnValue(PREPRINT_MOCK); + jsonApiService.patch.mockReturnValue(of(apiResponse)); + + const response = await firstValueFrom(service.updatePreprintLicense(preprintId, licenseId)); + + expect(jsonApiService.patch).toHaveBeenCalledWith(`${MOCK_API_URL}/preprints/${preprintId}/`, { + data: { + type: 'preprints', + id: preprintId, + relationships: { + license: { + data: { + id: licenseId, + type: 'licenses', + }, + }, + }, + attributes: {}, + }, + }); + expect(mapperSpy).toHaveBeenCalledWith(apiResponse); + expect(response).toEqual(PREPRINT_MOCK); + }); + + it('updatePreprintLicense should patch with license_record when options are provided', async () => { + setup(); + const licenseOptions: LicenseOptions = { + copyrightHolders: 'John Doe', + year: '2023', + }; + const mapperSpy = vi.spyOn(PreprintsMapper, 'fromPreprintJsonApi').mockReturnValue(PREPRINT_MOCK); + jsonApiService.patch.mockReturnValue(of(apiResponse)); + + const response = await firstValueFrom(service.updatePreprintLicense(preprintId, licenseId, licenseOptions)); + + expect(jsonApiService.patch).toHaveBeenCalledWith(`${MOCK_API_URL}/preprints/${preprintId}/`, { + data: { + type: 'preprints', + id: preprintId, + relationships: { + license: { + data: { + id: licenseId, + type: 'licenses', + }, + }, + }, + attributes: { + license_record: { + copyright_holders: [licenseOptions.copyrightHolders], + year: licenseOptions.year, + }, + }, + }, + }); + expect(mapperSpy).toHaveBeenCalledWith(apiResponse); + expect(response).toEqual(PREPRINT_MOCK); + }); +}); diff --git a/src/app/features/preprints/services/preprint-licenses.service.ts b/src/app/features/preprints/services/preprint-licenses.service.ts index 6f8de72cf..fbb9acbbe 100644 --- a/src/app/features/preprints/services/preprint-licenses.service.ts +++ b/src/app/features/preprints/services/preprint-licenses.service.ts @@ -1,4 +1,4 @@ -import { map, Observable } from 'rxjs'; +import { map } from 'rxjs'; import { inject, Injectable } from '@angular/core'; @@ -6,9 +6,7 @@ import { ENVIRONMENT } from '@core/provider/environment.provider'; import { PreprintsMapper } from '@osf/features/preprints/mappers'; import { PreprintDataJsonApi } from '@osf/shared/models/preprints/preprint-json-api.model'; import { JsonApiService } from '@osf/shared/services/json-api.service'; -import { LicensesMapper } from '@shared/mappers/licenses.mapper'; -import { LicenseModel, LicenseOptions } from '@shared/models/license/license.model'; -import { LicensesResponseJsonApi } from '@shared/models/license/licenses-json-api.model'; +import { LicenseOptions } from '@shared/models/license/license.model'; import { PreprintLicensePayloadJsonApi } from '../models'; @@ -23,15 +21,6 @@ export class PreprintLicensesService { return `${this.environment.apiDomainUrl}/v2`; } - getLicenses(providerId: string): Observable { - return this.jsonApiService - .get(`${this.apiUrl}/providers/preprints/${providerId}/licenses/`, { - 'page[size]': 100, - sort: 'name', - }) - .pipe(map((licenses) => LicensesMapper.fromLicensesResponse(licenses))); - } - updatePreprintLicense(preprintId: string, licenseId: string, licenseOptions?: LicenseOptions) { const payload: PreprintLicensePayloadJsonApi = { data: { diff --git a/src/app/features/preprints/services/preprints.service.spec.ts b/src/app/features/preprints/services/preprints.service.spec.ts new file mode 100644 index 000000000..d4e4cafce --- /dev/null +++ b/src/app/features/preprints/services/preprints.service.spec.ts @@ -0,0 +1,325 @@ +import { MockProvider } from 'ng-mocks'; + +import { firstValueFrom, of, throwError } from 'rxjs'; + +import { TestBed } from '@angular/core/testing'; +import { Router } from '@angular/router'; + +import { RegistryModerationMapper } from '@osf/features/moderation/mappers'; +import { PreprintRequestActionsMapper, PreprintRequestMapper, PreprintsMapper } from '@osf/features/preprints/mappers'; +import { SortOrder } from '@osf/shared/enums/sort-order.enum'; +import { + PreprintDataJsonApi, + PreprintMetricsResponseJsonApi, + PreprintResponseJsonApi, + PreprintsListResponseJsonApi, +} from '@osf/shared/models/preprints/preprint-json-api.model'; +import { JsonApiService } from '@osf/shared/services/json-api.service'; + +import { PREPRINT_MOCK } from '@testing/mocks/preprint.mock'; +import { PREPRINT_REQUEST_MOCK } from '@testing/mocks/preprint-request.mock'; +import { PREPRINT_SHORT_INFO_ARRAY_MOCK } from '@testing/mocks/preprint-short-info.mock'; +import { REVIEW_ACTION_MOCK } from '@testing/mocks/review-action.mock'; +import { MOCK_API_URL, provideMockEnvironment } from '@testing/providers/environment.provider.mock'; +import { JsonApiServiceMock, JsonApiServiceMockType } from '@testing/providers/json-api.service.mock'; +import { RouterMockBuilder, RouterMockType } from '@testing/providers/router-provider.mock'; + +import { + PreprintRequestAction, + PreprintRequestActionsJsonApiResponse, + PreprintRequestsJsonApiResponse, +} from '../models'; + +import { PreprintsService } from './preprints.service'; + +describe('PreprintsService', () => { + let service: PreprintsService; + let jsonApiService: JsonApiServiceMockType; + let router: RouterMockType; + + const preprintId = 'preprint-1'; + const providerId = 'osf'; + const preprintResponse = { data: { id: preprintId } } as PreprintResponseJsonApi; + const preprintData = { id: preprintId } as PreprintDataJsonApi; + + function setup() { + jsonApiService = JsonApiServiceMock.simple(); + router = RouterMockBuilder.create().build(); + + TestBed.configureTestingModule({ + providers: [ + PreprintsService, + MockProvider(JsonApiService, jsonApiService), + MockProvider(Router, router), + provideMockEnvironment(), + ], + }); + + service = TestBed.inject(PreprintsService); + } + + it('should expose apiUrl from environment', () => { + setup(); + + expect(service.apiUrl).toBe(MOCK_API_URL); + }); + + it('createPreprint should post create payload and map response', async () => { + setup(); + const mapperSpy = vi.spyOn(PreprintsMapper, 'fromPreprintJsonApi').mockReturnValue(PREPRINT_MOCK); + jsonApiService.post.mockReturnValue(of(preprintResponse)); + + const response = await firstValueFrom(service.createPreprint('Title', 'Abstract', providerId)); + + expect(jsonApiService.post).toHaveBeenCalledWith( + `${MOCK_API_URL}/preprints/`, + PreprintsMapper.toCreatePayload('Title', 'Abstract', providerId) + ); + expect(mapperSpy).toHaveBeenCalledWith(preprintResponse.data); + expect(response).toEqual(PREPRINT_MOCK); + }); + + it('getById should request preprint and map response', async () => { + setup(); + const mapperSpy = vi.spyOn(PreprintsMapper, 'fromPreprintJsonApi').mockReturnValue(PREPRINT_MOCK); + jsonApiService.get.mockReturnValue(of(preprintResponse)); + + const response = await firstValueFrom(service.getById(preprintId)); + + expect(jsonApiService.get).toHaveBeenCalledWith(`${MOCK_API_URL}/preprints/${preprintId}/`); + expect(mapperSpy).toHaveBeenCalledWith(preprintResponse.data); + expect(response).toEqual(PREPRINT_MOCK); + }); + + it('getByIdWithEmbeds should request embeds and map response', async () => { + setup(); + const mapperSpy = vi.spyOn(PreprintsMapper, 'fromPreprintWithEmbedsJsonApi').mockReturnValue(PREPRINT_MOCK); + jsonApiService.get.mockReturnValue(of(preprintResponse)); + + const response = await firstValueFrom(service.getByIdWithEmbeds(preprintId)); + + expect(jsonApiService.get).toHaveBeenCalledWith(`${MOCK_API_URL}/preprints/${preprintId}/`, { + 'embed[]': ['license', 'identifiers'], + }); + expect(mapperSpy).toHaveBeenCalledWith(preprintResponse); + expect(response).toEqual(PREPRINT_MOCK); + }); + + it('getByIdWithEmbeds should navigate to spam content for flagged errors', async () => { + setup(); + const error = { + error: { + errors: [{ meta: { flagged_content: true } }], + }, + }; + jsonApiService.get.mockReturnValue(throwError(() => error)); + + await expect(firstValueFrom(service.getByIdWithEmbeds(preprintId))).rejects.toEqual(error); + expect(router.navigate).toHaveBeenCalledWith(['/spam-content']); + }); + + it('getByIdWithEmbeds should rethrow other errors without navigating', async () => { + setup(); + const error = { error: { errors: [{ detail: 'not found' }] } }; + jsonApiService.get.mockReturnValue(throwError(() => error)); + + await expect(firstValueFrom(service.getByIdWithEmbeds(preprintId))).rejects.toEqual(error); + expect(router.navigate).not.toHaveBeenCalled(); + }); + + it('getPreprintMetrics should map downloads and views', async () => { + setup(); + const metricsResponse = { + meta: { + metrics: { + downloads: 12, + views: 34, + }, + }, + } as PreprintMetricsResponseJsonApi; + jsonApiService.get.mockReturnValue(of(metricsResponse)); + + const response = await firstValueFrom(service.getPreprintMetrics(preprintId)); + + expect(jsonApiService.get).toHaveBeenCalledWith(`${MOCK_API_URL}/preprints/${preprintId}/`, { + 'metrics[views]': 'total', + 'metrics[downloads]': 'total', + }); + expect(response).toEqual({ downloads: 12, views: 34 }); + }); + + it('updatePreprint should patch mapped attributes and skip undefined fields', async () => { + setup(); + const mapperSpy = vi.spyOn(PreprintsMapper, 'fromPreprintJsonApi').mockReturnValue(PREPRINT_MOCK); + jsonApiService.patch.mockReturnValue(of(preprintData)); + + const response = await firstValueFrom( + service.updatePreprint(preprintId, { + title: 'Updated', + hasCoi: true, + doi: undefined, + }) + ); + + expect(jsonApiService.patch).toHaveBeenCalledWith(`${MOCK_API_URL}/preprints/${preprintId}/`, { + data: { + type: 'preprints', + id: preprintId, + attributes: { + title: 'Updated', + has_coi: true, + }, + }, + }); + expect(mapperSpy).toHaveBeenCalledWith(preprintData); + expect(response).toEqual(PREPRINT_MOCK); + }); + + it('submitPreprint should post submit review action payload', async () => { + setup(); + jsonApiService.post.mockReturnValue(of({})); + + await firstValueFrom(service.submitPreprint(preprintId)); + + expect(jsonApiService.post).toHaveBeenCalledWith( + `${MOCK_API_URL}/preprints/${preprintId}/review_actions/`, + PreprintsMapper.toReviewActionPayload(preprintId, 'submit') + ); + }); + + it('createNewVersion should post versions endpoint and map response', async () => { + setup(); + const mapperSpy = vi.spyOn(PreprintsMapper, 'fromPreprintJsonApi').mockReturnValue(PREPRINT_MOCK); + jsonApiService.post.mockReturnValue(of(preprintResponse)); + + const response = await firstValueFrom(service.createNewVersion(preprintId)); + + expect(jsonApiService.post).toHaveBeenCalledWith(`${MOCK_API_URL}/preprints/${preprintId}/versions/`); + expect(mapperSpy).toHaveBeenCalledWith(preprintResponse.data); + expect(response).toEqual(PREPRINT_MOCK); + }); + + it('getPreprintVersionIds should return version ids', async () => { + setup(); + const listResponse = { + data: [{ id: 'v1' }, { id: 'v2' }], + } as PreprintsListResponseJsonApi; + jsonApiService.get.mockReturnValue(of(listResponse)); + + const response = await firstValueFrom(service.getPreprintVersionIds(preprintId)); + + expect(jsonApiService.get).toHaveBeenCalledWith(`${MOCK_API_URL}/preprints/${preprintId}/versions/`); + expect(response).toEqual(['v1', 'v2']); + }); + + it('getMyPreprints should request user preprints with filters and map response', async () => { + setup(); + const mapped = { data: PREPRINT_SHORT_INFO_ARRAY_MOCK, totalCount: 5 }; + const mapperSpy = vi.spyOn(PreprintsMapper, 'fromMyPreprintJsonApi').mockReturnValue(mapped); + const listResponse = { data: [], meta: { total: 0 } } as PreprintsListResponseJsonApi; + jsonApiService.get.mockReturnValue(of(listResponse)); + + const response = await firstValueFrom( + service.getMyPreprints(2, 25, { + searchValue: 'alpha', + searchFields: ['title', 'tags'], + sortColumn: 'dateModified', + sortOrder: SortOrder.Desc, + }) + ); + + expect(jsonApiService.get).toHaveBeenCalledWith(`${MOCK_API_URL}/users/me/preprints/`, { + 'embed[]': ['bibliographic_contributors'], + 'fields[users]': 'family_name,full_name,given_name,middle_name', + 'fields[preprints]': 'title,date_modified,public,bibliographic_contributors,provider,is_migrated', + 'filter[title,tags]': 'alpha', + page: 2, + 'page[size]': 25, + sort: '-date_modified', + }); + expect(mapperSpy).toHaveBeenCalledWith(listResponse); + expect(response).toEqual(mapped); + }); + + it('getPreprintReviewActions should map review actions', async () => { + setup(); + const actionData = { id: 'action-1' }; + const mapperSpy = vi.spyOn(RegistryModerationMapper, 'fromActionResponse').mockReturnValue(REVIEW_ACTION_MOCK); + jsonApiService.get.mockReturnValue(of({ data: [actionData] })); + + const response = await firstValueFrom(service.getPreprintReviewActions(preprintId)); + + expect(jsonApiService.get).toHaveBeenCalledWith( + `${MOCK_API_URL}/preprints/${preprintId}/review_actions/?embed=creator` + ); + expect(mapperSpy).toHaveBeenCalledWith(actionData); + expect(response).toEqual([REVIEW_ACTION_MOCK]); + }); + + it('getPreprintRequests should map preprint requests', async () => { + setup(); + const requestData = { id: 'request-1' }; + const mapperSpy = vi.spyOn(PreprintRequestMapper, 'fromPreprintRequest').mockReturnValue(PREPRINT_REQUEST_MOCK); + jsonApiService.get.mockReturnValue(of({ data: [requestData] } as PreprintRequestsJsonApiResponse)); + + const response = await firstValueFrom(service.getPreprintRequests(preprintId)); + + expect(jsonApiService.get).toHaveBeenCalledWith(`${MOCK_API_URL}/preprints/${preprintId}/requests/?embed=creator`); + expect(mapperSpy).toHaveBeenCalledWith(requestData); + expect(response).toEqual([PREPRINT_REQUEST_MOCK]); + }); + + it('getPreprintRequestActions should map request actions', async () => { + setup(); + const requestId = 'request-1'; + const actionData = { id: 'request-action-1' }; + const mappedAction = { id: 'request-action-1' } as PreprintRequestAction; + const mapperSpy = vi + .spyOn(PreprintRequestActionsMapper, 'fromPreprintRequestActions') + .mockReturnValue(mappedAction); + jsonApiService.get.mockReturnValue(of({ data: [actionData] } as PreprintRequestActionsJsonApiResponse)); + + const response = await firstValueFrom(service.getPreprintRequestActions(requestId)); + + expect(jsonApiService.get).toHaveBeenCalledWith(`${MOCK_API_URL}/requests/${requestId}/actions/`); + expect(mapperSpy).toHaveBeenCalledWith(actionData); + expect(response).toEqual([mappedAction]); + }); + + it('withdrawPreprint should post withdraw payload', async () => { + setup(); + jsonApiService.post.mockReturnValue(of({})); + + await firstValueFrom(service.withdrawPreprint(preprintId, 'reason')); + + expect(jsonApiService.post).toHaveBeenCalledWith( + `${MOCK_API_URL}/preprints/${preprintId}/requests/`, + PreprintRequestMapper.toWithdrawPreprintPayload(preprintId, 'reason') + ); + }); + + it('submitReviewsDecision should post review decision payload', async () => { + setup(); + jsonApiService.post.mockReturnValue(of({})); + + await firstValueFrom(service.submitReviewsDecision(preprintId, 'accept', 'looks good')); + + expect(jsonApiService.post).toHaveBeenCalledWith( + `${MOCK_API_URL}/actions/reviews/`, + PreprintsMapper.toReviewActionPayload(preprintId, 'accept', 'looks good') + ); + }); + + it('submitRequestsDecision should post request decision payload', async () => { + setup(); + const requestId = 'request-1'; + jsonApiService.post.mockReturnValue(of({})); + + await firstValueFrom(service.submitRequestsDecision(requestId, 'accept', null)); + + expect(jsonApiService.post).toHaveBeenCalledWith( + `${MOCK_API_URL}/actions/requests/preprints/`, + PreprintRequestActionsMapper.toRequestActionPayload(requestId, 'accept', null) + ); + }); +}); diff --git a/src/app/features/preprints/services/preprints.service.ts b/src/app/features/preprints/services/preprints.service.ts index d065f23d0..cdd62f29d 100644 --- a/src/app/features/preprints/services/preprints.service.ts +++ b/src/app/features/preprints/services/preprints.service.ts @@ -3,11 +3,9 @@ import { catchError, map, Observable, throwError } from 'rxjs'; import { inject, Injectable } from '@angular/core'; import { Router } from '@angular/router'; -import { ENVIRONMENT } from '@core/provider/environment.provider'; +import { ENVIRONMENT } from '@osf/core/provider/environment.provider'; import { RegistryModerationMapper } from '@osf/features/moderation/mappers'; -import { ReviewActionsResponseJsonApi } from '@osf/features/moderation/models/review-action-json-api.model'; -import { PreprintRequestActionsMapper } from '@osf/features/preprints/mappers/preprint-request-actions.mapper'; -import { PreprintRequestAction } from '@osf/features/preprints/models/preprint-request-action.model'; +import { ReviewActionsResponseJsonApi } from '@osf/features/moderation/models'; import { searchPreferencesToJsonApiQueryParams } from '@osf/shared/helpers/search-pref-to-json-api-query-params.helper'; import { StringOrNull } from '@osf/shared/helpers/types.helper'; import { @@ -21,10 +19,11 @@ import { SearchFilters } from '@osf/shared/models/search-filters.model'; import { JsonApiService } from '@osf/shared/services/json-api.service'; import { preprintSortFieldMap } from '../constants'; -import { PreprintRequestMapper, PreprintsMapper } from '../mappers'; +import { PreprintRequestActionsMapper, PreprintRequestMapper, PreprintsMapper } from '../mappers'; import { PreprintModel, PreprintRequest, + PreprintRequestAction, PreprintRequestActionsJsonApiResponse, PreprintRequestsJsonApiResponse, } from '../models'; @@ -143,7 +142,7 @@ export class PreprintsService { const params: Record = { 'embed[]': ['bibliographic_contributors'], 'fields[users]': 'family_name,full_name,given_name,middle_name', - 'fields[preprints]': 'title,date_modified,public,bibliographic_contributors,provider', + 'fields[preprints]': 'title,date_modified,public,bibliographic_contributors,provider,is_migrated', }; searchPreferencesToJsonApiQueryParams(params, pageNumber, pageSize, filters, preprintSortFieldMap); diff --git a/src/app/features/preprints/store/preprint-stepper/preprint-stepper.actions.ts b/src/app/features/preprints/store/preprint-stepper/preprint-stepper.actions.ts index 9edce748b..01baff0b7 100644 --- a/src/app/features/preprints/store/preprint-stepper/preprint-stepper.actions.ts +++ b/src/app/features/preprints/store/preprint-stepper/preprint-stepper.actions.ts @@ -53,10 +53,10 @@ export class UpdatePrimaryFileRelationship { constructor(public fileId: string) {} } -export class ReuploadFile { - static readonly type = '[Preprint Stepper] Reupload File'; +export class DeletePreprintFile { + static readonly type = '[Preprint Stepper] Delete Preprint File'; - constructor(public file: File) {} + constructor(public deleteLink: string) {} } export class CopyFileFromProject { @@ -93,7 +93,7 @@ export class FetchProjectFilesByLink { export class FetchLicenses { static readonly type = '[Preprint Stepper] Fetch Licenses'; - constructor(public providerId: string) {} + constructor(public licensesUrl?: string) {} } export class SaveLicense { @@ -132,7 +132,7 @@ export class CreateNewProject { } export class SubmitPreprint { - static readonly type = '[Preprint Stepper] Preprint Stepper'; + static readonly type = '[Preprint Stepper] Submit Preprint'; } export class CreateNewVersion { diff --git a/src/app/features/preprints/store/preprint-stepper/preprint-stepper.selectors.ts b/src/app/features/preprints/store/preprint-stepper/preprint-stepper.selectors.ts index f88c8eaf9..d53c8db0c 100644 --- a/src/app/features/preprints/store/preprint-stepper/preprint-stepper.selectors.ts +++ b/src/app/features/preprints/store/preprint-stepper/preprint-stepper.selectors.ts @@ -64,11 +64,6 @@ export class PreprintStepperSelectors { return state.licenses.data; } - @Selector([PreprintStepperState]) - static getPreprintLicense(state: PreprintStepperStateModel) { - return state.licenses.data.find((l) => l.id === state.preprint.data?.licenseId) || null; - } - @Selector([PreprintStepperState]) static getPreprintProject(state: PreprintStepperStateModel) { return state.preprintProject.data; diff --git a/src/app/features/preprints/store/preprint-stepper/preprint-stepper.state.ts b/src/app/features/preprints/store/preprint-stepper/preprint-stepper.state.ts index ff1e17cc7..f30440c62 100644 --- a/src/app/features/preprints/store/preprint-stepper/preprint-stepper.state.ts +++ b/src/app/features/preprints/store/preprint-stepper/preprint-stepper.state.ts @@ -12,7 +12,9 @@ import { handleSectionError } from '@osf/shared/helpers/state-error.handler'; import { FileModel } from '@osf/shared/models/files/file.model'; import { FileFolderModel } from '@osf/shared/models/files/file-folder.model'; import { FilesService } from '@osf/shared/services/files.service'; +import { LicensesService } from '@osf/shared/services/licenses.service'; +import { PreprintFileSource } from '../../enums'; import { PreprintFilesService } from '../../services/preprint-files.service'; import { PreprintLicensesService } from '../../services/preprint-licenses.service'; import { PreprintsService } from '../../services/preprints.service'; @@ -24,6 +26,7 @@ import { CreateNewProject, CreateNewVersion, CreatePreprint, + DeletePreprintFile, DisconnectProject, FetchAvailableProjects, FetchLicenses, @@ -33,7 +36,6 @@ import { FetchPreprintProject, FetchProjectFilesByLink, ResetPreprintStepperState, - ReuploadFile, SaveLicense, SetInstitutionsChanged, SetPreprintStepperCurrentFolder, @@ -55,7 +57,8 @@ export class PreprintStepperState { private preprintsService = inject(PreprintsService); private preprintFilesService = inject(PreprintFilesService); private fileService = inject(FilesService); - private licensesService = inject(PreprintLicensesService); + private preprintLicensesService = inject(PreprintLicensesService); + private licensesService = inject(LicensesService); private preprintProjectsService = inject(PreprintsProjectsService); @Action(CreatePreprint) @@ -108,7 +111,8 @@ export class PreprintStepperState { return this.preprintFilesService.getPreprintFilesLinks(state.preprint.data.id).pipe( tap((preprintStorage) => { ctx.setState(patch({ preprintFilesLinks: patch({ isLoading: false, data: preprintStorage }) })); - }) + }), + catchError((error) => handleSectionError(ctx, 'preprintFilesLinks', error)) ); } @@ -128,7 +132,8 @@ export class PreprintStepperState { const createdFileId = file.id.split('/')[1]; return ctx.dispatch(new UpdatePrimaryFileRelationship(createdFileId)); - }) + }), + catchError((error) => handleSectionError(ctx, 'preprintFile', error)) ); } @@ -155,20 +160,31 @@ export class PreprintStepperState { ); } - @Action(ReuploadFile) - reuploadFile(ctx: StateContext, action: ReuploadFile) { - const state = ctx.getState(); - const uploadedFile = state.preprintFile.data; - if (!uploadedFile) return EMPTY; - + @Action(DeletePreprintFile) + deletePreprintFile(ctx: StateContext, action: DeletePreprintFile) { ctx.setState(patch({ preprintFile: patch({ isLoading: true }) })); - return this.fileService.updateFileContent(action.file, uploadedFile.links.upload).pipe( - switchMap(() => - uploadedFile.name !== action.file.name - ? this.fileService.renameEntry(uploadedFile.links.upload, action.file.name, 'replace') - : of(null) - ), + return this.fileService.deleteEntry(action.deleteLink).pipe( + tap(() => { + const state = ctx.getState(); + ctx.patchState({ + preprintFile: { + data: null, + isLoading: false, + error: null, + }, + fileSource: PreprintFileSource.None, + preprint: { + ...state.preprint, + data: state.preprint.data + ? { + ...state.preprint.data, + primaryFileId: null, + } + : null, + }, + }); + }), catchError((error) => handleSectionError(ctx, 'preprintFile', error)) ); } @@ -285,7 +301,7 @@ export class PreprintStepperState { copyFileFromProject(ctx: StateContext, action: CopyFileFromProject) { const createdPreprintId = ctx.getState().preprint.data?.id; if (!createdPreprintId) { - return; + return EMPTY; } ctx.setState(patch({ preprintFile: patch({ isLoading: true }) })); @@ -316,9 +332,13 @@ export class PreprintStepperState { @Action(FetchLicenses) fetchLicenses(ctx: StateContext, action: FetchLicenses) { + if (!action.licensesUrl) { + return EMPTY; + } + ctx.setState(patch({ licenses: patch({ isLoading: true }) })); - return this.licensesService.getLicenses(action.providerId).pipe( + return this.licensesService.getLicenses(action.licensesUrl).pipe( tap((licenses) => { ctx.setState(patch({ licenses: patch({ isLoading: false, data: licenses }) })); }), @@ -331,12 +351,14 @@ export class PreprintStepperState { const createdPreprintId = ctx.getState().preprint.data!.id; ctx.setState(patch({ preprint: patch({ isSubmitting: true }) })); - return this.licensesService.updatePreprintLicense(createdPreprintId, action.licenseId, action.licenseOptions).pipe( - tap((preprint) => { - ctx.setState(patch({ preprint: patch({ isSubmitting: false, data: preprint }) })); - }), - catchError((error) => handleSectionError(ctx, 'preprint', error)) - ); + return this.preprintLicensesService + .updatePreprintLicense(createdPreprintId, action.licenseId, action.licenseOptions) + .pipe( + tap((preprint) => { + ctx.setState(patch({ preprint: patch({ isSubmitting: false, data: preprint }) })); + }), + catchError((error) => handleSectionError(ctx, 'preprint', error)) + ); } @Action(DisconnectProject) @@ -449,7 +471,11 @@ export class PreprintStepperState { @Action(SubmitPreprint) submitPreprint(ctx: StateContext) { - const createdPreprintId = ctx.getState().preprint.data!.id; + const createdPreprintId = ctx.getState().preprint.data?.id; + if (!createdPreprintId) { + return EMPTY; + } + ctx.setState(patch({ preprint: patch({ isSubmitting: true }) })); return this.preprintsService.submitPreprint(createdPreprintId).pipe( diff --git a/src/app/features/project/overview/components/link-resource-dialog/link-resource-dialog.component.ts b/src/app/features/project/overview/components/link-resource-dialog/link-resource-dialog.component.ts index 4760056f0..4bba750dd 100644 --- a/src/app/features/project/overview/components/link-resource-dialog/link-resource-dialog.component.ts +++ b/src/app/features/project/overview/components/link-resource-dialog/link-resource-dialog.component.ts @@ -197,9 +197,9 @@ export class LinkResourceDialogComponent { if (!currentResourceId) return; if (resourceType === ResourceType.Project) { - this.actions.getProjects(this.currentPage(), this.tableRows, searchFilters, searchMode, undefined); + this.actions.getProjects(this.currentPage(), this.tableRows, searchFilters, searchMode); } else if (resourceType === ResourceType.Registration) { - this.actions.getRegistrations(this.currentPage(), this.tableRows, searchFilters, searchMode, undefined); + this.actions.getRegistrations(this.currentPage(), this.tableRows, searchFilters, searchMode); } }); } diff --git a/src/app/features/project/overview/components/project-overview-metadata/project-overview-metadata.component.spec.ts b/src/app/features/project/overview/components/project-overview-metadata/project-overview-metadata.component.spec.ts index a8931935f..cfb545f1b 100644 --- a/src/app/features/project/overview/components/project-overview-metadata/project-overview-metadata.component.spec.ts +++ b/src/app/features/project/overview/components/project-overview-metadata/project-overview-metadata.component.spec.ts @@ -30,18 +30,23 @@ import { GetBibliographicContributors, LoadMoreBibliographicContributors, } from '@osf/shared/stores/contributors'; +import { FetchLicense, LicensesSelectors } from '@osf/shared/stores/licenses'; import { FetchSelectedSubjects, SubjectsSelectors } from '@osf/shared/stores/subjects'; import { MOCK_PROJECT_OVERVIEW } from '@testing/mocks/project-overview.mock'; import { provideOSFCore } from '@testing/osf.testing.provider'; import { ActivatedRouteMockBuilder } from '@testing/providers/route-provider.mock'; import { RouterMockBuilder, RouterMockType } from '@testing/providers/router-provider.mock'; -import { mergeSignalOverrides, provideMockStore } from '@testing/providers/store-provider.mock'; +import { + BaseSetupOverrides, + mergeSignalOverrides, + provideMockStore, + SignalOverride, +} from '@testing/providers/store-provider.mock'; import { GetProjectIdentifiers, GetProjectInstitutions, - GetProjectLicense, GetProjectPreprints, ProjectOverviewSelectors, SetProjectCustomCitation, @@ -51,6 +56,8 @@ import { OverviewSupplementsComponent } from '../overview-supplements/overview-s import { ProjectOverviewMetadataComponent } from './project-overview-metadata.component'; +const MOCK_PROJECT_WITH_LICENSE = { ...MOCK_PROJECT_OVERVIEW, licenseId: 'license-1' }; + describe('ProjectOverviewMetadataComponent', () => { let component: ProjectOverviewMetadataComponent; let fixture: ComponentFixture; @@ -59,17 +66,16 @@ describe('ProjectOverviewMetadataComponent', () => { let mockRouter: RouterMockType; let metadataRecordsService: { downloadMetadata: Mock }; - interface SetupOverrides { + interface SetupOverrides extends BaseSetupOverrides { project?: typeof MOCK_PROJECT_OVERVIEW | null; - selectorOverrides?: { selector: any; value: any }[]; } function setup(overrides: SetupOverrides = {}) { - const project = 'project' in overrides ? overrides.project : MOCK_PROJECT_OVERVIEW; + const project = 'project' in overrides ? overrides.project : MOCK_PROJECT_WITH_LICENSE; mockRouter = RouterMockBuilder.create().withUrl('/project/project-1/overview').build(); metadataRecordsService = { downloadMetadata: vi.fn() }; - const defaultSignals = [ + const defaultSignals: SignalOverride[] = [ { selector: ProjectOverviewSelectors.getProject, value: project }, { selector: ProjectOverviewSelectors.isProjectAnonymous, value: false }, { selector: ProjectOverviewSelectors.hasWriteAccess, value: true }, @@ -77,8 +83,8 @@ describe('ProjectOverviewMetadataComponent', () => { { selector: ProjectOverviewSelectors.isInstitutionsLoading, value: false }, { selector: ProjectOverviewSelectors.getIdentifiers, value: [] }, { selector: ProjectOverviewSelectors.isIdentifiersLoading, value: false }, - { selector: ProjectOverviewSelectors.getLicense, value: null }, - { selector: ProjectOverviewSelectors.isLicenseLoading, value: false }, + { selector: LicensesSelectors.getLicense, value: null }, + { selector: LicensesSelectors.isLicenseLoading, value: false }, { selector: ProjectOverviewSelectors.getPreprints, value: [] }, { selector: ProjectOverviewSelectors.isPreprintsLoading, value: false }, { selector: SubjectsSelectors.getSelectedSubjects, value: [] }, @@ -95,7 +101,7 @@ describe('ProjectOverviewMetadataComponent', () => { { selector: MetadataSelectors.getCustomItemMetadata, value: null }, { selector: MetadataSelectors.isCustomItemMetadataLoading, value: false }, ]; - const signals = mergeSignalOverrides(defaultSignals, overrides.selectorOverrides || []); + const signals = mergeSignalOverrides(defaultSignals, overrides.selectorOverrides); TestBed.configureTestingModule({ imports: [ @@ -143,11 +149,11 @@ describe('ProjectOverviewMetadataComponent', () => { expect(dispatchMock).toHaveBeenCalledWith(new GetBibliographicContributors('project-1', ResourceType.Project)); expect(dispatchMock).toHaveBeenCalledWith(new GetProjectInstitutions('project-1')); expect(dispatchMock).toHaveBeenCalledWith(new GetProjectIdentifiers('project-1')); - expect(dispatchMock).toHaveBeenCalledWith(new GetProjectPreprints('project-1')); + expect(dispatchMock).toHaveBeenCalledWith(new GetProjectPreprints(MOCK_PROJECT_OVERVIEW.preprintsUrl)); expect(dispatchMock).toHaveBeenCalledWith(new FetchSelectedSubjects('project-1', ResourceType.Project)); expect(dispatchMock).toHaveBeenCalledWith(new GetProjectSubmissions('project-1')); expect(dispatchMock).toHaveBeenCalledWith(new GetCustomItemMetadata('project-1')); - expect(dispatchMock).toHaveBeenCalledWith(new GetProjectLicense(MOCK_PROJECT_OVERVIEW.licenseId)); + expect(dispatchMock).toHaveBeenCalledWith(new FetchLicense('license-1')); expect(dispatchMock).toHaveBeenCalledWith(new GetCedarMetadataRecords('project-1', ResourceType.Project)); expect(dispatchMock).toHaveBeenCalledWith(new GetCedarMetadataTemplates()); }); diff --git a/src/app/features/project/overview/components/project-overview-metadata/project-overview-metadata.component.ts b/src/app/features/project/overview/components/project-overview-metadata/project-overview-metadata.component.ts index 4ab4f60a5..280d92295 100644 --- a/src/app/features/project/overview/components/project-overview-metadata/project-overview-metadata.component.ts +++ b/src/app/features/project/overview/components/project-overview-metadata/project-overview-metadata.component.ts @@ -35,12 +35,12 @@ import { GetBibliographicContributors, LoadMoreBibliographicContributors, } from '@osf/shared/stores/contributors'; +import { FetchLicense, LicensesSelectors } from '@osf/shared/stores/licenses'; import { FetchSelectedSubjects, SubjectsSelectors } from '@osf/shared/stores/subjects'; import { GetProjectIdentifiers, GetProjectInstitutions, - GetProjectLicense, GetProjectPreprints, ProjectOverviewSelectors, SetProjectCustomCitation, @@ -87,8 +87,8 @@ export class ProjectOverviewMetadataComponent { readonly isInstitutionsLoading = select(ProjectOverviewSelectors.isInstitutionsLoading); readonly identifiers = select(ProjectOverviewSelectors.getIdentifiers); readonly isIdentifiersLoading = select(ProjectOverviewSelectors.isIdentifiersLoading); - readonly license = select(ProjectOverviewSelectors.getLicense); - readonly isLicenseLoading = select(ProjectOverviewSelectors.isLicenseLoading); + readonly license = select(LicensesSelectors.getLicense); + readonly isLicenseLoading = select(LicensesSelectors.isLicenseLoading); readonly preprints = select(ProjectOverviewSelectors.getPreprints); readonly isPreprintsLoading = select(ProjectOverviewSelectors.isPreprintsLoading); readonly subjects = select(SubjectsSelectors.getSelectedSubjects); @@ -112,7 +112,7 @@ export class ProjectOverviewMetadataComponent { private readonly actions = createDispatchMap({ getInstitutions: GetProjectInstitutions, getIdentifiers: GetProjectIdentifiers, - getLicense: GetProjectLicense, + getLicense: FetchLicense, getPreprints: GetProjectPreprints, setCustomCitation: SetProjectCustomCitation, getSubjects: FetchSelectedSubjects, @@ -132,7 +132,7 @@ export class ProjectOverviewMetadataComponent { this.actions.getBibliographicContributors(project.id, ResourceType.Project); this.actions.getInstitutions(project.id); this.actions.getIdentifiers(project.id); - this.actions.getPreprints(project.id); + this.actions.getPreprints(project.preprintsUrl); this.actions.getSubjects(project.id, ResourceType.Project); this.actions.getProjectSubmissions(project.id); this.actions.getLicense(project.licenseId); diff --git a/src/app/features/project/overview/mappers/project-overview.mapper.ts b/src/app/features/project/overview/mappers/project-overview.mapper.ts index 186b39b44..67d7b0614 100644 --- a/src/app/features/project/overview/mappers/project-overview.mapper.ts +++ b/src/app/features/project/overview/mappers/project-overview.mapper.ts @@ -19,6 +19,7 @@ export class ProjectOverviewMapper { ? (relationships?.view_only_links?.links?.related?.meta['count'] as number) : 0, licenseId: relationships?.license?.data?.id, + preprintsUrl: relationships?.preprints?.links?.related?.href ?? null, }; } } diff --git a/src/app/features/project/overview/models/project-overview.model.ts b/src/app/features/project/overview/models/project-overview.model.ts index f1bd65c38..7c1d95c06 100644 --- a/src/app/features/project/overview/models/project-overview.model.ts +++ b/src/app/features/project/overview/models/project-overview.model.ts @@ -7,5 +7,6 @@ export interface ProjectOverviewModel extends BaseNodeModel { parentId?: string; rootParentId?: string; licenseId?: string; + preprintsUrl?: string | null; contributors?: ContributorModel[]; } diff --git a/src/app/features/project/overview/services/project-overview.service.spec.ts b/src/app/features/project/overview/services/project-overview.service.spec.ts index 314248cf7..7c969910a 100644 --- a/src/app/features/project/overview/services/project-overview.service.spec.ts +++ b/src/app/features/project/overview/services/project-overview.service.spec.ts @@ -9,21 +9,18 @@ import { BYPASS_ERROR_INTERCEPTOR } from '@core/interceptors/error-interceptor.t import { JSON_API_BULK_HEADERS } from '@osf/shared/constants/json-api-headers.const'; import { IdentifiersMapper } from '@osf/shared/mappers/identifiers.mapper'; import { InstitutionsMapper } from '@osf/shared/mappers/institutions'; -import { LicensesMapper } from '@osf/shared/mappers/licenses.mapper'; import { BaseNodeMapper } from '@osf/shared/mappers/nodes'; import { NodePreprintMapper } from '@osf/shared/mappers/nodes/node-preprint.mapper'; import { NodeStorageMapper } from '@osf/shared/mappers/nodes/node-storage.mapper'; import { IdentifiersResponseJsonApi } from '@osf/shared/models/identifiers/identifier-json-api.model'; import { InstitutionsJsonApiResponse } from '@osf/shared/models/institutions/institution-json-api.model'; import { Institution } from '@osf/shared/models/institutions/institutions.model'; -import { LicenseResponseJsonApi } from '@osf/shared/models/license/licenses-json-api.model'; import { BaseNodeDataJsonApi } from '@osf/shared/models/nodes/base-node-data-json-api.model'; import { NodePreprintsResponseJsonApi } from '@osf/shared/models/nodes/node-preprint-json-api.model'; import { NodeStorageModel } from '@osf/shared/models/nodes/node-storage.model'; import { NodeResponseJsonApi, NodesResponseJsonApi } from '@osf/shared/models/nodes/nodes-json-api.model'; import { PaginatedData } from '@osf/shared/models/paginated-data.model'; import { JsonApiService } from '@osf/shared/services/json-api.service'; -import { LicenseModel } from '@shared/models/license/license.model'; import { MOCK_NODE_WITH_ADMIN } from '@testing/mocks/node.mock'; import { MOCK_NODE_PREPRINTS } from '@testing/mocks/node-preprint.mock'; @@ -121,21 +118,6 @@ describe('ProjectOverviewService', () => { expect(response).toEqual([MOCK_PROJECT_IDENTIFIERS]); }); - it('getProjectLicense should request license and map response', async () => { - setup(); - const licenseId = 'license-1'; - const mappedLicense = { id: licenseId, name: 'MIT' } as LicenseModel; - const apiResponse = { data: { id: licenseId } } as LicenseResponseJsonApi; - const mapperSpy = vi.spyOn(LicensesMapper, 'fromLicenseDataJsonApi').mockReturnValue(mappedLicense); - jsonApiService.get.mockReturnValue(of(apiResponse)); - - const response = await firstValueFrom(service.getProjectLicense(licenseId)); - - expect(jsonApiService.get).toHaveBeenCalledWith(`${MOCK_API_URL}/licenses/${licenseId}/`); - expect(mapperSpy).toHaveBeenCalledWith(apiResponse.data); - expect(response).toEqual(mappedLicense); - }); - it('getProjectStorage should request storage and map response', async () => { setup(); const mappedStorage = { storageLimitStatus: 'DEFAULT', storageUsage: '1' } as NodeStorageModel; @@ -152,13 +134,14 @@ describe('ProjectOverviewService', () => { it('getProjectPreprints should request preprints and map response', async () => { setup(); + const preprintsUrl = `${MOCK_API_URL}/nodes/${projectId}/preprints/`; const apiResponse = { data: [] } as unknown as NodePreprintsResponseJsonApi; const mapperSpy = vi.spyOn(NodePreprintMapper, 'getNodePreprints').mockReturnValue(MOCK_NODE_PREPRINTS); jsonApiService.get.mockReturnValue(of(apiResponse)); - const response = await firstValueFrom(service.getProjectPreprints(projectId)); + const response = await firstValueFrom(service.getProjectPreprints(preprintsUrl)); - expect(jsonApiService.get).toHaveBeenCalledWith(`${MOCK_API_URL}/nodes/${projectId}/preprints/`); + expect(jsonApiService.get).toHaveBeenCalledWith(preprintsUrl); expect(mapperSpy).toHaveBeenCalledWith(apiResponse.data); expect(response).toEqual(MOCK_NODE_PREPRINTS); }); diff --git a/src/app/features/project/overview/services/project-overview.service.ts b/src/app/features/project/overview/services/project-overview.service.ts index 9b93a910c..135b1af6b 100644 --- a/src/app/features/project/overview/services/project-overview.service.ts +++ b/src/app/features/project/overview/services/project-overview.service.ts @@ -7,14 +7,12 @@ import { ENVIRONMENT } from '@core/provider/environment.provider'; import { JSON_API_BULK_HEADERS } from '@osf/shared/constants/json-api-headers.const'; import { IdentifiersMapper } from '@osf/shared/mappers/identifiers.mapper'; import { InstitutionsMapper } from '@osf/shared/mappers/institutions'; -import { LicensesMapper } from '@osf/shared/mappers/licenses.mapper'; import { BaseNodeMapper } from '@osf/shared/mappers/nodes'; import { NodePreprintMapper } from '@osf/shared/mappers/nodes/node-preprint.mapper'; import { NodeStorageMapper } from '@osf/shared/mappers/nodes/node-storage.mapper'; import { IdentifiersResponseJsonApi } from '@osf/shared/models/identifiers/identifier-json-api.model'; import { InstitutionsJsonApiResponse } from '@osf/shared/models/institutions/institution-json-api.model'; import { Institution } from '@osf/shared/models/institutions/institutions.model'; -import { LicenseResponseJsonApi } from '@osf/shared/models/license/licenses-json-api.model'; import { BaseNodeModel, NodeModel } from '@osf/shared/models/nodes/base-node.model'; import { BaseNodeDataJsonApi } from '@osf/shared/models/nodes/base-node-data-json-api.model'; import { NodePreprintModel } from '@osf/shared/models/nodes/node-preprint.model'; @@ -25,7 +23,6 @@ import { NodeResponseJsonApi, NodesResponseJsonApi } from '@osf/shared/models/no import { PaginatedData } from '@osf/shared/models/paginated-data.model'; import { JsonApiService } from '@osf/shared/services/json-api.service'; import { IdentifierModel } from '@shared/models/identifiers/identifier.model'; -import { LicenseModel } from '@shared/models/license/license.model'; import { ProjectOverviewMapper } from '../mappers'; import { PrivacyStatusModel, ProjectOverviewModel } from '../models'; @@ -68,21 +65,15 @@ export class ProjectOverviewService { .pipe(map((response) => IdentifiersMapper.fromJsonApi(response))); } - getProjectLicense(licenseId: string): Observable { - return this.jsonApiService - .get(`${this.apiUrl}/licenses/${licenseId}/`) - .pipe(map((response) => LicensesMapper.fromLicenseDataJsonApi(response.data))); - } - getProjectStorage(projectId: string): Observable { return this.jsonApiService .get(`${this.apiUrl}/nodes/${projectId}/storage/`) .pipe(map((response) => NodeStorageMapper.getNodeStorage(response.data))); } - getProjectPreprints(projectId: string): Observable { + getProjectPreprints(preprintsUrl: string): Observable { return this.jsonApiService - .get(`${this.apiUrl}/nodes/${projectId}/preprints/`) + .get(preprintsUrl) .pipe(map((response) => NodePreprintMapper.getNodePreprints(response.data))); } diff --git a/src/app/features/project/overview/store/project-overview.actions.ts b/src/app/features/project/overview/store/project-overview.actions.ts index 16c79931a..928a86a9d 100644 --- a/src/app/features/project/overview/store/project-overview.actions.ts +++ b/src/app/features/project/overview/store/project-overview.actions.ts @@ -20,12 +20,6 @@ export class GetProjectIdentifiers { constructor(public projectId: string) {} } -export class GetProjectLicense { - static readonly type = '[Project Overview] Get Project License'; - - constructor(public licenseId: string | undefined) {} -} - export class GetProjectStorage { static readonly type = '[Project Overview] Get Project Storage'; @@ -35,7 +29,7 @@ export class GetProjectStorage { export class GetProjectPreprints { static readonly type = '[Project Overview] Get Project Preprints'; - constructor(public projectId: string) {} + constructor(public preprintsUrl: string | null | undefined) {} } export class UpdateProjectPublicStatus { diff --git a/src/app/features/project/overview/store/project-overview.model.ts b/src/app/features/project/overview/store/project-overview.model.ts index 51abff1ba..a14fe826e 100644 --- a/src/app/features/project/overview/store/project-overview.model.ts +++ b/src/app/features/project/overview/store/project-overview.model.ts @@ -5,7 +5,6 @@ import { NodeStorageModel } from '@osf/shared/models/nodes/node-storage.model'; import { AsyncStateModel } from '@osf/shared/models/store/async-state.model'; import { AsyncStateWithTotalCount } from '@osf/shared/models/store/async-state-with-total-count.model'; import { IdentifierModel } from '@shared/models/identifiers/identifier.model'; -import { LicenseModel } from '@shared/models/license/license.model'; import { ProjectOverviewModel } from '../models'; @@ -18,7 +17,6 @@ export interface ProjectOverviewStateModel { parentProject: AsyncStateModel; institutions: AsyncStateModel; identifiers: AsyncStateModel; - license: AsyncStateModel; storage: AsyncStateModel; preprints: AsyncStateModel; isAnonymous: boolean; @@ -56,11 +54,6 @@ export const PROJECT_OVERVIEW_DEFAULTS: ProjectOverviewStateModel = { isLoading: false, error: null, }, - license: { - data: null, - isLoading: false, - error: null, - }, storage: { data: null, isLoading: false, diff --git a/src/app/features/project/overview/store/project-overview.selectors.ts b/src/app/features/project/overview/store/project-overview.selectors.ts index b45a6c7f8..82d4d5cfb 100644 --- a/src/app/features/project/overview/store/project-overview.selectors.ts +++ b/src/app/features/project/overview/store/project-overview.selectors.ts @@ -106,16 +106,6 @@ export class ProjectOverviewSelectors { return state.identifiers.isLoading; } - @Selector([ProjectOverviewState]) - static getLicense(state: ProjectOverviewStateModel) { - return state.license.data; - } - - @Selector([ProjectOverviewState]) - static isLicenseLoading(state: ProjectOverviewStateModel) { - return state.license.isLoading; - } - @Selector([ProjectOverviewState]) static getStorage(state: ProjectOverviewStateModel) { return state.storage.data; diff --git a/src/app/features/project/overview/store/project-overview.state.ts b/src/app/features/project/overview/store/project-overview.state.ts index 8cd50508f..f1bb96385 100644 --- a/src/app/features/project/overview/store/project-overview.state.ts +++ b/src/app/features/project/overview/store/project-overview.state.ts @@ -21,7 +21,6 @@ import { GetProjectById, GetProjectIdentifiers, GetProjectInstitutions, - GetProjectLicense, GetProjectPreprints, GetProjectStorage, LoadMoreComponents, @@ -128,39 +127,6 @@ export class ProjectOverviewState { ); } - @Action(GetProjectLicense) - getProjectLicense(ctx: StateContext, action: GetProjectLicense) { - if (!action.licenseId) { - return; - } - - const state = ctx.getState(); - - if (state.license.isLoading) { - return; - } - - ctx.patchState({ - license: { - ...state.license, - isLoading: true, - }, - }); - - return this.projectOverviewService.getProjectLicense(action.licenseId).pipe( - tap((license) => { - ctx.patchState({ - license: { - data: license, - isLoading: false, - error: null, - }, - }); - }), - catchError((error) => handleSectionError(ctx, 'license', error)) - ); - } - @Action(GetProjectStorage) getProjectStorage(ctx: StateContext, action: GetProjectStorage) { const state = ctx.getState(); @@ -187,6 +153,10 @@ export class ProjectOverviewState { @Action(GetProjectPreprints) getProjectPreprints(ctx: StateContext, action: GetProjectPreprints) { + if (!action.preprintsUrl) { + return; + } + const state = ctx.getState(); ctx.patchState({ preprints: { @@ -195,7 +165,7 @@ export class ProjectOverviewState { }, }); - return this.projectOverviewService.getProjectPreprints(action.projectId).pipe( + return this.projectOverviewService.getProjectPreprints(action.preprintsUrl).pipe( tap((preprints) => { ctx.patchState({ preprints: { diff --git a/src/app/features/project/project.component.spec.ts b/src/app/features/project/project.component.spec.ts index 9cf3e1986..eec1bdbc4 100644 --- a/src/app/features/project/project.component.spec.ts +++ b/src/app/features/project/project.component.spec.ts @@ -18,6 +18,7 @@ import { MetaTagsService } from '@osf/shared/services/meta-tags.service'; import { MetaTagsBuilderService } from '@osf/shared/services/meta-tags-builder.service'; import { ContributorsSelectors } from '@osf/shared/stores/contributors'; import { CurrentResourceSelectors } from '@osf/shared/stores/current-resource'; +import { FetchLicense, LicensesSelectors } from '@osf/shared/stores/licenses'; import { MOCK_PROJECT_OVERVIEW } from '@testing/mocks/project-overview.mock'; import { provideOSFCore } from '@testing/osf.testing.provider'; @@ -36,7 +37,7 @@ import { SignalOverride, } from '@testing/providers/store-provider.mock'; -import { GetProjectById, GetProjectIdentifiers, GetProjectLicense, ProjectOverviewSelectors } from './overview/store'; +import { GetProjectById, GetProjectIdentifiers, ProjectOverviewSelectors } from './overview/store'; import { ProjectComponent } from './project.component'; interface SetupOverrides extends BaseSetupOverrides { @@ -92,8 +93,8 @@ function setup(overrides: SetupOverrides = {}) { { selector: ProjectOverviewSelectors.getProject, value: null }, { selector: ProjectOverviewSelectors.getProjectLoading, value: false }, { selector: ProjectOverviewSelectors.getIdentifiers, value: [] }, - { selector: ProjectOverviewSelectors.getLicense, value: { name: 'MIT' } }, - { selector: ProjectOverviewSelectors.isLicenseLoading, value: false }, + { selector: LicensesSelectors.getLicense, value: { name: 'MIT' } }, + { selector: LicensesSelectors.isLicenseLoading, value: false }, { selector: ContributorsSelectors.getBibliographicContributors, value: [] }, { selector: ContributorsSelectors.isBibliographicContributorsLoading, value: false }, { selector: CurrentResourceSelectors.getCurrentResource, value: null }, @@ -159,7 +160,7 @@ describe('Component: Project', () => { selectorOverrides: [{ selector: ProjectOverviewSelectors.getProject, value: project }], }); - expect(store.dispatch).toHaveBeenCalledWith(new GetProjectLicense('license-1')); + expect(store.dispatch).toHaveBeenCalledWith(new FetchLicense('license-1')); }); it('should call datacite tracking on init', () => { diff --git a/src/app/features/project/project.component.ts b/src/app/features/project/project.component.ts index d1dcfd443..29caaf304 100644 --- a/src/app/features/project/project.component.ts +++ b/src/app/features/project/project.component.ts @@ -27,10 +27,11 @@ import { DataciteService } from '@osf/shared/services/datacite/datacite.service' import { MetaTagsService } from '@osf/shared/services/meta-tags.service'; import { MetaTagsBuilderService } from '@osf/shared/services/meta-tags-builder.service'; import { ContributorsSelectors, GetBibliographicContributors } from '@osf/shared/stores/contributors'; +import { FetchLicense, LicensesSelectors } from '@osf/shared/stores/licenses'; import { AnalyticsService } from '@shared/services/analytics.service'; import { CurrentResourceSelectors } from '@shared/stores/current-resource'; -import { GetProjectById, GetProjectIdentifiers, GetProjectLicense, ProjectOverviewSelectors } from './overview/store'; +import { GetProjectById, GetProjectIdentifiers, ProjectOverviewSelectors } from './overview/store'; @Component({ selector: 'osf-project', @@ -58,8 +59,8 @@ export class ProjectComponent implements OnDestroy { readonly isProjectLoading = select(ProjectOverviewSelectors.getProjectLoading); readonly bibliographicContributors = select(ContributorsSelectors.getBibliographicContributors); readonly isBibliographicContributorsLoading = select(ContributorsSelectors.isBibliographicContributorsLoading); - readonly license = select(ProjectOverviewSelectors.getLicense); - readonly isLicenseLoading = select(ProjectOverviewSelectors.isLicenseLoading); + readonly license = select(LicensesSelectors.getLicense); + readonly isLicenseLoading = select(LicensesSelectors.isLicenseLoading); readonly identifiersForDatacite$ = toObservable(select(ProjectOverviewSelectors.getIdentifiers)).pipe( map((identifiers) => (identifiers?.length ? { identifiers } : null)) @@ -67,7 +68,7 @@ export class ProjectComponent implements OnDestroy { private readonly actions = createDispatchMap({ getProject: GetProjectById, - getLicense: GetProjectLicense, + getLicense: FetchLicense, getIdentifiers: GetProjectIdentifiers, getBibliographicContributors: GetBibliographicContributors, }); @@ -160,7 +161,7 @@ export class ProjectComponent implements OnDestroy { project, canonicalPath: this.canonicalPath(), contributors: this.bibliographicContributors(), - licenseName: this.license.name, + licenseName: this.license()?.name, }); this.metaTags.updateMetaTags(metaTagsData, this.destroyRef); diff --git a/src/app/features/registries/components/custom-step/custom-step.component.html b/src/app/features/registries/components/custom-step/custom-step.component.html index f161452d6..e561d3af7 100644 --- a/src/app/features/registries/components/custom-step/custom-step.component.html +++ b/src/app/features/registries/components/custom-step/custom-step.component.html @@ -1,25 +1,23 @@
- @if (currentPage()) { -
-

{{ currentPage().title }}

+ @let page = currentPage(); - @let helpText = currentPage().helpText; + @if (page) { +
+

{{ page.title }}

- @if (helpText) { - + @if (page.helpText) { + }
- @if (currentPage().description?.length) { -

{{ currentPage().description }}

+ @if (page.description?.length) { +

{{ page.description }}

} - @let questions = currentPage().questions || []; - - + - @if (currentPage().sections?.length) { - @for (section of currentPage().sections; track section.id) { + @if (page.sections?.length) { + @for (section of page.sections; track section.id) {

{{ section.title }}

@@ -39,8 +37,8 @@

{{ section.title }}

@for (q of questions; track q.id) { -
-
+ + + @if ( + stepForm.controls[controlName].errors?.['required'] && + (stepForm.controls[controlName].touched || stepForm.controls[controlName].dirty) + ) { + + {{ INPUT_VALIDATION_MESSAGES.required | translate }} + } }
- - - + + +
diff --git a/src/app/features/registries/components/custom-step/custom-step.component.spec.ts b/src/app/features/registries/components/custom-step/custom-step.component.spec.ts index 409a5d1b3..97f2e05c1 100644 --- a/src/app/features/registries/components/custom-step/custom-step.component.spec.ts +++ b/src/app/features/registries/components/custom-step/custom-step.component.spec.ts @@ -6,16 +6,19 @@ import { Mock } from 'vitest'; import { TestBed } from '@angular/core/testing'; import { FormGroup } from '@angular/forms'; +import { By } from '@angular/platform-browser'; import { ActivatedRoute, Router, UrlTree } from '@angular/router'; import { UserSelectors } from '@osf/core/store/user/user.selectors'; import { InfoIconComponent } from '@osf/shared/components/info-icon/info-icon.component'; +import { FILE_COUNT_ATTACHMENTS_LIMIT } from '@osf/shared/constants/files-limits.const'; import { FieldType } from '@osf/shared/enums/field-type.enum'; +import { FileModel } from '@osf/shared/models/files/file.model'; +import { FilePayloadJsonApi } from '@osf/shared/models/files/file-payload-json-api.model'; +import { PageSchema, Question } from '@osf/shared/models/registration/page-schema.model'; import { ToastService } from '@osf/shared/services/toast.service'; -import { FileModel } from '@shared/models/files/file.model'; -import { FilePayloadJsonApi } from '@shared/models/files/file-payload-json-api.model'; -import { PageSchema } from '@shared/models/registration/page-schema.model'; +import { FileModelMock } from '@testing/mocks/file.model.mock'; import { MOCK_REGISTRIES_PAGE, MOCK_STEPS_DATA } from '@testing/mocks/registries.mock'; import { provideOSFCore } from '@testing/osf.testing.provider'; import { ActivatedRouteMockBuilder } from '@testing/providers/route-provider.mock'; @@ -46,6 +49,13 @@ interface SetupOverrides extends BaseSetupOverrides { } describe('CustomStepComponent', () => { + const filePayload: FilePayloadJsonApi = { + file_id: 'f1', + file_name: 'doc.pdf', + file_urls: { html: '', download: '' }, + file_hashes: { sha256: '' }, + }; + function createPage( questions: PageSchema['questions'] = [], sections: PageSchema['sections'] = undefined @@ -53,8 +63,19 @@ describe('CustomStepComponent', () => { return { id: 'p', title: 'P', questions, sections }; } + function createQuestion(overrides: Partial & { responseKey: string; fieldType: FieldType }): Question { + return { + id: overrides.responseKey, + displayText: '', + required: false, + ...overrides, + }; + } + function setup(overrides: SetupOverrides = {}) { - const routeBuilder = ActivatedRouteMockBuilder.create().withParams(overrides.routeParams ?? { step: 1 }); + const routeBuilder = ActivatedRouteMockBuilder.create().withParams( + overrides.routeParams ?? { step: '1', id: 'draft-1' } + ); if (overrides.hasParent === false) { routeBuilder.withNoParent(); } @@ -94,59 +115,44 @@ describe('CustomStepComponent', () => { return { component, fixture, store, routeBuilder, mockRouter, toastMock }; } - it('should create', () => { - const { component } = setup(); - expect(component).toBeTruthy(); - }); - - it('should emit back on first step', () => { - const { component } = setup(); + it('should emit back on first step and navigate to the previous step later', () => { + const { component, mockRouter } = setup(); const backSpy = vi.spyOn(component.back, 'emit'); + component.goBack(); expect(backSpy).toHaveBeenCalled(); - }); - it('should navigate to previous step on step > 1', () => { - const { component, mockRouter } = setup(); component.step.set(2); component.goBack(); expect(mockRouter.navigate).toHaveBeenCalledWith(['../', 1], { relativeTo: expect.anything() }); }); - it('should navigate to next step within pages', () => { + it('should navigate to the next step or emit next on the last step', () => { const { component, mockRouter } = setup({ pages: [MOCK_REGISTRIES_PAGE, MOCK_REGISTRIES_PAGE] }); + const nextSpy = vi.spyOn(component.next, 'emit'); + component.goNext(); expect(mockRouter.navigate).toHaveBeenCalledWith(['../', 2], { relativeTo: expect.anything() }); - }); - it('should emit next on last step', () => { - const { component } = setup(); - const nextSpy = vi.spyOn(component.next, 'emit'); - component.step.set(1); + component.step.set(2); component.goNext(); expect(nextSpy).toHaveBeenCalled(); }); - it('should dispatch updateStepState on ngOnDestroy', () => { - const { component, store } = setup(); - (store.dispatch as Mock).mockClear(); - component.ngOnDestroy(); - expect(store.dispatch).toHaveBeenCalledWith(expect.any(UpdateStepState)); - }); - - it('should emit updateAction and dispatch setUpdatedFields when fields changed', () => { + it('should emit updateAction and SetUpdatedFields when fields changed on destroy', () => { const { component, store } = setup(); const emitSpy = vi.spyOn(component.updateAction, 'emit'); - component['stepForm'].get('field1')?.setValue('changed'); + component.stepForm.get('field1')?.setValue('changed'); (store.dispatch as Mock).mockClear(); component.ngOnDestroy(); - expect(emitSpy).toHaveBeenCalled(); + expect(emitSpy).toHaveBeenCalledWith(expect.objectContaining({ field1: 'changed' })); expect(store.dispatch).toHaveBeenCalledWith(new SetUpdatedFields({ field1: 'changed' })); + expect(store.dispatch).toHaveBeenCalledWith(new UpdateStepState('1', false, true)); }); - it('should not emit updateAction when no fields changed', () => { + it('should dispatch step state without updateAction when nothing changed', () => { const { component, store } = setup(); const emitSpy = vi.spyOn(component.updateAction, 'emit'); (store.dispatch as Mock).mockClear(); @@ -155,9 +161,10 @@ describe('CustomStepComponent', () => { expect(emitSpy).not.toHaveBeenCalled(); expect(store.dispatch).not.toHaveBeenCalledWith(expect.any(SetUpdatedFields)); + expect(store.dispatch).toHaveBeenCalledWith(new UpdateStepState('1', false, true)); }); - it('should skip saveStepState when form has no controls', () => { + it('should skip save when the form has no controls', () => { const { component, store } = setup(); component.stepForm = new FormGroup({}); (store.dispatch as Mock).mockClear(); @@ -167,198 +174,294 @@ describe('CustomStepComponent', () => { expect(store.dispatch).not.toHaveBeenCalled(); }); - it('should update file upload description based on isProjectCreationDisabled', () => { + it('should not treat attached file display names as field changes', () => { const { component } = setup({ - selectorOverrides: [{ selector: UserSelectors.isProjectCreationDisabled, value: true }], + pages: [createPage([createQuestion({ responseKey: 'files', fieldType: FieldType.File })])], + stepsData: { files: [filePayload] }, }); - expect(component.fileUploadDescription()).toBe('shared.files.descriptionNoProject'); + const emitSpy = vi.spyOn(component.updateAction, 'emit'); - const { component: component2 } = setup({ - selectorOverrides: [{ selector: UserSelectors.isProjectCreationDisabled, value: false }], - }); - expect(component2.fileUploadDescription()).toBe('shared.files.description'); + component.ngOnDestroy(); + + expect(component.attachedFiles['files'][0].name).toBe('doc.pdf'); + expect(emitSpy).not.toHaveBeenCalled(); }); - it('should attach file and emit updateAction', () => { - const { component } = setup(); - const emitSpy = vi.spyOn(component.updateAction, 'emit'); - const mockFile = { - id: 'new-file', - name: 'new.txt', - links: { html: 'http://html', download: 'http://dl' }, - extra: { hashes: { sha256: 'abc' } }, - } as FileModel; + it('should save state and update step and draftId on route param change', () => { + const { component, store, routeBuilder } = setup({ routeParams: { step: '1', id: 'draft-1' } }); + (store.dispatch as Mock).mockClear(); - component.onAttachFile(mockFile, 'field1'); + routeBuilder.withParams({ step: '2', id: 'draft-2' }); - expect(component.attachedFiles['field1'].length).toBe(1); - expect(emitSpy).toHaveBeenCalled(); - expect(emitSpy.mock.calls[0][0]['field1'][0].file_id).toBe('new-file'); + expect(store.dispatch).toHaveBeenCalledWith(expect.any(UpdateStepState)); + expect(component.step()).toBe(2); + expect(component.draftId()).toBe('draft-2'); }); - it('should not attach duplicate file', () => { - const { component } = setup(); - component.attachedFiles['field1'] = [{ file_id: 'file-1', name: 'existing.txt' }]; - const emitSpy = vi.spyOn(component.updateAction, 'emit'); + it('should initialize page and section controls and skip unknown types', () => { + const { component } = setup({ + pages: [ + createPage( + [ + createQuestion({ responseKey: 'cbField', fieldType: FieldType.Checkbox, required: true }), + createQuestion({ responseKey: 'radioField', fieldType: FieldType.Radio, required: true }), + createQuestion({ responseKey: 'fileField', fieldType: FieldType.File }), + createQuestion({ responseKey: 'unknownField', fieldType: 'unknown' as FieldType }), + ], + [ + { + id: 's1', + title: 'S', + questions: [createQuestion({ responseKey: 'secField', fieldType: FieldType.Text })], + }, + ] + ), + ], + stepsData: { fileField: [filePayload], secField: 'val' }, + }); - component.onAttachFile({ id: 'file-1' } as FileModel, 'field1'); + expect(component.stepForm.get('cbField')?.value).toEqual([]); + expect(component.stepForm.get('radioField')?.valid).toBe(false); + expect(component.attachedFiles['fileField'][0].name).toBe('doc.pdf'); + expect(component.stepForm.get('unknownField')).toBeNull(); + expect(component.stepForm.get('secField')?.value).toBe('val'); + }); - expect(component.attachedFiles['field1'].length).toBe(1); - expect(emitSpy).not.toHaveBeenCalled(); + it('should mark the form touched when the current step is invalid', () => { + const { component } = setup({ + stepsState: { 1: { invalid: true, touched: true } }, + }); + expect(component.stepForm.get('field1')?.touched).toBe(true); }); - it('should show warning when attachment limit reached', () => { - const { component, toastMock } = setup(); - component.attachedFiles['field1'] = Array.from({ length: 5 }, (_, i) => ({ file_id: `f-${i}`, name: `f-${i}` })); + it('should reset attachedFiles when navigating to another page', async () => { + const { component, fixture, routeBuilder } = setup({ + pages: [ + createPage([createQuestion({ responseKey: 'files', fieldType: FieldType.File })]), + createPage([createQuestion({ responseKey: 'title', fieldType: FieldType.Text })]), + ], + stepsData: { files: [filePayload], title: '' }, + routeParams: { step: '1', id: 'draft-1' }, + }); + + expect(component.attachedFiles['files']?.length).toBe(1); + + routeBuilder.withParams({ step: '2', id: 'draft-1' }); + await fixture.whenStable(); + + expect(component.attachedFiles['files']).toBeUndefined(); + expect(component.stepForm.get('title')).toBeDefined(); + }); + + it('should use the no-project file upload description when project creation is disabled', () => { + const { component } = setup({ + selectorOverrides: [{ selector: UserSelectors.isProjectCreationDisabled, value: true }], + }); + expect(component.fileUploadDescription()).toBe('shared.files.descriptionNoProject'); + }); - const mockFile = { - id: 'new', + it('should attach a file and emit a mapped form payload', () => { + const { component } = setup({ + pages: [ + createPage([ + createQuestion({ responseKey: 'title', fieldType: FieldType.Text }), + createQuestion({ responseKey: 'files', fieldType: FieldType.File }), + ]), + ], + stepsData: { title: 'a', files: [] }, + }); + const emitSpy = vi.spyOn(component.updateAction, 'emit'); + const mockFile = FileModelMock.simple({ + id: 'new-file', name: 'new.txt', - links: { html: '', download: '' }, - extra: { hashes: { sha256: '', md5: '' } }, - } as FileModel; - component.onAttachFile(mockFile, 'field1'); + links: { ...FileModelMock.simple().links, html: 'http://html', download: 'http://dl' }, + extra: { hashes: { sha256: 'abc', md5: '' }, downloads: 0 }, + }); - expect(toastMock.showWarn).toHaveBeenCalledWith('shared.files.limitText'); - expect(component.attachedFiles['field1'].length).toBe(5); + component.onAttachFile(mockFile, 'files'); + + expect(component.attachedFiles['files'].length).toBe(1); + expect(emitSpy).toHaveBeenCalledWith({ + title: 'a', + files: [ + { + file_id: 'new-file', + file_name: 'new.txt', + file_urls: { html: 'http://html', download: 'http://dl' }, + file_hashes: { sha256: 'abc' }, + }, + ], + }); }); - it('should remove file and emit updateAction', () => { - const { component } = setup(); + it('should not attach a duplicate file', () => { + const { component } = setup({ + pages: [createPage([createQuestion({ responseKey: 'files', fieldType: FieldType.File })])], + stepsData: { files: [] }, + }); + component.attachedFiles['files'] = [{ ...filePayload, file_id: 'file-1', name: 'existing.txt' }]; const emitSpy = vi.spyOn(component.updateAction, 'emit'); - component.attachedFiles['field1'] = [ - { file_id: 'f1', name: 'a' }, - { file_id: 'f2', name: 'b' }, - ]; - component.removeFromAttachedFiles('f1', 'field1'); + component.onAttachFile(FileModelMock.simple({ id: 'file-1' }), 'files'); - expect(component.attachedFiles['field1'].length).toBe(1); - expect(component.attachedFiles['field1'][0].file_id).toBe('f2'); - expect(emitSpy).toHaveBeenCalled(); + expect(component.attachedFiles['files'].length).toBe(1); + expect(emitSpy).not.toHaveBeenCalled(); }); - it('should open file preview in new tab when draftId and file guid exist', () => { - const urlTree = {} as UrlTree; - const { component, mockRouter } = setup({ - routeParams: { step: '1', id: 'draft-1' }, - urlTree, - serializedUrl: '/draft-1/files/file-guid/preview', + it('should not attach the same file twice before the draft is saved', () => { + const { component } = setup({ + pages: [createPage([createQuestion({ responseKey: 'files', fieldType: FieldType.File })])], + stepsData: { files: [] }, }); - const openSpy = vi.spyOn(window, 'open').mockImplementation(() => null); + const mockFile = FileModelMock.simple({ id: 'new-file', name: 'new.txt' }); - component.onOpenFile({ guid: 'file-guid' } as FileModel); + component.onAttachFile(mockFile, 'files'); + component.onAttachFile(mockFile, 'files'); - expect(mockRouter.createUrlTree).toHaveBeenCalledWith(['draft-1', 'files', 'file-guid', 'preview']); - expect(mockRouter.serializeUrl).toHaveBeenCalledWith(urlTree); - expect(openSpy).toHaveBeenCalledWith('/draft-1/files/file-guid/preview', '_blank'); + expect(component.attachedFiles['files']).toEqual([ + expect.objectContaining({ file_id: 'new-file', file_name: 'new.txt', name: 'new.txt' }), + ]); }); - it('should not open file preview when file guid is missing', () => { - const { component } = setup({ routeParams: { step: '1', id: 'draft-1' } }); - const openSpy = vi.spyOn(window, 'open').mockImplementation(() => null); + it('should warn when the attachment limit is reached', () => { + const { component, toastMock } = setup({ + pages: [createPage([createQuestion({ responseKey: 'files', fieldType: FieldType.File })])], + stepsData: { files: [] }, + }); + component.attachedFiles['files'] = Array.from({ length: FILE_COUNT_ATTACHMENTS_LIMIT }, (_, i) => ({ + ...filePayload, + file_id: `f-${i}`, + name: `f-${i}`, + })); - component.onOpenFile({ guid: null } as FileModel); + component.onAttachFile(FileModelMock.simple({ id: 'new' }), 'files'); - expect(openSpy).not.toHaveBeenCalled(); + expect(toastMock.showWarn).toHaveBeenCalledWith('shared.files.limitText'); + expect(component.attachedFiles['files'].length).toBe(FILE_COUNT_ATTACHMENTS_LIMIT); }); - it('should skip non-existent questionKey', () => { - const { component } = setup(); + it('should remove a file and emit the mapped question payload', () => { + const { component } = setup({ + pages: [createPage([createQuestion({ responseKey: 'files', fieldType: FieldType.File })])], + stepsData: { files: [] }, + }); const emitSpy = vi.spyOn(component.updateAction, 'emit'); - component.removeFromAttachedFiles('f1', 'nonexistent'); - expect(emitSpy).not.toHaveBeenCalled(); + component.attachedFiles['files'] = [ + { ...filePayload, name: 'a' }, + { + file_id: 'f2', + file_name: 'b.pdf', + file_urls: { html: '', download: '' }, + file_hashes: { sha256: '' }, + name: 'b', + }, + ]; + + component.removeFromAttachedFiles('f1', 'files'); + + expect(component.attachedFiles['files']).toEqual([expect.objectContaining({ file_id: 'f2', name: 'b' })]); + expect(emitSpy).toHaveBeenCalledWith({ + files: [ + { + file_id: 'f2', + file_name: 'b.pdf', + file_urls: { html: '', download: '' }, + file_hashes: { sha256: '' }, + }, + ], + }); }); - it('should save step state and update step on route param change', () => { - const { component, store, routeBuilder } = setup(); - (store.dispatch as Mock).mockClear(); - routeBuilder.withParams({ step: 2 }); + it('should skip remove when the question key is missing', () => { + const { component } = setup(); + const emitSpy = vi.spyOn(component.updateAction, 'emit'); - expect(store.dispatch).toHaveBeenCalledWith(expect.any(UpdateStepState)); - expect(component.step()).toBe(2); - }); + component.removeFromAttachedFiles('f1', 'nonexistent'); - it('should mark form touched when stepsState has invalid for current step', () => { - const { component } = setup({ - stepsState: { 1: { invalid: true, touched: true } }, - }); - expect(component['stepForm'].get('field1')?.touched).toBe(true); + expect(emitSpy).not.toHaveBeenCalled(); }); - it('should initialize checkbox control with empty array default', () => { + it('should remove a deleted file from file questions on every page', () => { + const otherFile: FilePayloadJsonApi = { ...filePayload, file_id: 'f2', file_name: 'other.pdf' }; const { component } = setup({ pages: [ - createPage([ - { id: 'q', displayText: '', responseKey: 'cbField', fieldType: FieldType.Checkbox, required: true }, - ]), + createPage([createQuestion({ responseKey: 'files', fieldType: FieldType.File })]), + createPage([createQuestion({ responseKey: 'otherFiles', fieldType: FieldType.File })]), ], - stepsData: {}, + stepsData: { files: [filePayload, otherFile], otherFiles: [filePayload] }, }); - expect(component['stepForm'].get('cbField')?.value).toEqual([]); + const emitSpy = vi.spyOn(component.updateAction, 'emit'); + + component.removeDeletedFileFromAllQuestions('f1'); + + expect(component.attachedFiles['files']).toEqual([{ ...otherFile, name: 'other.pdf' }]); + expect(component.stepForm.get('files')?.value).toEqual([{ ...otherFile, name: 'other.pdf' }]); + expect(emitSpy).toHaveBeenCalledWith({ files: [otherFile], otherFiles: [] }); }); - it('should initialize radio control with required validator', () => { + it('should remove a file attached on this page when it is deleted', () => { const { component } = setup({ - pages: [ - createPage([ - { id: 'q', displayText: '', responseKey: 'radioField', fieldType: FieldType.Radio, required: true }, - ]), - ], - stepsData: {}, + pages: [createPage([createQuestion({ responseKey: 'files', fieldType: FieldType.File })])], + stepsData: { files: [] }, }); - expect(component['stepForm'].get('radioField')?.valid).toBe(false); + component.onAttachFile(FileModelMock.simple({ id: 'new-file' }), 'files'); + const emitSpy = vi.spyOn(component.updateAction, 'emit'); + + component.removeDeletedFileFromAllQuestions('new-file'); + + expect(component.attachedFiles['files']).toEqual([]); + expect(emitSpy).toHaveBeenCalledWith({ files: [] }); }); - it('should initialize file control and populate attachedFiles', () => { - const files: FilePayloadJsonApi[] = [ - { file_id: 'f1', file_name: 'doc.pdf', file_urls: { html: '', download: '' }, file_hashes: { sha256: '' } }, - ]; + it('should not emit when the deleted file is not attached', () => { const { component } = setup({ - pages: [ - createPage([ - { id: 'q', displayText: '', responseKey: 'fileField', fieldType: FieldType.File, required: false }, - ]), - ], - stepsData: { fileField: files }, + pages: [createPage([createQuestion({ responseKey: 'files', fieldType: FieldType.File })])], + stepsData: { files: [filePayload] }, }); + const emitSpy = vi.spyOn(component.updateAction, 'emit'); - expect(component.attachedFiles['fileField'].length).toBe(1); - expect(component.attachedFiles['fileField'][0].name).toBe('doc.pdf'); + component.removeDeletedFileFromAllQuestions('unknown'); + + expect(component.attachedFiles['files']).toHaveLength(1); + expect(emitSpy).not.toHaveBeenCalled(); }); - it('should skip unknown field types', () => { - const { component } = setup({ - pages: [ - createPage([ - { id: 'q', displayText: '', responseKey: 'unknownField', fieldType: 'unknown' as FieldType, required: false }, - ]), - ], - stepsData: {}, + it('should handle a file deleted from the files list', () => { + const { component, fixture } = setup({ + pages: [createPage([createQuestion({ responseKey: 'files', fieldType: FieldType.File })])], + stepsData: { files: [filePayload] }, }); - expect(component['stepForm'].get('unknownField')).toBeNull(); + const deleteSpy = vi.spyOn(component, 'removeDeletedFileFromAllQuestions'); + + fixture.debugElement + .query(By.directive(FilesControlComponent)) + .triggerEventHandler('removeFromAttachedFiles', 'f1'); + + expect(deleteSpy).toHaveBeenCalledWith('f1'); }); - it('should include section questions', () => { - const { component } = setup({ - pages: [ - createPage( - [], - [ - { - id: 's1', - title: 'S', - questions: [ - { id: 'q', displayText: '', responseKey: 'secField', fieldType: FieldType.Text, required: false }, - ], - }, - ] - ), - ], - stepsData: { secField: 'val' }, + it('should open file preview when draftId and guid exist', () => { + const urlTree = {} as UrlTree; + const { component, mockRouter } = setup({ + routeParams: { step: '1', id: 'draft-1' }, + urlTree, + serializedUrl: '/draft-1/files/file-guid/preview', }); + const openSpy = vi.spyOn(window, 'open').mockImplementation(() => null); + + component.onOpenFile({ guid: 'file-guid' } as FileModel); - expect(component['stepForm'].get('secField')).toBeDefined(); - expect(component['stepForm'].get('secField')?.value).toBe('val'); + expect(mockRouter.createUrlTree).toHaveBeenCalledWith(['draft-1', 'files', 'file-guid', 'preview']); + expect(mockRouter.serializeUrl).toHaveBeenCalledWith(urlTree); + expect(openSpy).toHaveBeenCalledWith('/draft-1/files/file-guid/preview', '_blank'); + }); + + it('should not open file preview when guid is missing', () => { + const { component } = setup({ routeParams: { step: '1', id: 'draft-1' } }); + const openSpy = vi.spyOn(window, 'open').mockImplementation(() => null); + + component.onOpenFile({ guid: null } as FileModel); + + expect(openSpy).not.toHaveBeenCalled(); }); }); diff --git a/src/app/features/registries/components/custom-step/custom-step.component.ts b/src/app/features/registries/components/custom-step/custom-step.component.ts index ce1d26fc7..6b6245a00 100644 --- a/src/app/features/registries/components/custom-step/custom-step.component.ts +++ b/src/app/features/registries/components/custom-step/custom-step.component.ts @@ -29,17 +29,17 @@ import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { FormBuilder, FormControl, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms'; import { ActivatedRoute, Router } from '@angular/router'; -import { UserSelectors } from '@osf/core/store/user/user.selectors'; +import { UserSelectors } from '@osf/core/store/user'; import { InfoIconComponent } from '@osf/shared/components/info-icon/info-icon.component'; import { FILE_COUNT_ATTACHMENTS_LIMIT } from '@osf/shared/constants/files-limits.const'; import { INPUT_VALIDATION_MESSAGES } from '@osf/shared/constants/input-validation-messages.const'; import { FieldType } from '@osf/shared/enums/field-type.enum'; import { CustomValidators } from '@osf/shared/helpers/custom-form-validators.helper'; import { findChangedFields } from '@osf/shared/helpers/find-changed-fields'; +import { FileModel } from '@osf/shared/models/files/file.model'; +import { FilePayloadJsonApi } from '@osf/shared/models/files/file-payload-json-api.model'; +import { PageSchema, Question } from '@osf/shared/models/registration/page-schema.model'; import { ToastService } from '@osf/shared/services/toast.service'; -import { FileModel } from '@shared/models/files/file.model'; -import { FilePayloadJsonApi } from '@shared/models/files/file-payload-json-api.model'; -import { PageSchema } from '@shared/models/registration/page-schema.model'; import { FilesMapper } from '../../mappers/files.mapper'; import { AttachedFile } from '../../models/attached-file.model'; @@ -69,16 +69,14 @@ import { FilesControlComponent } from '../files-control/files-control.component' changeDetection: ChangeDetectionStrategy.OnPush, }) export class CustomStepComponent implements OnDestroy { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - stepsData = input.required>(); - filesLink = input.required(); - projectId = input.required(); - filesViewOnly = input(false); + readonly stepsData = input.required>(); + readonly filesLink = input.required(); + readonly projectId = input.required(); + readonly filesViewOnly = input(false); - // eslint-disable-next-line @typescript-eslint/no-explicit-any - updateAction = output>(); - back = output(); - next = output(); + readonly updateAction = output>(); + readonly back = output(); + readonly next = output(); private readonly route = inject(ActivatedRoute); private readonly router = inject(Router); @@ -98,15 +96,21 @@ export class CustomStepComponent implements OnDestroy { readonly FieldType = FieldType; readonly INPUT_VALIDATION_MESSAGES = INPUT_VALIDATION_MESSAGES; - step = signal(this.route.snapshot.params['step']); - draftId = signal(this.route.snapshot.params['id']); - currentPage = computed(() => this.pages()[this.step() - 1]); + readonly step = signal(+this.route.snapshot.params['step']); + readonly draftId = signal(this.route.snapshot.params['id'] as string); + readonly currentPage = computed(() => this.pages()[this.step() - 1]); readonly fileUploadDescription = computed(() => { if (this.projectCreationDisabled()) { return 'shared.files.descriptionNoProject'; } return 'shared.files.description'; }); + private readonly fileQuestionKeys = computed(() => + this.pages() + .flatMap((page) => this.getPageQuestions(page)) + .filter((q) => q.fieldType === FieldType.File) + .map((q) => q.responseKey as string) + ); stepForm: FormGroup = this.fb.group({}); attachedFiles: Record = {}; @@ -132,15 +136,32 @@ export class CustomStepComponent implements OnDestroy { return; } - this.attachedFiles[questionKey] = [...this.attachedFiles[questionKey], file]; + const attachedFile = { ...FilesMapper.toFilePayload(file), name: file.name }; + this.attachedFiles[questionKey] = [...this.attachedFiles[questionKey], attachedFile]; this.stepForm.patchValue({ [questionKey]: this.attachedFiles[questionKey] }); + this.updateAction.emit(this.getFormPayload()); + } - const otherFormValues = { ...this.stepForm.value }; - delete otherFormValues[questionKey]; - this.updateAction.emit({ - [questionKey]: this.mapFilesToPayload(this.attachedFiles[questionKey]), - ...otherFormValues, - }); + removeDeletedFileFromAllQuestions(fileId: string): void { + const payload: Record = {}; + + for (const key of this.fileQuestionKeys()) { + const files = this.attachedFiles[key] ?? this.getSavedFiles(key); + if (!files.some((f) => f.file_id === fileId)) { + continue; + } + + const remaining = files.filter((f) => f.file_id !== fileId); + if (this.attachedFiles[key]) { + this.attachedFiles[key] = remaining; + this.stepForm.patchValue({ [key]: remaining }); + } + payload[key] = this.mapFilesToPayload(remaining); + } + + if (Object.keys(payload).length) { + this.updateAction.emit(payload); + } } onOpenFile(file: FileModel): void { @@ -184,6 +205,7 @@ export class CustomStepComponent implements OnDestroy { this.route.params.pipe(takeUntilDestroyed(this.destroyRef)).subscribe((params) => { this.saveStepState(); this.step.set(+params['step']); + this.draftId.set(params['id']); }); } @@ -198,19 +220,14 @@ export class CustomStepComponent implements OnDestroy { private initStepForm(page: PageSchema): void { this.stepForm = this.fb.group({}); - const questions = [ - ...(page.questions || []), - ...(page.sections?.flatMap((section) => section.questions ?? []) ?? []), - ]; - - questions.forEach((q) => { + this.attachedFiles = {}; + this.getPageQuestions(page).forEach((q) => { const controlName = q.responseKey as string; const control = this.createControl(q.fieldType!, controlName, q.required); if (!control) return; if (q.fieldType === FieldType.File) { - this.attachedFiles[controlName] = - this.stepsData()[controlName]?.map((file: FilePayloadJsonApi) => ({ ...file, name: file.file_name })) || []; + this.attachedFiles[controlName] = this.getSavedFiles(controlName); } this.stepForm.addControl(controlName, control); @@ -253,23 +270,39 @@ export class CustomStepComponent implements OnDestroy { return; } - const changedFields = findChangedFields(this.stepForm.value, this.stepsData()); + const formPayload = this.getFormPayload(); + const changedFields = findChangedFields(formPayload, this.stepsData()); if (Object.keys(changedFields).length > 0) { this.actions.setUpdatedFields(changedFields); - this.updateAction.emit(this.stepForm.value); + this.updateAction.emit(formPayload); } this.stepForm.markAllAsTouched(); - this.actions.updateStepState(this.step(), this.stepForm.invalid, true); + this.actions.updateStepState(String(this.step()), this.stepForm.invalid, true); } - private mapFilesToPayload(files: AttachedFile[]): FilePayloadJsonApi[] { - return files.map((f) => { - if (f.file_id) { - const { name: _, ...payload } = f; - return payload as FilePayloadJsonApi; + private getFormPayload(): Record { + const values: Record = { ...this.stepForm.value }; + + for (const key of Object.keys(this.attachedFiles)) { + if (Object.prototype.hasOwnProperty.call(values, key)) { + values[key] = this.mapFilesToPayload(this.attachedFiles[key] ?? []); } - return FilesMapper.toFilePayload(f as FileModel); - }); + } + + return values; + } + + private getPageQuestions(page: PageSchema): Question[] { + return [...(page.questions || []), ...(page.sections?.flatMap((section) => section.questions ?? []) ?? [])]; + } + + private getSavedFiles(questionKey: string): AttachedFile[] { + const files = (this.stepsData()[questionKey] as FilePayloadJsonApi[] | undefined) || []; + return files.map((file) => ({ ...file, name: file.file_name })); + } + + private mapFilesToPayload(files: AttachedFile[]): FilePayloadJsonApi[] { + return files.map(({ name: _, ...payload }) => payload); } } diff --git a/src/app/features/registries/components/drafts/drafts.component.spec.ts b/src/app/features/registries/components/drafts/drafts.component.spec.ts index ad41d715b..560ec5990 100644 --- a/src/app/features/registries/components/drafts/drafts.component.spec.ts +++ b/src/app/features/registries/components/drafts/drafts.component.spec.ts @@ -11,9 +11,11 @@ import { ActivatedRoute, NavigationEnd, Router } from '@angular/router'; import { StepperComponent } from '@osf/shared/components/stepper/stepper.component'; import { SubHeaderComponent } from '@osf/shared/components/sub-header/sub-header.component'; +import { ResourceType } from '@osf/shared/enums/resource-type.enum'; import { LoaderService } from '@osf/shared/services/loader.service'; -import { ContributorsSelectors } from '@osf/shared/stores/contributors'; -import { SubjectsSelectors } from '@osf/shared/stores/subjects'; +import { ContributorsSelectors, GetAllContributors } from '@osf/shared/stores/contributors'; +import { GetRegistryProvider, RegistrationProviderSelectors } from '@osf/shared/stores/registration-provider'; +import { FetchSelectedSubjects, SubjectsSelectors } from '@osf/shared/stores/subjects'; import { MOCK_DRAFT_REGISTRATION, @@ -25,18 +27,21 @@ import { provideOSFCore } from '@testing/osf.testing.provider'; import { LoaderServiceMock } from '@testing/providers/loader-service.mock'; import { ActivatedRouteMockBuilder } from '@testing/providers/route-provider.mock'; import { RouterMockBuilder, RouterMockType } from '@testing/providers/router-provider.mock'; -import { provideMockStore } from '@testing/providers/store-provider.mock'; +import { + BaseSetupOverrides, + mergeSignalOverrides, + provideMockStore, + SignalOverride, +} from '@testing/providers/store-provider.mock'; -import { ClearState, RegistriesSelectors } from '../../store'; +import { ClearState, FetchDraft, RegistriesSelectors } from '../../store'; import { DraftsComponent } from './drafts.component'; -interface SetupOverrides { - routeParams?: Record; +interface SetupOverrides extends BaseSetupOverrides { firstChildParams?: Record | null; routerUrl?: string; routerEvents?: unknown; - selectorOverrides?: { selector: unknown; value: unknown }[]; } function setup(overrides: SetupOverrides = {}) { @@ -61,23 +66,16 @@ function setup(overrides: SetupOverrides = {}) { mockRouter.events = of(new NavigationEnd(1, '/', '/')); } - const defaultSignals: { selector: unknown; value: unknown }[] = [ + const defaultSignals: SignalOverride[] = [ { selector: RegistriesSelectors.getPagesSchema, value: MOCK_PAGES_SCHEMA }, { selector: RegistriesSelectors.getDraftRegistration, value: MOCK_DRAFT_REGISTRATION }, - { selector: RegistriesSelectors.getRegistrationLicense, value: { id: 'mit' } }, { selector: RegistriesSelectors.getStepsState, value: {} }, { selector: RegistriesSelectors.getStepsData, value: {} }, { selector: ContributorsSelectors.getContributors, value: [{ id: 'c1' }] }, { selector: SubjectsSelectors.getSelectedSubjects, value: [{ id: 's1' }] }, + { selector: RegistrationProviderSelectors.getBrandedProvider, value: { id: 'osf' } }, ]; - const signals = overrides.selectorOverrides - ? defaultSignals.map((s) => { - const override = overrides.selectorOverrides!.find((o) => o.selector === s.selector); - return override ? { ...s, value: override.value } : s; - }) - : defaultSignals; - TestBed.configureTestingModule({ imports: [DraftsComponent, ...MockComponents(StepperComponent, SubHeaderComponent)], providers: [ @@ -85,7 +83,9 @@ function setup(overrides: SetupOverrides = {}) { MockProvider(ActivatedRoute, mockActivatedRoute), MockProvider(Router, mockRouter), MockProvider(LoaderService, new LoaderServiceMock()), - provideMockStore({ signals }), + provideMockStore({ + signals: mergeSignalOverrides(defaultSignals, overrides.selectorOverrides), + }), ], }); @@ -186,7 +186,12 @@ describe('DraftsComponent', () => { it('should set metadata step as invalid when license is missing', () => { const { component: c } = setup({ - selectorOverrides: [{ selector: RegistriesSelectors.getRegistrationLicense, value: null }], + selectorOverrides: [ + { + selector: RegistriesSelectors.getDraftRegistration, + value: { ...MOCK_DRAFT_REGISTRATION, license: { id: '', options: null } }, + }, + ], }); const steps = c.steps(); @@ -194,39 +199,62 @@ describe('DraftsComponent', () => { }); it('should dispatch getDraftRegistration when draftRegistration is null', () => { - const { component: c } = setup({ + const { store: s } = setup({ selectorOverrides: [{ selector: RegistriesSelectors.getDraftRegistration, value: null }], }); - expect(c).toBeTruthy(); + expect(s.dispatch).toHaveBeenCalledWith(new FetchDraft('reg-1')); }); it('should dispatch getContributors when contributors list is empty', () => { - const { component: c } = setup({ + const { store: s } = setup({ selectorOverrides: [{ selector: ContributorsSelectors.getContributors, value: [] }], }); - expect(c).toBeTruthy(); + expect(s.dispatch).toHaveBeenCalledWith(new GetAllContributors('reg-1', ResourceType.DraftRegistration)); }); it('should dispatch getSubjects when selectedSubjects list is empty', () => { - const { component: c } = setup({ + const { store: s } = setup({ selectorOverrides: [{ selector: SubjectsSelectors.getSelectedSubjects, value: [] }], }); - expect(c).toBeTruthy(); + expect(s.dispatch).toHaveBeenCalledWith(new FetchSelectedSubjects('reg-1', ResourceType.DraftRegistration)); }); - it('should dispatch all actions when all initial data is missing', () => { - const { component: c } = setup({ + it('should dispatch getRegistryProvider when branded provider is missing', () => { + const { store: s, fixture: f } = setup({ + selectorOverrides: [{ selector: RegistrationProviderSelectors.getBrandedProvider, value: null }], + }); + + f.detectChanges(); + + expect(s.dispatch).toHaveBeenCalledWith(new GetRegistryProvider('osf')); + }); + + it('should dispatch getRegistryProvider with defaultProvider when draft has no providerId', () => { + const { store: s, fixture: f } = setup({ selectorOverrides: [ - { selector: RegistriesSelectors.getDraftRegistration, value: null }, - { selector: ContributorsSelectors.getContributors, value: [] }, - { selector: SubjectsSelectors.getSelectedSubjects, value: [] }, + { + selector: RegistriesSelectors.getDraftRegistration, + value: { ...MOCK_DRAFT_REGISTRATION, providerId: undefined }, + }, + { selector: RegistrationProviderSelectors.getBrandedProvider, value: null }, ], }); - expect(c).toBeTruthy(); + f.detectChanges(); + + expect(s.dispatch).toHaveBeenCalledWith(new GetRegistryProvider('osf')); + }); + + it('should not dispatch getRegistryProvider when branded provider already matches', () => { + const { store: s, fixture: f } = setup(); + + (s.dispatch as Mock).mockClear(); + f.detectChanges(); + + expect(s.dispatch).not.toHaveBeenCalledWith(expect.any(GetRegistryProvider)); }); it('should hide loader after schema blocks are fetched', async () => { @@ -401,18 +429,6 @@ describe('DraftsComponent', () => { expect(c.currentStepIndex()).toBe(0); }); - it('should validate metadata step as invalid when license is missing', () => { - const { component: c } = setup({ - firstChildParams: { id: 'reg-1', step: '1' }, - selectorOverrides: [ - { selector: RegistriesSelectors.getRegistrationLicense, value: null }, - { selector: RegistriesSelectors.getStepsData, value: { field1: 'v1' } }, - ], - }); - - expect(c.isMetaDataInvalid()).toBe(true); - }); - it('should validate metadata step as invalid when description is missing', () => { const { component: c } = setup({ firstChildParams: { id: 'reg-1', step: '1' }, diff --git a/src/app/features/registries/components/drafts/drafts.component.ts b/src/app/features/registries/components/drafts/drafts.component.ts index f1579427a..a2dc034e4 100644 --- a/src/app/features/registries/components/drafts/drafts.component.ts +++ b/src/app/features/registries/components/drafts/drafts.component.ts @@ -18,6 +18,7 @@ import { import { takeUntilDestroyed, toObservable } from '@angular/core/rxjs-interop'; import { ActivatedRoute, NavigationEnd, Router, RouterOutlet } from '@angular/router'; +import { ENVIRONMENT } from '@core/provider/environment.provider'; import { StepperComponent } from '@osf/shared/components/stepper/stepper.component'; import { SubHeaderComponent } from '@osf/shared/components/sub-header/sub-header.component'; import { ResourceType } from '@osf/shared/enums/resource-type.enum'; @@ -25,6 +26,7 @@ import { PageSchema, Question } from '@osf/shared/models/registration/page-schem import { StepOption } from '@osf/shared/models/step-option.model'; import { LoaderService } from '@osf/shared/services/loader.service'; import { ContributorsSelectors, GetAllContributors } from '@osf/shared/stores/contributors'; +import { GetRegistryProvider, RegistrationProviderSelectors } from '@osf/shared/stores/registration-provider'; import { FetchSelectedSubjects, SubjectsSelectors } from '@osf/shared/stores/subjects'; import { DEFAULT_STEPS } from '../../constants'; @@ -43,13 +45,14 @@ export class DraftsComponent implements OnDestroy { private readonly loaderService = inject(LoaderService); private readonly translateService = inject(TranslateService); private readonly destroyRef = inject(DestroyRef); + private readonly environment = inject(ENVIRONMENT); readonly pages = select(RegistriesSelectors.getPagesSchema); readonly draftRegistration = select(RegistriesSelectors.getDraftRegistration); readonly stepsState = select(RegistriesSelectors.getStepsState); + readonly provider = select(RegistrationProviderSelectors.getBrandedProvider); private readonly stepsData = select(RegistriesSelectors.getStepsData); - private readonly registrationLicense = select(RegistriesSelectors.getRegistrationLicense); private readonly selectedSubjects = select(SubjectsSelectors.getSelectedSubjects); private readonly contributors = select(ContributorsSelectors.getContributors); @@ -57,9 +60,10 @@ export class DraftsComponent implements OnDestroy { getSchemaBlocks: FetchSchemaBlocks, getDraftRegistration: FetchDraft, updateStepState: UpdateStepState, - clearState: ClearState, getContributors: GetAllContributors, getSubjects: FetchSelectedSubjects, + getRegistryProvider: GetRegistryProvider, + clearState: ClearState, }); get isReviewPage(): boolean { @@ -70,7 +74,7 @@ export class DraftsComponent implements OnDestroy { () => !this.draftRegistration()?.title || !this.draftRegistration()?.description || - !this.registrationLicense() || + !this.draftRegistration()?.license?.id || !this.selectedSubjects()?.length ); @@ -115,6 +119,7 @@ export class DraftsComponent implements OnDestroy { constructor() { this.loadInitialData(); this.setupSchemaLoader(); + this.setupProviderLoader(); this.setupRouteWatcher(); this.setupReviewStepSync(); this.setupStepValidation(); @@ -156,6 +161,20 @@ export class DraftsComponent implements OnDestroy { .subscribe(() => this.loaderService.hide()); } + private setupProviderLoader() { + effect(() => { + const draft = this.draftRegistration(); + if (!draft) { + return; + } + + const providerId = draft.providerId ?? this.environment.defaultProvider; + if (this.provider()?.id !== providerId) { + this.actions.getRegistryProvider(providerId); + } + }); + } + private setupRouteWatcher() { this.router.events .pipe( diff --git a/src/app/features/registries/components/registries-metadata-step/registries-license/registries-license.component.html b/src/app/features/registries/components/registries-metadata-step/registries-license/registries-license.component.html index 694fe910e..2b411cdd5 100644 --- a/src/app/features/registries/components/registries-metadata-step/registries-license/registries-license.component.html +++ b/src/app/features/registries/components/registries-metadata-step/registries-license/registries-license.component.html @@ -2,7 +2,7 @@

{{ 'common.labels.license' | translate }}

{{ 'shared.license.description' | translate }}

-

+

{{ 'shared.license.helpText' | translate }} {{ 'common.links.helpGuide' | translate }}{{ 'common.labels.license' | translate }}

| null; + licensesUrl?: string | null; +} + describe('RegistriesLicenseComponent', () => { let component: RegistriesLicenseComponent; let fixture: ComponentFixture; let store: Store; let licensesSignal: WritableSignal; - let selectedLicenseSignal: WritableSignal<{ id: string; options?: Record } | null>; - let draftRegistrationSignal: WritableSignal | null>; + let selectedLicenseSignal: WritableSignal; + let draftRegistrationSignal: WritableSignal | null>; const mockLicense: LicenseModel = { id: 'lic-1', name: 'MIT', requiredFields: [], url: '', text: '' }; const mockDefaultLicense: LicenseModel = { id: 'default-1', name: 'Default', requiredFields: [], url: '', text: '' }; - beforeEach(() => { + function setup(overrides: SetupOverrides = {}) { + const draft = 'draft' in overrides ? overrides.draft! : {}; + const licensesUrl = 'licensesUrl' in overrides ? overrides.licensesUrl : DEFAULT_LICENSES_URL; + licensesSignal = signal([]); - selectedLicenseSignal = signal<{ id: string; options?: Record } | null>(null); - draftRegistrationSignal = signal | null>({ - providerId: 'osf', - }); + selectedLicenseSignal = signal(null); + draftRegistrationSignal = signal(draft); TestBed.configureTestingModule({ imports: [RegistriesLicenseComponent, MockComponent(LicenseComponent)], @@ -54,34 +63,56 @@ describe('RegistriesLicenseComponent', () => { component = fixture.componentInstance; fixture.componentRef.setInput('control', new FormGroup({ id: new FormControl('') })); fixture.componentRef.setInput('draftId', 'draft-1'); + if (licensesUrl != null) { + fixture.componentRef.setInput('licensesUrl', licensesUrl); + } fixture.detectChanges(); - }); + } it('should create', () => { + setup(); expect(component).toBeTruthy(); }); - it('should dispatch fetchLicenses on init when draft present', () => { - expect(store.dispatch).toHaveBeenCalledWith(new FetchLicenses('osf')); + it('should dispatch fetchLicenses on init when licensesUrl present', () => { + setup(); + expect(store.dispatch).toHaveBeenCalledWith(new FetchLicenses(DEFAULT_LICENSES_URL)); + }); + + it('should not fetch licenses when licensesUrl is missing', () => { + setup({ licensesUrl: null }); + expect(store.dispatch).not.toHaveBeenCalledWith(expect.any(FetchLicenses)); }); - it('should fetch licenses only once even if draft re-emits', () => { + it('should not re-fetch when draft registration changes', () => { + setup(); (store.dispatch as Mock).mockClear(); - draftRegistrationSignal.set({ providerId: 'other' }); + draftRegistrationSignal.set({ defaultLicenseId: 'default-1' }); fixture.detectChanges(); expect(store.dispatch).not.toHaveBeenCalledWith(expect.any(FetchLicenses)); }); it('should sync selected license to control when license exists in list', () => { + setup(); licensesSignal.set([mockLicense]); - selectedLicenseSignal.set({ id: 'lic-1' }); + selectedLicenseSignal.set({ id: 'lic-1', options: null }); fixture.detectChanges(); expect(component.control().get('id')?.value).toBe('lic-1'); }); + it('should apply default license when selected license is not in the list', () => { + setup({ draft: { defaultLicenseId: 'default-1' } }); + (store.dispatch as Mock).mockClear(); + selectedLicenseSignal.set({ id: 'missing-lic', options: null }); + licensesSignal.set([mockDefaultLicense]); + fixture.detectChanges(); + expect(component.control().get('id')?.value).toBe('default-1'); + expect(store.dispatch).toHaveBeenCalledWith(new SaveLicense('draft-1', 'default-1')); + }); + it('should apply default license and save when no selected license', () => { + setup({ draft: { defaultLicenseId: 'default-1' } }); (store.dispatch as Mock).mockClear(); - draftRegistrationSignal.set({ providerId: 'osf', defaultLicenseId: 'default-1' }); licensesSignal.set([mockDefaultLicense]); fixture.detectChanges(); expect(component.control().get('id')?.value).toBe('default-1'); @@ -89,6 +120,7 @@ describe('RegistriesLicenseComponent', () => { }); it('should apply default license but not save when it has required fields', () => { + setup({ draft: { defaultLicenseId: 'default-2' } }); (store.dispatch as Mock).mockClear(); const licenseWithFields: LicenseModel = { id: 'default-2', @@ -97,7 +129,6 @@ describe('RegistriesLicenseComponent', () => { url: '', text: '', }; - draftRegistrationSignal.set({ providerId: 'osf', defaultLicenseId: 'default-2' }); licensesSignal.set([licenseWithFields]); fixture.detectChanges(); expect(component.control().get('id')?.value).toBe('default-2'); @@ -105,14 +136,15 @@ describe('RegistriesLicenseComponent', () => { }); it('should prefer selected license over default license', () => { + setup({ draft: { defaultLicenseId: 'default-1' } }); licensesSignal.set([mockDefaultLicense, mockLicense]); - draftRegistrationSignal.set({ providerId: 'osf', defaultLicenseId: 'default-1' }); - selectedLicenseSignal.set({ id: 'lic-1' }); + selectedLicenseSignal.set({ id: 'lic-1', options: { year: '2024', copyrightHolders: 'Me' } }); fixture.detectChanges(); expect(component.control().get('id')?.value).toBe('lic-1'); }); it('should set control id and save license when selecting simple license', () => { + setup(); (store.dispatch as Mock).mockClear(); component.selectLicense(mockLicense); expect(component.control().get('id')?.value).toBe('lic-1'); @@ -120,22 +152,28 @@ describe('RegistriesLicenseComponent', () => { }); it('should not save when license has required fields', () => { + setup(); (store.dispatch as Mock).mockClear(); component.selectLicense({ id: 'lic-2', name: 'CC-BY', requiredFields: ['year'], url: '', text: '' }); expect(store.dispatch).not.toHaveBeenCalled(); }); it('should dispatch saveLicense with options on createLicense', () => { + setup(); (store.dispatch as Mock).mockClear(); - component.createLicense({ id: 'lic-3', licenseOptions: { year: '2024', copyrightHolders: 'Me' } }); + const licenseDetails: LicenseDetails = { + id: 'lic-3', + licenseOptions: { year: '2024', copyrightHolders: 'Me' }, + }; + component.createLicense(licenseDetails); expect(store.dispatch).toHaveBeenCalledWith( new SaveLicense('draft-1', 'lic-3', { year: '2024', copyrightHolders: 'Me' }) ); }); it('should not apply default license when defaultLicenseId is not in the list', () => { + setup({ draft: { defaultLicenseId: 'non-existent' } }); (store.dispatch as Mock).mockClear(); - draftRegistrationSignal.set({ providerId: 'osf', defaultLicenseId: 'non-existent' }); licensesSignal.set([mockLicense]); fixture.detectChanges(); expect(component.control().get('id')?.value).toBe(''); @@ -143,6 +181,7 @@ describe('RegistriesLicenseComponent', () => { }); it('should mark control on focus out', () => { + setup(); component.onFocusOut(); expect(component.control().touched).toBe(true); expect(component.control().dirty).toBe(true); diff --git a/src/app/features/registries/components/registries-metadata-step/registries-license/registries-license.component.ts b/src/app/features/registries/components/registries-metadata-step/registries-license/registries-license.component.ts index 7225338ca..fdf887bb6 100644 --- a/src/app/features/registries/components/registries-metadata-step/registries-license/registries-license.component.ts +++ b/src/app/features/registries/components/registries-metadata-step/registries-license/registries-license.component.ts @@ -5,14 +5,13 @@ import { TranslatePipe } from '@ngx-translate/core'; import { Card } from 'primeng/card'; import { Message } from 'primeng/message'; -import { ChangeDetectionStrategy, Component, effect, inject, input, signal } from '@angular/core'; +import { ChangeDetectionStrategy, Component, effect, input } from '@angular/core'; import { FormGroup, ReactiveFormsModule } from '@angular/forms'; -import { ENVIRONMENT } from '@core/provider/environment.provider'; import { FetchLicenses, RegistriesSelectors, SaveLicense } from '@osf/features/registries/store'; import { LicenseComponent } from '@osf/shared/components/license/license.component'; import { INPUT_VALIDATION_MESSAGES } from '@osf/shared/constants/input-validation-messages.const'; -import { LicenseModel, LicenseOptions } from '@shared/models/license/license.model'; +import { LicenseDetails, LicenseModel } from '@shared/models/license/license.model'; @Component({ selector: 'osf-registries-license', @@ -22,26 +21,24 @@ import { LicenseModel, LicenseOptions } from '@shared/models/license/license.mod changeDetection: ChangeDetectionStrategy.OnPush, }) export class RegistriesLicenseComponent { - control = input.required(); - draftId = input.required(); + readonly control = input.required(); + readonly draftId = input.required(); + readonly licensesUrl = input(); - private readonly environment = inject(ENVIRONMENT); + readonly actions = createDispatchMap({ fetchLicenses: FetchLicenses, saveLicense: SaveLicense }); - actions = createDispatchMap({ fetchLicenses: FetchLicenses, saveLicense: SaveLicense }); - - licenses = select(RegistriesSelectors.getLicenses); - selectedLicense = select(RegistriesSelectors.getSelectedLicense); - draftRegistration = select(RegistriesSelectors.getDraftRegistration); + readonly licenses = select(RegistriesSelectors.getLicenses); + readonly selectedLicense = select(RegistriesSelectors.getSelectedLicense); + readonly draftRegistration = select(RegistriesSelectors.getDraftRegistration); readonly INPUT_VALIDATION_MESSAGES = INPUT_VALIDATION_MESSAGES; - private readonly licensesLoaded = signal(false); - constructor() { effect(() => { - if (this.draftRegistration() && !this.licensesLoaded()) { - this.actions.fetchLicenses(this.draftRegistration()?.providerId ?? this.environment.defaultProvider); - this.licensesLoaded.set(true); + const licensesUrl = this.licensesUrl(); + + if (licensesUrl) { + this.actions.fetchLicenses(licensesUrl); } }); @@ -60,7 +57,7 @@ export class RegistriesLicenseComponent { }); } - createLicense(licenseDetails: { id: string; licenseOptions: LicenseOptions }) { + createLicense(licenseDetails: LicenseDetails) { this.actions.saveLicense(this.draftId(), licenseDetails.id, licenseDetails.licenseOptions); } diff --git a/src/app/features/registries/components/registries-metadata-step/registries-metadata-step.component.html b/src/app/features/registries/components/registries-metadata-step/registries-metadata-step.component.html index 04af77dbc..e139bb208 100644 --- a/src/app/features/registries/components/registries-metadata-step/registries-metadata-step.component.html +++ b/src/app/features/registries/components/registries-metadata-step/registries-metadata-step.component.html @@ -53,17 +53,19 @@

{{ 'common.labels.description' | translate }}

- - - - + + + + - + [licensesUrl]="provider()?.licensesLink" + /> + + + +
{ { selector: RegistriesSelectors.hasDraftAdminAccess, value: true }, { selector: ContributorsSelectors.getContributors, value: [] }, { selector: SubjectsSelectors.getSelectedSubjects, value: [] }, + { selector: RegistrationProviderSelectors.getBrandedProvider, value: null }, ], }), ], @@ -143,7 +145,7 @@ describe('RegistriesMetadataStepComponent', () => { }); it('should set isDraftDeleted and navigate on deleteDraft confirm', () => { - customConfirmationService.confirmDelete.mockImplementation(({ onConfirm }: any) => onConfirm()); + customConfirmationService.confirmDelete.mockImplementation(({ onConfirm }) => onConfirm?.()); (store.dispatch as Mock).mockClear(); component.deleteDraft(); diff --git a/src/app/features/registries/components/registries-metadata-step/registries-metadata-step.component.ts b/src/app/features/registries/components/registries-metadata-step/registries-metadata-step.component.ts index 589ec9174..59f4fc145 100644 --- a/src/app/features/registries/components/registries-metadata-step/registries-metadata-step.component.ts +++ b/src/app/features/registries/components/registries-metadata-step/registries-metadata-step.component.ts @@ -21,6 +21,7 @@ import { CustomValidators } from '@osf/shared/helpers/custom-form-validators.hel import { findChangedFields } from '@osf/shared/helpers/find-changed-fields'; import { CustomConfirmationService } from '@osf/shared/services/custom-confirmation.service'; import { ContributorsSelectors } from '@osf/shared/stores/contributors'; +import { RegistrationProviderSelectors } from '@osf/shared/stores/registration-provider'; import { SubjectsSelectors } from '@osf/shared/stores/subjects'; import { ContributorModel } from '@shared/models/contributors/contributor.model'; import { DraftRegistrationModel } from '@shared/models/registration/draft-registration.model'; @@ -70,6 +71,7 @@ export class RegistriesMetadataStepComponent implements OnDestroy { initialContributors = select(ContributorsSelectors.getContributors); stepsState = select(RegistriesSelectors.getStepsState); hasAdminAccess = select(RegistriesSelectors.hasDraftAdminAccess); + provider = select(RegistrationProviderSelectors.getBrandedProvider); actions = createDispatchMap({ deleteDraft: DeleteDraft, diff --git a/src/app/features/registries/components/review/review.component.html b/src/app/features/registries/components/review/review.component.html index 589a4ab68..2120cfcd5 100644 --- a/src/app/features/registries/components/review/review.component.html +++ b/src/app/features/registries/components/review/review.component.html @@ -1,27 +1,29 @@ +@let draft = draftRegistration(); +@let selectedLicense = license(); +@let selectedSubjects = subjects(); +@let tags = draft?.tags; +

{{ 'navigation.metadata' | translate }}

{{ 'common.labels.title' | translate }}

-

{{ draftRegistration()?.title }}

- @if (!draftRegistration()?.title) { -

{{ 'common.labels.title' | translate }}

-

{{ 'common.labels.noData' | translate }}

- - {{ INPUT_VALIDATION_MESSAGES.required | translate }} - + @if (draft?.title) { +

{{ draft?.title }}

+ } @else { +

{{ 'common.labels.noData' | translate }}

+ }

{{ 'common.labels.description' | translate }}

-

{{ draftRegistration()?.description }}

- @if (!draftRegistration()?.description) { -

{{ 'common.labels.noData' | translate }}

- - {{ INPUT_VALIDATION_MESSAGES.required | translate }} - + @if (draft?.description) { +

{{ draft?.description }}

+ } @else { +

{{ 'common.labels.noData' | translate }}

+ }
@@ -33,47 +35,44 @@

{{ 'common.labels.contributors' | translate }}

[isLoading]="areContributorsLoading()" [hasLoadMore]="hasMoreContributors()" (loadMoreContributors)="loadMoreContributors()" - > + />
-
+

{{ 'common.labels.license' | translate }}

- @if (draftRegistration()?.license && license()) { - + @if (draft?.license?.id && selectedLicense) { + } @else {

{{ 'common.labels.noData' | translate }}

- - {{ INPUT_VALIDATION_MESSAGES.required | translate }} - + }

{{ 'common.labels.subjects' | translate }}

-
- @for (subject of subjects(); track subject.id) { - - } -
- - @if (!subjects().length) { + @if (selectedSubjects.length) { +
+ @for (subject of selectedSubjects; track subject.id) { + + } +
+ } @else {

{{ 'common.labels.noData' | translate }}

- - {{ INPUT_VALIDATION_MESSAGES.required | translate }} - + }

{{ 'shared.tags.title' | translate }}

-
- @for (tag of draftRegistration()?.tags; track tag) { - - } -
- @if (!draftRegistration()?.tags?.length) { -

{{ 'common.labels.noData' | translate }}

+ @if (tags?.length) { +
+ @for (tag of tags; track tag) { + + } +
+ } @else { +

{{ 'common.labels.noData' | translate }}

}
@@ -87,11 +86,7 @@

{{ page.title }}

} @if (page.questions?.length) { - + } @if (page.sections?.length) { @@ -106,7 +101,7 @@

{{ section.title }}

[isDraft]="true" [questions]="section.questions" [reviewData]="stepsData()" - >
+ /> }
} @@ -115,27 +110,25 @@

{{ section.title }}

}
+ - - + /> + />
+ + + + {{ INPUT_VALIDATION_MESSAGES.required | translate }} + + diff --git a/src/app/features/registries/components/review/review.component.spec.ts b/src/app/features/registries/components/review/review.component.spec.ts index 8f656b4a8..81f0db046 100644 --- a/src/app/features/registries/components/review/review.component.spec.ts +++ b/src/app/features/registries/components/review/review.component.spec.ts @@ -9,13 +9,7 @@ import { Mock } from 'vitest'; import { TestBed } from '@angular/core/testing'; import { ActivatedRoute, Router } from '@angular/router'; -import { - ClearState, - DeleteDraft, - FetchLicenses, - FetchProjectChildren, - RegistriesSelectors, -} from '@osf/features/registries/store'; +import { ClearState, DeleteDraft, FetchProjectChildren, RegistriesSelectors } from '@osf/features/registries/store'; import { ContributorsListComponent } from '@osf/shared/components/contributors-list/contributors-list.component'; import { LicenseDisplayComponent } from '@osf/shared/components/license-display/license-display.component'; import { RegistrationBlocksDataComponent } from '@osf/shared/components/registration-blocks-data/registration-blocks-data.component'; @@ -29,6 +23,7 @@ import { LoadMoreContributors, ResetContributorsState, } from '@osf/shared/stores/contributors'; +import { FetchLicense, LicensesSelectors } from '@osf/shared/stores/licenses'; import { FetchSelectedSubjects, SubjectsSelectors } from '@osf/shared/stores/subjects'; import { provideOSFCore } from '@testing/osf.testing.provider'; @@ -42,7 +37,12 @@ import { } from '@testing/providers/custom-dialog-provider.mock'; import { ActivatedRouteMockBuilder } from '@testing/providers/route-provider.mock'; import { RouterMockBuilder, RouterMockType } from '@testing/providers/router-provider.mock'; -import { provideMockStore } from '@testing/providers/store-provider.mock'; +import { + BaseSetupOverrides, + mergeSignalOverrides, + provideMockStore, + SignalOverride, +} from '@testing/providers/store-provider.mock'; import { ToastServiceMock, ToastServiceMockType } from '@testing/providers/toast-provider.mock'; import { ReviewComponent } from './review.component'; @@ -52,80 +52,12 @@ const DEFAULT_DRAFT = { providerId: 'prov-1', currentUserPermissions: [], hasProject: false, - license: { options: {} }, + license: { id: 'lic-1', options: {} }, branchedFrom: { id: 'proj-1', type: 'nodes' }, }; -function createDefaultSignals(overrides: { selector: any; value: any }[] = []) { - const defaults = [ - { selector: RegistriesSelectors.getPagesSchema, value: [] }, - { selector: RegistriesSelectors.getDraftRegistration, value: DEFAULT_DRAFT }, - { selector: RegistriesSelectors.isDraftSubmitting, value: false }, - { selector: RegistriesSelectors.isDraftLoading, value: false }, - { selector: RegistriesSelectors.getStepsData, value: {} }, - { selector: RegistriesSelectors.getRegistrationComponents, value: [] }, - { selector: RegistriesSelectors.getRegistrationLicense, value: null }, - { selector: RegistriesSelectors.getRegistration, value: { id: 'new-reg-1' } }, - { selector: RegistriesSelectors.getStepsState, value: { 0: { invalid: false } } }, - { selector: RegistriesSelectors.hasDraftAdminAccess, value: true }, - { selector: ContributorsSelectors.getContributors, value: [] }, - { selector: ContributorsSelectors.isContributorsLoading, value: false }, - { selector: ContributorsSelectors.hasMoreContributors, value: false }, - { selector: SubjectsSelectors.getSelectedSubjects, value: [] }, - ]; - - return overrides.length - ? defaults.map((s) => { - const override = overrides.find((o) => o.selector === s.selector); - return override ? { ...s, value: override.value } : s; - }) - : defaults; -} - -function setup( - opts: { - selectorOverrides?: { selector: any; value: any }[]; - dialogCloseSubject?: Subject; - } = {} -) { - const mockRouter = RouterMockBuilder.create().withUrl('/registries/123/review').build(); - const mockActivatedRoute = ActivatedRouteMockBuilder.create().withParams({ id: 'draft-1' }).build(); - - const dialogClose$ = opts.dialogCloseSubject ?? new Subject(); - const mockDialog = CustomDialogServiceMockBuilder.create() - .withOpen( - vi.fn().mockReturnValue({ - onClose: dialogClose$.pipe(), - close: vi.fn(), - }) - ) - .build(); - - const mockToast = ToastServiceMock.simple(); - const mockConfirmation = CustomConfirmationServiceMock.simple(); - - TestBed.configureTestingModule({ - imports: [ - ReviewComponent, - ...MockComponents(RegistrationBlocksDataComponent, ContributorsListComponent, LicenseDisplayComponent), - ], - providers: [ - provideOSFCore(), - MockProvider(ActivatedRoute, mockActivatedRoute), - MockProvider(Router, mockRouter), - MockProvider(CustomDialogService, mockDialog), - MockProvider(CustomConfirmationService, mockConfirmation), - MockProvider(ToastService, mockToast), - provideMockStore({ signals: createDefaultSignals(opts.selectorOverrides) }), - ], - }); - - const store = TestBed.inject(Store); - const fixture = TestBed.createComponent(ReviewComponent); - const component = fixture.componentInstance; - fixture.detectChanges(); - - return { fixture, component, store, mockRouter, mockDialog, mockToast, mockConfirmation, dialogClose$ }; +interface SetupOverrides extends BaseSetupOverrides { + dialogCloseSubject?: Subject; } describe('ReviewComponent', () => { @@ -135,37 +67,88 @@ describe('ReviewComponent', () => { let mockDialog: CustomDialogServiceMockType; let mockToast: ToastServiceMockType; let mockConfirmation: CustomConfirmationServiceMockType; - let dialogClose$: Subject; + let dialogClose$: Subject; + + function setup(overrides: SetupOverrides = {}) { + mockRouter = RouterMockBuilder.create().withUrl('/registries/123/review').build(); + const mockActivatedRoute = ActivatedRouteMockBuilder.create().withParams({ id: 'draft-1' }).build(); + + dialogClose$ = overrides.dialogCloseSubject ?? new Subject(); + mockDialog = CustomDialogServiceMockBuilder.create() + .withOpen( + vi.fn().mockReturnValue({ + onClose: dialogClose$.pipe(), + close: vi.fn(), + }) + ) + .build(); + + mockToast = ToastServiceMock.simple(); + mockConfirmation = CustomConfirmationServiceMock.simple(); + + const defaultSignals: SignalOverride[] = [ + { selector: RegistriesSelectors.getPagesSchema, value: [] }, + { selector: RegistriesSelectors.getDraftRegistration, value: DEFAULT_DRAFT }, + { selector: RegistriesSelectors.isDraftLoading, value: false }, + { selector: RegistriesSelectors.getStepsData, value: {} }, + { selector: RegistriesSelectors.getRegistrationComponents, value: [] }, + { selector: RegistriesSelectors.isRegistrationComponentsLoading, value: false }, + { selector: LicensesSelectors.getLicense, value: null }, + { selector: RegistriesSelectors.getRegistration, value: { id: 'new-reg-1' } }, + { selector: RegistriesSelectors.getStepsState, value: { 0: { invalid: false } } }, + { selector: RegistriesSelectors.hasDraftAdminAccess, value: true }, + { selector: ContributorsSelectors.getContributors, value: [] }, + { selector: ContributorsSelectors.isContributorsLoading, value: false }, + { selector: ContributorsSelectors.hasMoreContributors, value: false }, + { selector: SubjectsSelectors.getSelectedSubjects, value: [] }, + ]; + + TestBed.configureTestingModule({ + imports: [ + ReviewComponent, + ...MockComponents(RegistrationBlocksDataComponent, ContributorsListComponent, LicenseDisplayComponent), + ], + providers: [ + provideOSFCore(), + MockProvider(ActivatedRoute, mockActivatedRoute), + MockProvider(Router, mockRouter), + MockProvider(CustomDialogService, mockDialog), + MockProvider(CustomConfirmationService, mockConfirmation), + MockProvider(ToastService, mockToast), + provideMockStore({ + signals: mergeSignalOverrides(defaultSignals, overrides.selectorOverrides), + }), + ], + }); + + store = TestBed.inject(Store); + const fixture = TestBed.createComponent(ReviewComponent); + component = fixture.componentInstance; + fixture.detectChanges(); + } beforeEach(() => { - const result = setup(); - component = result.component; - store = result.store; - mockRouter = result.mockRouter; - mockDialog = result.mockDialog; - mockToast = result.mockToast; - mockConfirmation = result.mockConfirmation; - dialogClose$ = result.dialogClose$; + setup(); }); it('should create', () => { expect(component).toBeTruthy(); }); - it('should dispatch getContributors, getSubjects and fetchLicenses on init', () => { + it('should dispatch getContributors, getSubjects and fetchLicense on init', () => { expect(store.dispatch).toHaveBeenCalledWith(new GetAllContributors('draft-1', ResourceType.DraftRegistration)); expect(store.dispatch).toHaveBeenCalledWith(new FetchSelectedSubjects('draft-1', ResourceType.DraftRegistration)); - expect(store.dispatch).toHaveBeenCalledWith(new FetchLicenses('prov-1')); + expect(store.dispatch).toHaveBeenCalledWith(new FetchLicense('lic-1')); }); it('should navigate to previous step on goBack', () => { - const { component: c, mockRouter: router } = setup({ + setup({ selectorOverrides: [{ selector: RegistriesSelectors.getPagesSchema, value: [{ id: '1' }, { id: '2' }] }], }); - c.goBack(); + component.goBack(); - expect(router.navigate).toHaveBeenCalledWith( + expect(mockRouter.navigate).toHaveBeenCalledWith( ['../', 2], expect.objectContaining({ relativeTo: expect.anything() }) ); @@ -181,7 +164,7 @@ describe('ReviewComponent', () => { }); it('should dispatch deleteDraft and navigate on confirm', () => { - mockConfirmation.confirmDelete.mockImplementation(({ onConfirm }: any) => onConfirm()); + mockConfirmation.confirmDelete.mockImplementation(({ onConfirm }) => onConfirm?.()); (store.dispatch as Mock).mockClear(); component.deleteDraft(); @@ -192,14 +175,14 @@ describe('ReviewComponent', () => { }); it('should open select components dialog when components exist', () => { - const { component: c, mockDialog: dialog } = setup({ + setup({ selectorOverrides: [{ selector: RegistriesSelectors.getRegistrationComponents, value: [{ id: 'comp-1' }] }], }); - c.confirmRegistration(); + component.confirmRegistration(); - expect(dialog.open).toHaveBeenCalled(); - const firstCallArgs = (dialog.open as Mock).mock.calls[0]; + expect(mockDialog.open).toHaveBeenCalled(); + const firstCallArgs = (mockDialog.open as Mock).mock.calls[0]; expect(firstCallArgs[1].header).toBe('registries.review.selectComponents.title'); }); @@ -220,18 +203,14 @@ describe('ReviewComponent', () => { }); it('should reopen select components dialog when confirm dialog closed with falsy result and components exist', () => { - const { - component: c, - mockDialog: dialog, - dialogClose$: close$, - } = setup({ + setup({ selectorOverrides: [{ selector: RegistriesSelectors.getRegistrationComponents, value: [{ id: 'comp-1' }] }], }); - c.openConfirmRegistrationDialog(['comp-1']); - close$.next(false); + component.openConfirmRegistrationDialog(['comp-1']); + dialogClose$.next(false); - expect(dialog.open).toHaveBeenCalledTimes(2); + expect(mockDialog.open).toHaveBeenCalledTimes(2); }); it('should not navigate when confirm dialog closed with falsy result and no components', () => { @@ -242,44 +221,44 @@ describe('ReviewComponent', () => { }); it('should pass selected components from select dialog to confirm dialog', () => { - const selectClose$ = new Subject(); - const confirmClose$ = new Subject(); + const selectClose$ = new Subject(); + const confirmClose$ = new Subject(); let callCount = 0; - const { component: c, mockDialog: dialog } = setup({ + setup({ selectorOverrides: [{ selector: RegistriesSelectors.getRegistrationComponents, value: [{ id: 'comp-1' }] }], }); - (dialog.open as Mock).mockImplementation(() => { + (mockDialog.open as Mock).mockImplementation(() => { callCount++; const subj = callCount === 1 ? selectClose$ : confirmClose$; return { onClose: subj.pipe(), close: vi.fn() }; }); - c.openSelectComponentsForRegistrationDialog(); + component.openSelectComponentsForRegistrationDialog(); selectClose$.next(['comp-1']); - expect(dialog.open).toHaveBeenCalledTimes(2); - const secondCallArgs = (dialog.open as Mock).mock.calls[1]; + expect(mockDialog.open).toHaveBeenCalledTimes(2); + const secondCallArgs = (mockDialog.open as Mock).mock.calls[1]; expect(secondCallArgs[1].data.components).toEqual(['comp-1']); }); it('should not open confirm dialog when select components dialog returns falsy', () => { - const selectClose$ = new Subject(); + const selectClose$ = new Subject(); - const { component: c, mockDialog: dialog } = setup({ + setup({ selectorOverrides: [{ selector: RegistriesSelectors.getRegistrationComponents, value: [{ id: 'comp-1' }] }], }); - (dialog.open as Mock).mockReturnValue({ + (mockDialog.open as Mock).mockReturnValue({ onClose: selectClose$.pipe(), close: vi.fn(), }); - c.openSelectComponentsForRegistrationDialog(); + component.openSelectComponentsForRegistrationDialog(); selectClose$.next(null); - expect(dialog.open).toHaveBeenCalledTimes(1); + expect(mockDialog.open).toHaveBeenCalledTimes(1); }); it('should dispatch loadMoreContributors', () => { @@ -299,10 +278,10 @@ describe('ReviewComponent', () => { }); it('should compute isDraftInvalid as true when any step is invalid', () => { - const { component: c } = setup({ + setup({ selectorOverrides: [{ selector: RegistriesSelectors.getStepsState, value: { 0: { invalid: true } } }], }); - expect(c.isDraftInvalid()).toBe(true); + expect(component.isDraftInvalid()).toBe(true); }); it('should compute registerButtonDisabled as false when valid and has admin access', () => { @@ -310,36 +289,43 @@ describe('ReviewComponent', () => { }); it('should compute registerButtonDisabled as true when draft is loading', () => { - const { component: c } = setup({ + setup({ selectorOverrides: [{ selector: RegistriesSelectors.isDraftLoading, value: true }], }); - expect(c.registerButtonDisabled()).toBe(true); + expect(component.registerButtonDisabled()).toBe(true); }); it('should compute registerButtonDisabled as true when draft is invalid', () => { - const { component: c } = setup({ + setup({ selectorOverrides: [{ selector: RegistriesSelectors.getStepsState, value: { 0: { invalid: true } } }], }); - expect(c.registerButtonDisabled()).toBe(true); + expect(component.registerButtonDisabled()).toBe(true); }); it('should compute registerButtonDisabled as true when no admin access', () => { - const { component: c } = setup({ + setup({ selectorOverrides: [{ selector: RegistriesSelectors.hasDraftAdminAccess, value: false }], }); - expect(c.registerButtonDisabled()).toBe(true); + expect(component.registerButtonDisabled()).toBe(true); + }); + + it('should compute registerButtonDisabled as true when registration components are loading', () => { + setup({ + selectorOverrides: [{ selector: RegistriesSelectors.isRegistrationComponentsLoading, value: true }], + }); + expect(component.registerButtonDisabled()).toBe(true); }); it('should compute licenseOptionsRecord from draft license options', () => { - const { component: c } = setup({ + setup({ selectorOverrides: [ { selector: RegistriesSelectors.getDraftRegistration, - value: { ...DEFAULT_DRAFT, license: { options: { year: '2026', copyright: 'Test' } } }, + value: { ...DEFAULT_DRAFT, license: { id: 'lic-1', options: { year: '2026', copyright: 'Test' } } }, }, ], }); - expect(c.licenseOptionsRecord()).toEqual({ year: '2026', copyright: 'Test' }); + expect(component.licenseOptionsRecord()).toEqual({ year: '2026', copyright: 'Test' }); }); it('should compute licenseOptionsRecord as empty when no license options', () => { @@ -356,7 +342,7 @@ describe('ReviewComponent', () => { }); it('should set projectId to null when branchedFrom type is not nodes', () => { - const { component: c, mockDialog: dialog } = setup({ + setup({ selectorOverrides: [ { selector: RegistriesSelectors.getDraftRegistration, @@ -365,9 +351,9 @@ describe('ReviewComponent', () => { ], }); - c.openConfirmRegistrationDialog(); + component.openConfirmRegistrationDialog(); - const callArgs = (dialog.open as Mock).mock.calls[0]; + const callArgs = (mockDialog.open as Mock).mock.calls[0]; expect(callArgs[1].data.projectId).toBeNull(); }); @@ -379,24 +365,19 @@ describe('ReviewComponent', () => { }); it('should not navigate after registration when newRegistration has no id', () => { - const { - component: c, - mockRouter: router, - mockToast: toast, - dialogClose$: close$, - } = setup({ + setup({ selectorOverrides: [{ selector: RegistriesSelectors.getRegistration, value: { id: null } }], }); - c.openConfirmRegistrationDialog(); - close$.next(true); + component.openConfirmRegistrationDialog(); + dialogClose$.next(true); - expect(toast.showSuccess).toHaveBeenCalled(); - expect(router.navigate).not.toHaveBeenCalled(); + expect(mockToast.showSuccess).toHaveBeenCalled(); + expect(mockRouter.navigate).not.toHaveBeenCalled(); }); it('should dispatch getProjectsComponents when draft hasProject is true', () => { - const { store: s } = setup({ + setup({ selectorOverrides: [ { selector: RegistriesSelectors.getDraftRegistration, @@ -405,11 +386,11 @@ describe('ReviewComponent', () => { ], }); - expect(s.dispatch).toHaveBeenCalledWith(new FetchProjectChildren('proj-1')); + expect(store.dispatch).toHaveBeenCalledWith(new FetchProjectChildren('proj-1')); }); - it('should dispatch getProjectsComponents with empty string when branchedFrom has no id', () => { - const { store: s } = setup({ + it('should not dispatch getProjectsComponents when branchedFrom has no id', () => { + setup({ selectorOverrides: [ { selector: RegistriesSelectors.getDraftRegistration, @@ -418,20 +399,6 @@ describe('ReviewComponent', () => { ], }); - expect(s.dispatch).toHaveBeenCalledWith(new FetchProjectChildren('')); - }); - - it('should not dispatch getProjectsComponents when isDraftSubmitting is true', () => { - const { store: s } = setup({ - selectorOverrides: [ - { selector: RegistriesSelectors.isDraftSubmitting, value: true }, - { - selector: RegistriesSelectors.getDraftRegistration, - value: { ...DEFAULT_DRAFT, hasProject: true }, - }, - ], - }); - - expect(s.dispatch).not.toHaveBeenCalledWith(expect.any(FetchProjectChildren)); + expect(store.dispatch).not.toHaveBeenCalledWith(expect.any(FetchProjectChildren)); }); }); diff --git a/src/app/features/registries/components/review/review.component.ts b/src/app/features/registries/components/review/review.component.ts index bc634acbb..a6e094e22 100644 --- a/src/app/features/registries/components/review/review.component.ts +++ b/src/app/features/registries/components/review/review.component.ts @@ -9,6 +9,7 @@ import { Tag } from 'primeng/tag'; import { filter, map } from 'rxjs'; +import { NgTemplateOutlet } from '@angular/common'; import { ChangeDetectionStrategy, Component, @@ -22,7 +23,6 @@ import { import { takeUntilDestroyed, toSignal } from '@angular/core/rxjs-interop'; import { ActivatedRoute, Router } from '@angular/router'; -import { ENVIRONMENT } from '@core/provider/environment.provider'; import { ContributorsListComponent } from '@osf/shared/components/contributors-list/contributors-list.component'; import { LicenseDisplayComponent } from '@osf/shared/components/license-display/license-display.component'; import { RegistrationBlocksDataComponent } from '@osf/shared/components/registration-blocks-data/registration-blocks-data.component'; @@ -37,15 +37,17 @@ import { LoadMoreContributors, ResetContributorsState, } from '@osf/shared/stores/contributors'; +import { FetchLicense, LicensesSelectors } from '@osf/shared/stores/licenses'; import { FetchSelectedSubjects, SubjectsSelectors } from '@osf/shared/stores/subjects'; -import { ClearState, DeleteDraft, FetchLicenses, FetchProjectChildren, RegistriesSelectors } from '../../store'; +import { ClearState, DeleteDraft, FetchProjectChildren, RegistriesSelectors } from '../../store'; import { ConfirmRegistrationDialogComponent } from '../confirm-registration-dialog/confirm-registration-dialog.component'; import { SelectComponentsDialogComponent } from '../select-components-dialog/select-components-dialog.component'; @Component({ selector: 'osf-review', imports: [ + NgTemplateOutlet, TranslatePipe, Card, Message, @@ -66,15 +68,14 @@ export class ReviewComponent implements OnDestroy { private readonly customDialogService = inject(CustomDialogService); private readonly toastService = inject(ToastService); private readonly destroyRef = inject(DestroyRef); - private readonly environment = inject(ENVIRONMENT); readonly pages = select(RegistriesSelectors.getPagesSchema); readonly draftRegistration = select(RegistriesSelectors.getDraftRegistration); - readonly isDraftSubmitting = select(RegistriesSelectors.isDraftSubmitting); readonly isDraftLoading = select(RegistriesSelectors.isDraftLoading); readonly stepsData = select(RegistriesSelectors.getStepsData); readonly components = select(RegistriesSelectors.getRegistrationComponents); - readonly license = select(RegistriesSelectors.getRegistrationLicense); + readonly isRegistrationComponentsLoading = select(RegistriesSelectors.isRegistrationComponentsLoading); + readonly license = select(LicensesSelectors.getLicense); readonly newRegistration = select(RegistriesSelectors.getRegistration); readonly stepsState = select(RegistriesSelectors.getStepsState); readonly contributors = select(ContributorsSelectors.getContributors); @@ -89,7 +90,7 @@ export class ReviewComponent implements OnDestroy { deleteDraft: DeleteDraft, clearState: ClearState, getProjectsComponents: FetchProjectChildren, - fetchLicenses: FetchLicenses, + fetchLicense: FetchLicense, loadMoreContributors: LoadMoreContributors, resetContributorsState: ResetContributorsState, }); @@ -97,17 +98,14 @@ export class ReviewComponent implements OnDestroy { readonly INPUT_VALIDATION_MESSAGES = INPUT_VALIDATION_MESSAGES; private readonly draftId = toSignal(this.route.params.pipe(map((params) => params['id']))); - - private readonly resolvedProviderId = computed(() => { - const draft = this.draftRegistration(); - return draft ? (draft.providerId ?? this.environment.defaultProvider) : undefined; - }); - private readonly componentsLoaded = signal(false); isDraftInvalid = computed(() => Object.values(this.stepsState()).some((step) => step.invalid)); licenseOptionsRecord = computed(() => (this.draftRegistration()?.license.options ?? {}) as Record); - registerButtonDisabled = computed(() => this.isDraftLoading() || this.isDraftInvalid() || !this.hasAdminAccess()); + registerButtonDisabled = computed( + () => + this.isDraftLoading() || this.isRegistrationComponentsLoading() || this.isDraftInvalid() || !this.hasAdminAccess() + ); constructor() { if (!this.contributors()?.length) { @@ -119,21 +117,18 @@ export class ReviewComponent implements OnDestroy { } effect(() => { - const providerId = this.resolvedProviderId(); - - if (providerId) { - this.actions.fetchLicenses(providerId); - } + this.actions.fetchLicense(this.draftRegistration()?.license?.id); }); effect(() => { - if (!this.isDraftSubmitting() && !this.componentsLoaded()) { - const draft = this.draftRegistration(); - if (draft?.hasProject) { - this.actions.getProjectsComponents(draft.branchedFrom?.id ?? ''); - this.componentsLoaded.set(true); - } + const projectId = this.draftRegistration()?.hasProject ? this.draftRegistration()?.branchedFrom?.id : undefined; + + if (!projectId || this.componentsLoaded()) { + return; } + + this.componentsLoaded.set(true); + this.actions.getProjectsComponents(projectId); }); } diff --git a/src/app/features/registries/mappers/index.ts b/src/app/features/registries/mappers/index.ts deleted file mode 100644 index 8c8a64cf3..000000000 --- a/src/app/features/registries/mappers/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './licenses.mapper'; diff --git a/src/app/features/registries/mappers/licenses.mapper.ts b/src/app/features/registries/mappers/licenses.mapper.ts deleted file mode 100644 index afac806d9..000000000 --- a/src/app/features/registries/mappers/licenses.mapper.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { LicenseModel } from '@osf/shared/models/license/license.model'; -import { LicensesResponseJsonApi } from '@osf/shared/models/license/licenses-json-api.model'; - -export class LicensesMapper { - static fromLicensesResponse(response: LicensesResponseJsonApi): LicenseModel[] { - return response.data.map((item) => ({ - id: item.id, - name: item.attributes.name, - requiredFields: item.attributes.required_fields, - url: item.attributes.url, - text: item.attributes.text, - })); - } -} diff --git a/src/app/features/registries/models/attached-file.model.ts b/src/app/features/registries/models/attached-file.model.ts index 458dac9cf..acc6d3b39 100644 --- a/src/app/features/registries/models/attached-file.model.ts +++ b/src/app/features/registries/models/attached-file.model.ts @@ -1,3 +1,3 @@ -import { FileModel } from '@osf/shared/models/files/file.model'; +import { FilePayloadJsonApi } from '@osf/shared/models/files/file-payload-json-api.model'; -export type AttachedFile = Partial; +export type AttachedFile = FilePayloadJsonApi & { name: string }; diff --git a/src/app/features/registries/services/registrations-licenses.service.spec.ts b/src/app/features/registries/services/registrations-licenses.service.spec.ts new file mode 100644 index 000000000..f3d958fdd --- /dev/null +++ b/src/app/features/registries/services/registrations-licenses.service.spec.ts @@ -0,0 +1,109 @@ +import { MockProvider } from 'ng-mocks'; + +import { firstValueFrom, of } from 'rxjs'; + +import { TestBed } from '@angular/core/testing'; + +import { RegistrationMapper } from '@osf/shared/mappers/registration'; +import { LicenseOptions } from '@osf/shared/models/license/license.model'; +import { DraftRegistrationModel } from '@osf/shared/models/registration/draft-registration.model'; +import { DraftRegistrationDataJsonApi } from '@osf/shared/models/registration/registration-json-api.model'; +import { JsonApiService } from '@osf/shared/services/json-api.service'; + +import { MOCK_DRAFT_REGISTRATION } from '@testing/mocks/registries.mock'; +import { MOCK_API_URL, provideMockEnvironment } from '@testing/providers/environment.provider.mock'; +import { JsonApiServiceMock, JsonApiServiceMockType } from '@testing/providers/json-api.service.mock'; + +import { RegistrationsLicenseService } from './registrations-licenses.service'; + +describe('RegistrationsLicenseService', () => { + let service: RegistrationsLicenseService; + let jsonApiService: JsonApiServiceMockType; + + const registrationId = 'draft-1'; + const licenseId = 'license-123'; + const apiResponse = { id: registrationId } as DraftRegistrationDataJsonApi; + const mappedDraft = MOCK_DRAFT_REGISTRATION as DraftRegistrationModel; + + function setup() { + jsonApiService = JsonApiServiceMock.simple(); + + TestBed.configureTestingModule({ + providers: [RegistrationsLicenseService, MockProvider(JsonApiService, jsonApiService), provideMockEnvironment()], + }); + + service = TestBed.inject(RegistrationsLicenseService); + } + + it('should expose apiUrl from environment', () => { + setup(); + + expect(service.apiUrl).toBe(MOCK_API_URL); + }); + + it('updateLicense should patch with empty node_license when options are omitted', async () => { + setup(); + const mapperSpy = vi.spyOn(RegistrationMapper, 'fromDraftRegistrationResponse').mockReturnValue(mappedDraft); + jsonApiService.patch.mockReturnValue(of(apiResponse)); + + const response = await firstValueFrom(service.updateLicense(registrationId, licenseId)); + + expect(jsonApiService.patch).toHaveBeenCalledWith(`${MOCK_API_URL}/draft_registrations/${registrationId}/`, { + data: { + type: 'draft_registrations', + id: registrationId, + relationships: { + license: { + data: { + id: licenseId, + type: 'licenses', + }, + }, + }, + attributes: { + node_license: { + copyright_holders: [], + year: '', + }, + }, + }, + }); + expect(mapperSpy).toHaveBeenCalledWith(apiResponse); + expect(response).toEqual(mappedDraft); + }); + + it('updateLicense should patch with node_license when options are provided', async () => { + setup(); + const licenseOptions: LicenseOptions = { + copyrightHolders: 'John Doe', + year: '2023', + }; + const mapperSpy = vi.spyOn(RegistrationMapper, 'fromDraftRegistrationResponse').mockReturnValue(mappedDraft); + jsonApiService.patch.mockReturnValue(of(apiResponse)); + + const response = await firstValueFrom(service.updateLicense(registrationId, licenseId, licenseOptions)); + + expect(jsonApiService.patch).toHaveBeenCalledWith(`${MOCK_API_URL}/draft_registrations/${registrationId}/`, { + data: { + type: 'draft_registrations', + id: registrationId, + relationships: { + license: { + data: { + id: licenseId, + type: 'licenses', + }, + }, + }, + attributes: { + node_license: { + copyright_holders: [licenseOptions.copyrightHolders], + year: licenseOptions.year, + }, + }, + }, + }); + expect(mapperSpy).toHaveBeenCalledWith(apiResponse); + expect(response).toEqual(mappedDraft); + }); +}); diff --git a/src/app/features/registries/services/registrations-licenses.service.ts b/src/app/features/registries/services/registrations-licenses.service.ts index 6d0317db9..4377c197b 100644 --- a/src/app/features/registries/services/registrations-licenses.service.ts +++ b/src/app/features/registries/services/registrations-licenses.service.ts @@ -4,8 +4,7 @@ import { inject, Injectable } from '@angular/core'; import { ENVIRONMENT } from '@core/provider/environment.provider'; import { RegistrationMapper } from '@osf/shared/mappers/registration'; -import { LicenseModel, LicenseOptions } from '@osf/shared/models/license/license.model'; -import { LicensesResponseJsonApi } from '@osf/shared/models/license/licenses-json-api.model'; +import { LicenseOptions } from '@osf/shared/models/license/license.model'; import { DraftRegistrationModel } from '@osf/shared/models/registration/draft-registration.model'; import { CreateRegistrationPayloadJsonApi, @@ -13,8 +12,6 @@ import { } from '@osf/shared/models/registration/registration-json-api.model'; import { JsonApiService } from '@osf/shared/services/json-api.service'; -import { LicensesMapper } from '../mappers'; - @Injectable({ providedIn: 'root', }) @@ -26,14 +23,6 @@ export class RegistrationsLicenseService { return `${this.environment.apiDomainUrl}/v2`; } - getLicenses(providerId: string): Observable { - return this.jsonApiService - .get(`${this.apiUrl}/providers/registrations/${providerId}/licenses/`, { - 'page[size]': 100, - }) - .pipe(map((licenses) => LicensesMapper.fromLicensesResponse(licenses))); - } - updateLicense( registrationId: string, licenseId: string, diff --git a/src/app/features/registries/store/handlers/licenses.handlers.ts b/src/app/features/registries/store/handlers/licenses.handlers.ts index 1ba7b8a68..09f486329 100644 --- a/src/app/features/registries/store/handlers/licenses.handlers.ts +++ b/src/app/features/registries/store/handlers/licenses.handlers.ts @@ -1,10 +1,11 @@ import { StateContext } from '@ngxs/store'; -import { catchError, tap } from 'rxjs'; +import { catchError, EMPTY, tap } from 'rxjs'; import { inject, Injectable } from '@angular/core'; import { handleSectionError } from '@osf/shared/helpers/state-error.handler'; +import { LicensesService } from '@osf/shared/services/licenses.service'; import { RegistrationsLicenseService } from '../../services/registrations-licenses.service'; import { SaveLicense } from '../registries.actions'; @@ -13,8 +14,13 @@ import { RegistriesStateModel } from '../registries.model'; @Injectable() export class LicensesHandlers { registrationsLicenseService = inject(RegistrationsLicenseService); + licensesService = inject(LicensesService); + + fetchLicenses(ctx: StateContext, licensesUrl?: string) { + if (!licensesUrl) { + return EMPTY; + } - fetchLicenses(ctx: StateContext, providerId: string) { ctx.patchState({ licenses: { ...ctx.getState().licenses, @@ -22,7 +28,7 @@ export class LicensesHandlers { }, }); - return this.registrationsLicenseService.getLicenses(providerId).pipe( + return this.licensesService.getLicenses(licensesUrl).pipe( tap((licenses) => { ctx.patchState({ licenses: { diff --git a/src/app/features/registries/store/handlers/projects.handlers.ts b/src/app/features/registries/store/handlers/projects.handlers.ts index 88562a02a..8bacd1f1d 100644 --- a/src/app/features/registries/store/handlers/projects.handlers.ts +++ b/src/app/features/registries/store/handlers/projects.handlers.ts @@ -47,10 +47,13 @@ export class ProjectsHandlers { } fetchProjectChildren(ctx: StateContext, projectId: string) { - const state = ctx.getState(); + if (!projectId) { + return; + } + ctx.patchState({ - draftRegistration: { - data: state.draftRegistration.data, + registrationComponents: { + data: [], isLoading: true, error: null, }, @@ -59,17 +62,14 @@ export class ProjectsHandlers { return this.projectsService.getComponentsTree(projectId).subscribe({ next: (children: ProjectShortInfoModel[]) => { ctx.patchState({ - draftRegistration: { - data: { - ...state.draftRegistration.data!, - components: [...state.draftRegistration.data!.components, ...children], - }, + registrationComponents: { + data: children, isLoading: false, error: null, }, }); }, - error: (error) => handleSectionError(ctx, 'draftRegistration', error), + error: (error) => handleSectionError(ctx, 'registrationComponents', error), }); } } diff --git a/src/app/features/registries/store/registries.actions.ts b/src/app/features/registries/store/registries.actions.ts index 25a553773..58c2c261a 100644 --- a/src/app/features/registries/store/registries.actions.ts +++ b/src/app/features/registries/store/registries.actions.ts @@ -75,7 +75,7 @@ export class FetchSchemaBlocks { export class FetchLicenses { static readonly type = '[Registries] Fetch Licenses'; - constructor(public providerId: string) {} + constructor(public licensesUrl?: string) {} } export class SaveLicense { diff --git a/src/app/features/registries/store/registries.model.ts b/src/app/features/registries/store/registries.model.ts index 4542aaa96..ed18d3d02 100644 --- a/src/app/features/registries/store/registries.model.ts +++ b/src/app/features/registries/store/registries.model.ts @@ -18,6 +18,7 @@ export interface RegistriesStateModel { projects: AsyncStateModel; draftRegistration: AsyncStateModel; registration: AsyncStateModel; + registrationComponents: AsyncStateModel; registries: AsyncStateModel; licenses: AsyncStateModel; pagesSchema: AsyncStateModel; @@ -70,6 +71,11 @@ export const REGISTRIES_STATE_DEFAULTS: RegistriesStateModel = { isSubmitting: false, error: null, }, + registrationComponents: { + data: [], + isLoading: false, + error: null, + }, draftRegistrations: { data: [], isLoading: false, diff --git a/src/app/features/registries/store/registries.selectors.ts b/src/app/features/registries/store/registries.selectors.ts index e75242bf2..34b563634 100644 --- a/src/app/features/registries/store/registries.selectors.ts +++ b/src/app/features/registries/store/registries.selectors.ts @@ -83,11 +83,6 @@ export class RegistriesSelectors { return state.draftRegistration.data?.license || null; } - @Selector([RegistriesState]) - static getRegistrationLicense(state: RegistriesStateModel): LicenseModel | null { - return state.licenses.data.find((l) => l.id === state.draftRegistration.data?.license.id) || null; - } - @Selector([RegistriesState]) static getPagesSchema(state: RegistriesStateModel): PageSchema[] { return state.pagesSchema.data; @@ -165,7 +160,12 @@ export class RegistriesSelectors { @Selector([RegistriesState]) static getRegistrationComponents(state: RegistriesStateModel) { - return state.draftRegistration.data?.components || []; + return state.registrationComponents.data; + } + + @Selector([RegistriesState]) + static isRegistrationComponentsLoading(state: RegistriesStateModel): boolean { + return state.registrationComponents.isLoading; } @Selector([RegistriesState]) diff --git a/src/app/features/registries/store/registries.state.ts b/src/app/features/registries/store/registries.state.ts index c2373159c..36c72356a 100644 --- a/src/app/features/registries/store/registries.state.ts +++ b/src/app/features/registries/store/registries.state.ts @@ -276,8 +276,8 @@ export class RegistriesState { } @Action(FetchLicenses) - fetchLicenses(ctx: StateContext, { providerId }: FetchLicenses) { - return this.licensesHandler.fetchLicenses(ctx, providerId); + fetchLicenses(ctx: StateContext, { licensesUrl }: FetchLicenses) { + return this.licensesHandler.fetchLicenses(ctx, licensesUrl); } @Action(SaveLicense) diff --git a/src/app/features/registry/components/registry-overview-metadata/registry-overview-metadata.component.spec.ts b/src/app/features/registry/components/registry-overview-metadata/registry-overview-metadata.component.spec.ts index 61eb29f5c..36ccb7b67 100644 --- a/src/app/features/registry/components/registry-overview-metadata/registry-overview-metadata.component.spec.ts +++ b/src/app/features/registry/components/registry-overview-metadata/registry-overview-metadata.component.spec.ts @@ -2,8 +2,6 @@ import { Store } from '@ngxs/store'; import { MockComponents, MockProvider } from 'ng-mocks'; -import { of } from 'rxjs'; - import { Mock } from 'vitest'; import { TestBed } from '@angular/core/testing'; @@ -20,19 +18,24 @@ import { SubjectsListComponent } from '@osf/shared/components/subjects-list/subj import { TagsListComponent } from '@osf/shared/components/tags-list/tags-list.component'; import { ResourceType } from '@osf/shared/enums/resource-type.enum'; import { ContributorsSelectors, LoadMoreBibliographicContributors } from '@osf/shared/stores/contributors'; +import { FetchLicense, LicensesSelectors } from '@osf/shared/stores/licenses'; import { RegistrationProviderSelectors } from '@osf/shared/stores/registration-provider'; import { FetchSelectedSubjects, SubjectsSelectors } from '@osf/shared/stores/subjects'; import { MOCK_REGISTRATION_OVERVIEW_MODEL } from '@testing/mocks/registration-overview-model.mock'; import { provideOSFCore } from '@testing/osf.testing.provider'; import { ActivatedRouteMockBuilder } from '@testing/providers/route-provider.mock'; -import { RouterMockBuilder } from '@testing/providers/router-provider.mock'; -import { provideMockStore } from '@testing/providers/store-provider.mock'; +import { RouterMockBuilder, RouterMockType } from '@testing/providers/router-provider.mock'; +import { + BaseSetupOverrides, + mergeSignalOverrides, + provideMockStore, + SignalOverride, +} from '@testing/providers/store-provider.mock'; import { GetRegistryIdentifiers, GetRegistryInstitutions, - GetRegistryLicense, RegistrySelectors, SetRegistryCustomCitation, } from '../../store/registry'; @@ -41,97 +44,97 @@ import { RegistryOverviewMetadataComponent } from './registry-overview-metadata. const MOCK_REGISTRY = { ...MOCK_REGISTRATION_OVERVIEW_MODEL, id: 'registry-123', licenseId: 'license-123' }; -interface SetupOverrides { +interface SetupOverrides extends BaseSetupOverrides { registry?: typeof MOCK_REGISTRY | null; } -function setup(overrides: SetupOverrides = {}) { - const registryValue = 'registry' in overrides ? overrides.registry! : MOCK_REGISTRY; - const mockRouter = RouterMockBuilder.create().build(); - - TestBed.configureTestingModule({ - imports: [ - RegistryOverviewMetadataComponent, - ...MockComponents( - ResourceCitationsComponent, - AffiliatedInstitutionsViewComponent, - ContributorsListComponent, - ResourceDoiComponent, - ResourceLicenseComponent, - SubjectsListComponent, - TagsListComponent, - FundersListComponent - ), - ], - providers: [ - provideOSFCore(), - MockProvider(ActivatedRoute, ActivatedRouteMockBuilder.create().build()), - MockProvider(Router, mockRouter), - provideMockStore({ - signals: [ - { selector: RegistrySelectors.getRegistry, value: registryValue }, - { selector: RegistrySelectors.isRegistryAnonymous, value: false }, - { selector: RegistrySelectors.hasWriteAccess, value: true }, - { selector: RegistrySelectors.getLicense, value: null }, - { selector: RegistrySelectors.isLicenseLoading, value: false }, - { selector: RegistrySelectors.getIdentifiers, value: [] }, - { selector: RegistrySelectors.isIdentifiersLoading, value: false }, - { selector: RegistrySelectors.getInstitutions, value: [] }, - { selector: RegistrySelectors.isInstitutionsLoading, value: false }, - { selector: RegistrationProviderSelectors.getBrandedProvider, value: null }, - { selector: SubjectsSelectors.getSelectedSubjects, value: [] }, - { selector: SubjectsSelectors.areSelectedSubjectsLoading, value: false }, - { selector: ContributorsSelectors.getBibliographicContributors, value: [] }, - { selector: ContributorsSelectors.isBibliographicContributorsLoading, value: false }, - { selector: ContributorsSelectors.hasMoreBibliographicContributors, value: false }, - { selector: MetadataSelectors.getCustomItemMetadata, value: null }, - { selector: MetadataSelectors.isCustomItemMetadataLoading, value: false }, - ], - }), - ], - }); +describe('RegistryOverviewMetadataComponent', () => { + let store: Store; + let mockRouter: RouterMockType; + + function setup(overrides: SetupOverrides = {}) { + const registryValue = 'registry' in overrides ? overrides.registry! : MOCK_REGISTRY; + mockRouter = RouterMockBuilder.create().build(); + + const defaultSignals: SignalOverride[] = [ + { selector: RegistrySelectors.getRegistry, value: registryValue }, + { selector: RegistrySelectors.isRegistryAnonymous, value: false }, + { selector: RegistrySelectors.hasWriteAccess, value: true }, + { selector: LicensesSelectors.getLicense, value: null }, + { selector: LicensesSelectors.isLicenseLoading, value: false }, + { selector: RegistrySelectors.getIdentifiers, value: [] }, + { selector: RegistrySelectors.isIdentifiersLoading, value: false }, + { selector: RegistrySelectors.getInstitutions, value: [] }, + { selector: RegistrySelectors.isInstitutionsLoading, value: false }, + { selector: RegistrationProviderSelectors.getBrandedProvider, value: null }, + { selector: SubjectsSelectors.getSelectedSubjects, value: [] }, + { selector: SubjectsSelectors.areSelectedSubjectsLoading, value: false }, + { selector: ContributorsSelectors.getBibliographicContributors, value: [] }, + { selector: ContributorsSelectors.isBibliographicContributorsLoading, value: false }, + { selector: ContributorsSelectors.hasMoreBibliographicContributors, value: false }, + { selector: MetadataSelectors.getCustomItemMetadata, value: null }, + { selector: MetadataSelectors.isCustomItemMetadataLoading, value: false }, + ]; + + TestBed.configureTestingModule({ + imports: [ + RegistryOverviewMetadataComponent, + ...MockComponents( + ResourceCitationsComponent, + AffiliatedInstitutionsViewComponent, + ContributorsListComponent, + ResourceDoiComponent, + ResourceLicenseComponent, + SubjectsListComponent, + TagsListComponent, + FundersListComponent + ), + ], + providers: [ + provideOSFCore(), + MockProvider(ActivatedRoute, ActivatedRouteMockBuilder.create().build()), + MockProvider(Router, mockRouter), + provideMockStore({ + signals: mergeSignalOverrides(defaultSignals, overrides.selectorOverrides), + }), + ], + }); - const store = TestBed.inject(Store); - const fixture = TestBed.createComponent(RegistryOverviewMetadataComponent); - fixture.detectChanges(); + store = TestBed.inject(Store); + const fixture = TestBed.createComponent(RegistryOverviewMetadataComponent); + fixture.detectChanges(); - return { fixture, component: fixture.componentInstance, store, mockRouter }; -} + return { fixture, component: fixture.componentInstance }; + } -describe('RegistryOverviewMetadataComponent', () => { it('should dispatch all init actions when registry exists', () => { - const { store } = setup(); - - expect(store.dispatch).toHaveBeenCalledWith(expect.objectContaining({ registryId: 'registry-123' })); - expect(store.dispatch).toHaveBeenCalledWith(expect.any(GetRegistryInstitutions)); - expect(store.dispatch).toHaveBeenCalledWith(expect.any(FetchSelectedSubjects)); - expect(store.dispatch).toHaveBeenCalledWith(expect.any(GetRegistryLicense)); - expect(store.dispatch).toHaveBeenCalledWith(expect.any(GetRegistryIdentifiers)); - expect(store.dispatch).toHaveBeenCalledWith(expect.any(GetCustomItemMetadata)); + setup(); + + expect(store.dispatch).toHaveBeenCalledWith(new GetRegistryInstitutions('registry-123')); + expect(store.dispatch).toHaveBeenCalledWith(new FetchSelectedSubjects('registry-123', ResourceType.Registration)); + expect(store.dispatch).toHaveBeenCalledWith(new FetchLicense('license-123')); + expect(store.dispatch).toHaveBeenCalledWith(new GetRegistryIdentifiers('registry-123')); + expect(store.dispatch).toHaveBeenCalledWith(new GetCustomItemMetadata('registry-123')); }); it('should not dispatch init actions when registry is null', () => { - const { store } = setup({ registry: null }); + setup({ registry: null }); expect(store.dispatch).not.toHaveBeenCalled(); }); it('should dispatch SetRegistryCustomCitation on onCustomCitationUpdated', () => { - const { component, store } = setup(); + const { component } = setup(); + (store.dispatch as Mock).mockClear(); component.onCustomCitationUpdated('Custom Citation'); - const call = (store.dispatch as Mock).mock.calls.find((c) => c[0] instanceof SetRegistryCustomCitation); - expect(call?.[0]).toBeInstanceOf(SetRegistryCustomCitation); - if (!call) { - throw new Error('SetRegistryCustomCitation dispatch call was not found'); - } - expect((call[0] as SetRegistryCustomCitation).citation).toBe('Custom Citation'); + expect(store.dispatch).toHaveBeenCalledWith(new SetRegistryCustomCitation('Custom Citation')); }); it('should dispatch LoadMoreBibliographicContributors on handleLoadMoreContributors', () => { - const { component, store } = setup(); - vi.spyOn(store, 'dispatch').mockReturnValue(of(undefined)); + const { component } = setup(); + (store.dispatch as Mock).mockClear(); component.handleLoadMoreContributors(); @@ -141,8 +144,8 @@ describe('RegistryOverviewMetadataComponent', () => { }); it('should not dispatch on handleLoadMoreContributors when registry is null', () => { - const { component, store } = setup({ registry: null }); - vi.spyOn(store, 'dispatch').mockReturnValue(of(undefined)); + const { component } = setup({ registry: null }); + (store.dispatch as Mock).mockClear(); component.handleLoadMoreContributors(); @@ -150,7 +153,7 @@ describe('RegistryOverviewMetadataComponent', () => { }); it('should navigate to search on tagClicked', () => { - const { component, mockRouter } = setup(); + const { component } = setup(); component.tagClicked('test-tag'); diff --git a/src/app/features/registry/components/registry-overview-metadata/registry-overview-metadata.component.ts b/src/app/features/registry/components/registry-overview-metadata/registry-overview-metadata.component.ts index 803b56e9b..23230208b 100644 --- a/src/app/features/registry/components/registry-overview-metadata/registry-overview-metadata.component.ts +++ b/src/app/features/registry/components/registry-overview-metadata/registry-overview-metadata.component.ts @@ -23,13 +23,13 @@ import { CurrentResourceType, ResourceType } from '@osf/shared/enums/resource-ty import { LanguageLabelPipe } from '@osf/shared/pipes/language-label.pipe'; import { ResourceTypeGeneralLabelPipe } from '@osf/shared/pipes/resource-type-general-label.pipe'; import { ContributorsSelectors, LoadMoreBibliographicContributors } from '@osf/shared/stores/contributors'; +import { FetchLicense, LicensesSelectors } from '@osf/shared/stores/licenses'; import { RegistrationProviderSelectors } from '@osf/shared/stores/registration-provider'; import { FetchSelectedSubjects, SubjectsSelectors } from '@osf/shared/stores/subjects'; import { GetRegistryIdentifiers, GetRegistryInstitutions, - GetRegistryLicense, RegistrySelectors, SetRegistryCustomCitation, } from '../../store/registry'; @@ -68,8 +68,8 @@ export class RegistryOverviewMetadataComponent { readonly isCustomItemMetadataLoading = select(MetadataSelectors.isCustomItemMetadataLoading); canEdit = select(RegistrySelectors.hasWriteAccess); - license = select(RegistrySelectors.getLicense); - isLicenseLoading = select(RegistrySelectors.isLicenseLoading); + license = select(LicensesSelectors.getLicense); + isLicenseLoading = select(LicensesSelectors.isLicenseLoading); identifiers = select(RegistrySelectors.getIdentifiers); isIdentifiersLoading = select(RegistrySelectors.isIdentifiersLoading); institutions = select(RegistrySelectors.getInstitutions); @@ -92,7 +92,7 @@ export class RegistryOverviewMetadataComponent { getSubjects: FetchSelectedSubjects, getInstitutions: GetRegistryInstitutions, getIdentifiers: GetRegistryIdentifiers, - getLicense: GetRegistryLicense, + getLicense: FetchLicense, getCustomItemMetadata: GetCustomItemMetadata, setCustomCitation: SetRegistryCustomCitation, loadMoreBibliographicContributors: LoadMoreBibliographicContributors, diff --git a/src/app/features/registry/registry.component.spec.ts b/src/app/features/registry/registry.component.spec.ts index 0736c97c7..47d5a93d7 100644 --- a/src/app/features/registry/registry.component.spec.ts +++ b/src/app/features/registry/registry.component.spec.ts @@ -18,6 +18,7 @@ import { DataciteService } from '@osf/shared/services/datacite/datacite.service' import { MetaTagsService } from '@osf/shared/services/meta-tags.service'; import { MetaTagsBuilderService } from '@osf/shared/services/meta-tags-builder.service'; import { ContributorsSelectors } from '@osf/shared/stores/contributors'; +import { LicensesSelectors } from '@osf/shared/stores/licenses'; import { CurrentResourceSelectors } from '@shared/stores/current-resource'; import { MOCK_REGISTRATION_OVERVIEW_MODEL } from '@testing/mocks/registration-overview-model.mock'; @@ -79,8 +80,8 @@ function setup(overrides: SetupOverrides = {}) { { selector: RegistrySelectors.getRegistry, value: registry }, { selector: RegistrySelectors.isRegistryLoading, value: false }, { selector: RegistrySelectors.getIdentifiers, value: identifiers }, - { selector: RegistrySelectors.getLicense, value: { name: 'MIT' } }, - { selector: RegistrySelectors.isLicenseLoading, value: false }, + { selector: LicensesSelectors.getLicense, value: { name: 'MIT' } }, + { selector: LicensesSelectors.isLicenseLoading, value: false }, { selector: ContributorsSelectors.getBibliographicContributors, value: [] }, { selector: ContributorsSelectors.isBibliographicContributorsLoading, value: false }, { selector: CurrentResourceSelectors.getCurrentResource, value: null }, diff --git a/src/app/features/registry/registry.component.ts b/src/app/features/registry/registry.component.ts index 70a7bf693..af2fc51b8 100644 --- a/src/app/features/registry/registry.component.ts +++ b/src/app/features/registry/registry.component.ts @@ -30,6 +30,7 @@ import { AnalyticsService } from '@osf/shared/services/analytics.service'; import { MetaTagsService } from '@osf/shared/services/meta-tags.service'; import { MetaTagsBuilderService } from '@osf/shared/services/meta-tags-builder.service'; import { ContributorsSelectors, GetBibliographicContributors } from '@osf/shared/stores/contributors'; +import { LicensesSelectors } from '@osf/shared/stores/licenses'; import { DataciteService } from '@shared/services/datacite/datacite.service'; import { CurrentResourceSelectors } from '@shared/stores/current-resource'; @@ -76,8 +77,8 @@ export class RegistryComponent implements OnDestroy { private readonly isBibliographicContributorsLoading = select( ContributorsSelectors.isBibliographicContributorsLoading ); - private readonly license = select(RegistrySelectors.getLicense); - private readonly isLicenseLoading = select(RegistrySelectors.isLicenseLoading); + private readonly license = select(LicensesSelectors.getLicense); + private readonly isLicenseLoading = select(LicensesSelectors.isLicenseLoading); private readonly canonicalPath = signal(this.getCanonicalPathFromSnapshot()); private readonly isFileDetailRoute = signal(this.isFileDetailRouteFromSnapshot()); diff --git a/src/app/features/registry/services/registry-overview.service.spec.ts b/src/app/features/registry/services/registry-overview.service.spec.ts new file mode 100644 index 000000000..bfb0c2d1d --- /dev/null +++ b/src/app/features/registry/services/registry-overview.service.spec.ts @@ -0,0 +1,338 @@ +import { MockProvider } from 'ng-mocks'; + +import { firstValueFrom, of } from 'rxjs'; + +import { TestBed } from '@angular/core/testing'; + +import { RegistryModerationMapper } from '@osf/features/moderation/mappers'; +import { ReviewAction, ReviewActionsResponseJsonApi } from '@osf/features/moderation/models'; +import { RegistrationReviewStates } from '@osf/shared/enums/registration-review-states.enum'; +import { RevisionReviewStates } from '@osf/shared/enums/revision-review-states.enum'; +import { IdentifiersMapper } from '@osf/shared/mappers/identifiers.mapper'; +import { InstitutionsMapper } from '@osf/shared/mappers/institutions'; +import { PageSchemaMapper, RegistrationMapper, RegistrationNodeMapper } from '@osf/shared/mappers/registration'; +import { ReviewActionsMapper } from '@osf/shared/mappers/review-actions.mapper'; +import { IdentifiersResponseJsonApi } from '@osf/shared/models/identifiers/identifier-json-api.model'; +import { InstitutionsJsonApiResponse } from '@osf/shared/models/institutions/institution-json-api.model'; +import { Institution } from '@osf/shared/models/institutions/institutions.model'; +import { SchemaBlocksResponseJsonApi } from '@osf/shared/models/registration/schema-blocks-json-api.model'; +import { + SchemaResponseJsonApi, + SchemaResponsesJsonApi, +} from '@osf/shared/models/registration/schema-response-json-api.model'; +import { ReviewActionPayload } from '@osf/shared/models/review-action/review-action-payload.model'; +import { ReviewActionPayloadJsonApi } from '@osf/shared/models/review-action/review-action-payload-json-api.model'; +import { JsonApiService } from '@osf/shared/services/json-api.service'; + +import { MOCK_INSTITUTION } from '@testing/mocks/institution.mock'; +import { MOCK_PROJECT_IDENTIFIERS } from '@testing/mocks/project-overview.mock'; +import { MOCK_REGISTRATION_OVERVIEW_MODEL } from '@testing/mocks/registration-overview-model.mock'; +import { MOCK_PAGES_SCHEMA } from '@testing/mocks/registries.mock'; +import { REVIEW_ACTION_MOCK } from '@testing/mocks/review-action.mock'; +import { createMockSchemaResponse } from '@testing/mocks/schema-response.mock'; +import { MOCK_API_URL, provideMockEnvironment } from '@testing/providers/environment.provider.mock'; +import { JsonApiServiceMock, JsonApiServiceMockType } from '@testing/providers/json-api.service.mock'; + +import { RegistrationOverviewDataJsonApi, RegistrationOverviewResponse } from '../models'; + +import { RegistryOverviewService } from './registry-overview.service'; + +describe('RegistryOverviewService', () => { + let service: RegistryOverviewService; + let jsonApiService: JsonApiServiceMockType; + + const registryId = 'registry-1'; + const registrationData = { + id: registryId, + attributes: { + pending_embargo_approval: false, + pending_embargo_termination_approval: false, + embargoed: false, + pending_registration_approval: false, + reviews_state: RegistrationReviewStates.Accepted, + revision_state: RevisionReviewStates.Approved, + }, + relationships: { + registered_from: { data: { id: 'project-1' } }, + registration_schema: { links: { related: { href: 'https://api.test/schema/' } } }, + license: { data: { id: 'license-1' } }, + provider: { data: { id: 'osf' } }, + root: { data: { id: 'root-1' } }, + forks: { links: { related: { meta: { count: 3 } } } }, + }, + } as RegistrationOverviewDataJsonApi; + const schemaResponse = createMockSchemaResponse('schema-response-1', RevisionReviewStates.Approved); + + function setup() { + jsonApiService = JsonApiServiceMock.simple(); + + TestBed.configureTestingModule({ + providers: [RegistryOverviewService, MockProvider(JsonApiService, jsonApiService), provideMockEnvironment()], + }); + + service = TestBed.inject(RegistryOverviewService); + } + + function stubRegistrationNodeMapper() { + return vi + .spyOn(RegistrationNodeMapper, 'getRegistrationNodeAttributes') + .mockReturnValue(MOCK_REGISTRATION_OVERVIEW_MODEL); + } + + it('should expose apiUrl from environment', () => { + setup(); + + expect(service.apiUrl).toBe(MOCK_API_URL); + }); + + it('getRegistrationById should request registration and map response', async () => { + setup(); + const apiResponse = { + data: registrationData, + meta: { anonymous: true }, + } as RegistrationOverviewResponse; + stubRegistrationNodeMapper(); + jsonApiService.get.mockReturnValue(of(apiResponse)); + + const response = await firstValueFrom(service.getRegistrationById(registryId)); + + expect(jsonApiService.get).toHaveBeenCalledWith(`${MOCK_API_URL}/registrations/${registryId}/`, { + related_counts: 'forks', + }); + expect(response.isAnonymous).toBe(true); + expect(response.registry).toEqual( + expect.objectContaining({ + id: MOCK_REGISTRATION_OVERVIEW_MODEL.id, + associatedProjectId: 'project-1', + providerId: 'osf', + licenseId: 'license-1', + forksCount: 3, + }) + ); + }); + + it('getRegistrationById should default isAnonymous to false when meta is missing', async () => { + setup(); + stubRegistrationNodeMapper(); + jsonApiService.get.mockReturnValue(of({ data: registrationData } as RegistrationOverviewResponse)); + + const response = await firstValueFrom(service.getRegistrationById(registryId)); + + expect(response.isAnonymous).toBe(false); + }); + + it('getInstitutions should request institutions and map response', async () => { + setup(); + const apiResponse = { data: [] } as unknown as InstitutionsJsonApiResponse; + const mappedInstitutions = [MOCK_INSTITUTION] as unknown as Institution[]; + const mapperSpy = vi.spyOn(InstitutionsMapper, 'fromInstitutionsResponse').mockReturnValue(mappedInstitutions); + jsonApiService.get.mockReturnValue(of(apiResponse)); + + const response = await firstValueFrom(service.getInstitutions(registryId)); + + expect(jsonApiService.get).toHaveBeenCalledWith(`${MOCK_API_URL}/registrations/${registryId}/institutions/`, { + 'page[size]': 100, + }); + expect(mapperSpy).toHaveBeenCalledWith(apiResponse); + expect(response).toEqual(mappedInstitutions); + }); + + it('getRegistryIdentifiers should request identifiers and map response', async () => { + setup(); + const apiResponse = { data: [] } as unknown as IdentifiersResponseJsonApi; + const mapperSpy = vi.spyOn(IdentifiersMapper, 'fromJsonApi').mockReturnValue([MOCK_PROJECT_IDENTIFIERS]); + jsonApiService.get.mockReturnValue(of(apiResponse)); + + const response = await firstValueFrom(service.getRegistryIdentifiers(registryId)); + + expect(jsonApiService.get).toHaveBeenCalledWith(`${MOCK_API_URL}/registrations/${registryId}/identifiers/`); + expect(mapperSpy).toHaveBeenCalledWith(apiResponse); + expect(response).toEqual([MOCK_PROJECT_IDENTIFIERS]); + }); + + it('getSchemaBlocks should append schema_blocks path without query string', async () => { + setup(); + const schemaLink = 'https://api.test/v2/schemas/schema-1/'; + const apiResponse = { data: [] } as unknown as SchemaBlocksResponseJsonApi; + const mapperSpy = vi.spyOn(PageSchemaMapper, 'fromSchemaBlocksResponse').mockReturnValue(MOCK_PAGES_SCHEMA); + jsonApiService.get.mockReturnValue(of(apiResponse)); + + const response = await firstValueFrom(service.getSchemaBlocks(schemaLink)); + + expect(jsonApiService.get).toHaveBeenCalledWith(`${schemaLink}schema_blocks/`, { + 'page[size]': 200, + page: 1, + }); + expect(mapperSpy).toHaveBeenCalledWith(apiResponse); + expect(response).toEqual(MOCK_PAGES_SCHEMA); + }); + + it('getSchemaBlocks should preserve query string when schema link has params', async () => { + setup(); + const schemaLink = 'https://api.test/v2/schemas/schema-1/?version=2'; + const apiResponse = { data: [] } as unknown as SchemaBlocksResponseJsonApi; + vi.spyOn(PageSchemaMapper, 'fromSchemaBlocksResponse').mockReturnValue(MOCK_PAGES_SCHEMA); + jsonApiService.get.mockReturnValue(of(apiResponse)); + + await firstValueFrom(service.getSchemaBlocks(schemaLink)); + + expect(jsonApiService.get).toHaveBeenCalledWith('https://api.test/v2/schemas/schema-1/schema_blocks/?version=2', { + 'page[size]': 200, + page: 1, + }); + }); + + it('getSchemaResponses should request schema responses and map each item', async () => { + setup(); + const apiItem = { id: 'schema-response-1' }; + const apiResponse = { data: [apiItem] } as unknown as SchemaResponsesJsonApi; + const mapperSpy = vi.spyOn(RegistrationMapper, 'fromSchemaResponse').mockReturnValue(schemaResponse); + jsonApiService.get.mockReturnValue(of(apiResponse)); + + const response = await firstValueFrom(service.getSchemaResponses(registryId)); + + expect(jsonApiService.get).toHaveBeenCalledWith(`${MOCK_API_URL}/registrations/${registryId}/schema_responses/`); + expect(mapperSpy).toHaveBeenCalledWith(apiItem); + expect(response).toEqual([schemaResponse]); + }); + + it('getRegistryReviewActions should request actions and map each item', async () => { + setup(); + const apiItem = { id: 'action-1' }; + const apiResponse = { data: [apiItem] } as unknown as ReviewActionsResponseJsonApi; + const mappedAction = REVIEW_ACTION_MOCK as ReviewAction; + const mapperSpy = vi.spyOn(RegistryModerationMapper, 'fromActionResponse').mockReturnValue(mappedAction); + jsonApiService.get.mockReturnValue(of(apiResponse)); + + const response = await firstValueFrom(service.getRegistryReviewActions(registryId)); + + expect(jsonApiService.get).toHaveBeenCalledWith(`${MOCK_API_URL}/registrations/${registryId}/actions/`); + expect(mapperSpy).toHaveBeenCalledWith(apiItem); + expect(response).toEqual([mappedAction]); + }); + + it('createSchemaResponse should post payload and map response', async () => { + setup(); + const apiResponse = { data: { id: 'schema-response-1' } } as unknown as SchemaResponseJsonApi; + const mapperSpy = vi.spyOn(RegistrationMapper, 'fromSchemaResponse').mockReturnValue(schemaResponse); + jsonApiService.post.mockReturnValue(of(apiResponse)); + + const response = await firstValueFrom(service.createSchemaResponse(registryId)); + + expect(jsonApiService.post).toHaveBeenCalledWith(`${MOCK_API_URL}/schema_responses/`, { + data: { + type: 'schema_responses', + relationships: { + registration: { + data: { + type: 'registrations', + id: registryId, + }, + }, + }, + }, + }); + expect(mapperSpy).toHaveBeenCalledWith(apiResponse.data); + expect(response).toEqual(schemaResponse); + }); + + it('withdrawRegistration should patch registration and map response', async () => { + setup(); + const justification = 'Withdrawing for testing'; + stubRegistrationNodeMapper(); + jsonApiService.patch.mockReturnValue(of(registrationData)); + + const response = await firstValueFrom(service.withdrawRegistration(registryId, justification)); + + expect(jsonApiService.patch).toHaveBeenCalledWith(`${MOCK_API_URL}/registrations/${registryId}/`, { + data: { + id: registryId, + attributes: { + withdrawal_justification: justification, + pending_withdrawal: true, + }, + relationships: {}, + type: 'registrations', + }, + }); + expect(response).toEqual( + expect.objectContaining({ + id: MOCK_REGISTRATION_OVERVIEW_MODEL.id, + associatedProjectId: 'project-1', + forksCount: 3, + }) + ); + }); + + it('makePublic should patch registration public flag and map response', async () => { + setup(); + stubRegistrationNodeMapper(); + jsonApiService.patch.mockReturnValue(of(registrationData)); + + const response = await firstValueFrom(service.makePublic(registryId)); + + expect(jsonApiService.patch).toHaveBeenCalledWith(`${MOCK_API_URL}/registrations/${registryId}/`, { + data: { + id: registryId, + attributes: { + public: true, + }, + relationships: {}, + type: 'registrations', + }, + }); + expect(response).toEqual( + expect.objectContaining({ + id: MOCK_REGISTRATION_OVERVIEW_MODEL.id, + providerId: 'osf', + forksCount: 3, + }) + ); + }); + + it('submitDecision should post review action for registrations', async () => { + setup(); + const payload: ReviewActionPayload = { + targetId: registryId, + action: 'accept_submission', + comment: 'Looks good', + }; + const mappedParams = { + data: { type: 'review_actions' }, + } as ReviewActionPayloadJsonApi; + const mapperSpy = vi.spyOn(ReviewActionsMapper, 'toReviewActionPayloadJsonApi').mockReturnValue(mappedParams); + jsonApiService.post.mockReturnValue(of(undefined)); + + const response = await firstValueFrom(service.submitDecision(payload, false)); + + expect(mapperSpy).toHaveBeenCalledWith(payload, 'review_actions', 'registrations'); + expect(jsonApiService.post).toHaveBeenCalledWith( + `${MOCK_API_URL}/registrations/${registryId}/actions/`, + mappedParams + ); + expect(response).toBeUndefined(); + }); + + it('submitDecision should post schema response action for revisions', async () => { + setup(); + const payload: ReviewActionPayload = { + targetId: 'schema-response-1', + action: 'approve', + comment: 'Approved', + }; + const mappedParams = { + data: { type: 'schema_response_actions' }, + } as ReviewActionPayloadJsonApi; + const mapperSpy = vi.spyOn(ReviewActionsMapper, 'toReviewActionPayloadJsonApi').mockReturnValue(mappedParams); + jsonApiService.post.mockReturnValue(of(undefined)); + + const response = await firstValueFrom(service.submitDecision(payload, true)); + + expect(mapperSpy).toHaveBeenCalledWith(payload, 'schema_response_actions', 'schema-responses'); + expect(jsonApiService.post).toHaveBeenCalledWith( + `${MOCK_API_URL}/schema_responses/${payload.targetId}/actions/`, + mappedParams + ); + expect(response).toBeUndefined(); + }); +}); diff --git a/src/app/features/registry/services/registry-overview.service.ts b/src/app/features/registry/services/registry-overview.service.ts index ee8bfeb18..de2509775 100644 --- a/src/app/features/registry/services/registry-overview.service.ts +++ b/src/app/features/registry/services/registry-overview.service.ts @@ -7,15 +7,12 @@ import { RegistryModerationMapper } from '@osf/features/moderation/mappers'; import { ReviewAction, ReviewActionsResponseJsonApi } from '@osf/features/moderation/models'; import { IdentifiersMapper } from '@osf/shared/mappers/identifiers.mapper'; import { InstitutionsMapper } from '@osf/shared/mappers/institutions'; -import { LicensesMapper } from '@osf/shared/mappers/licenses.mapper'; import { PageSchemaMapper, RegistrationMapper } from '@osf/shared/mappers/registration'; import { ReviewActionsMapper } from '@osf/shared/mappers/review-actions.mapper'; import { IdentifierModel } from '@osf/shared/models/identifiers/identifier.model'; import { IdentifiersResponseJsonApi } from '@osf/shared/models/identifiers/identifier-json-api.model'; import { InstitutionsJsonApiResponse } from '@osf/shared/models/institutions/institution-json-api.model'; import { Institution } from '@osf/shared/models/institutions/institutions.model'; -import { LicenseModel } from '@osf/shared/models/license/license.model'; -import { LicenseResponseJsonApi } from '@osf/shared/models/license/licenses-json-api.model'; import { PageSchema } from '@osf/shared/models/registration/page-schema.model'; import { SchemaBlocksResponseJsonApi } from '@osf/shared/models/registration/schema-blocks-json-api.model'; import { SchemaResponse } from '@osf/shared/models/registration/schema-response.model'; @@ -70,12 +67,6 @@ export class RegistryOverviewService { .pipe(map((response) => IdentifiersMapper.fromJsonApi(response))); } - getRegistryLicense(licenseId: string): Observable { - return this.jsonApiService - .get(`${this.apiUrl}/licenses/${licenseId}/`) - .pipe(map((response) => LicensesMapper.fromLicenseDataJsonApi(response.data))); - } - getSchemaBlocks(schemaLink: string): Observable { const params = { 'page[size]': 200, diff --git a/src/app/features/registry/store/registry/registry.actions.ts b/src/app/features/registry/store/registry/registry.actions.ts index 54723554a..018d1fc47 100644 --- a/src/app/features/registry/store/registry/registry.actions.ts +++ b/src/app/features/registry/store/registry/registry.actions.ts @@ -24,12 +24,6 @@ export class GetRegistryIdentifiers { constructor(public registryId: string) {} } -export class GetRegistryLicense { - static readonly type = '[Registry] Get Registry License'; - - constructor(public licenseId: string | undefined) {} -} - export class GetSchemaBlocks { static readonly type = '[Registry] Get Schema Blocks'; diff --git a/src/app/features/registry/store/registry/registry.model.ts b/src/app/features/registry/store/registry/registry.model.ts index 098aa94cd..e0237f88e 100644 --- a/src/app/features/registry/store/registry/registry.model.ts +++ b/src/app/features/registry/store/registry/registry.model.ts @@ -1,7 +1,6 @@ import { ReviewAction } from '@osf/features/moderation/models'; import { IdentifierModel } from '@osf/shared/models/identifiers/identifier.model'; import { Institution } from '@osf/shared/models/institutions/institutions.model'; -import { LicenseModel } from '@osf/shared/models/license/license.model'; import { PageSchema } from '@osf/shared/models/registration/page-schema.model'; import { SchemaResponse } from '@osf/shared/models/registration/schema-response.model'; import { AsyncStateModel } from '@osf/shared/models/store/async-state.model'; @@ -12,7 +11,6 @@ export interface RegistryStateModel { registry: AsyncStateModel; institutions: AsyncStateModel; identifiers: AsyncStateModel; - license: AsyncStateModel; schemaBlocks: AsyncStateModel; schemaResponses: AsyncStateModel; currentSchemaResponse: AsyncStateModel; @@ -42,11 +40,6 @@ export const REGISTRY_DEFAULTS: RegistryStateModel = { isLoading: false, error: null, }, - license: { - data: null, - isLoading: false, - error: null, - }, schemaBlocks: { data: [], isLoading: false, diff --git a/src/app/features/registry/store/registry/registry.selectors.ts b/src/app/features/registry/store/registry/registry.selectors.ts index 8adc38841..7ee739d00 100644 --- a/src/app/features/registry/store/registry/registry.selectors.ts +++ b/src/app/features/registry/store/registry/registry.selectors.ts @@ -5,7 +5,6 @@ import { RegistrationOverviewModel } from '@osf/features/registry/models'; import { UserPermissions } from '@osf/shared/enums/user-permissions.enum'; import { IdentifierModel } from '@osf/shared/models/identifiers/identifier.model'; import { Institution } from '@osf/shared/models/institutions/institutions.model'; -import { LicenseModel } from '@osf/shared/models/license/license.model'; import { SchemaResponse } from '@osf/shared/models/registration/schema-response.model'; import { PageSchema } from '@shared/models/registration/page-schema.model'; @@ -73,16 +72,6 @@ export class RegistrySelectors { return state.identifiers.isLoading; } - @Selector([RegistryState]) - static getLicense(state: RegistryStateModel): LicenseModel | null { - return state.license.data; - } - - @Selector([RegistryState]) - static isLicenseLoading(state: RegistryStateModel): boolean { - return state.license.isLoading; - } - @Selector([RegistryState]) static getSchemaResponses(state: RegistryStateModel): SchemaResponse[] { return state.schemaResponses.data; diff --git a/src/app/features/registry/store/registry/registry.state.ts b/src/app/features/registry/store/registry/registry.state.ts index 3674f4989..c3e746040 100644 --- a/src/app/features/registry/store/registry/registry.state.ts +++ b/src/app/features/registry/store/registry/registry.state.ts @@ -8,6 +8,7 @@ import { inject, Injectable } from '@angular/core'; import { CurrentResourceType } from '@osf/shared/enums/resource-type.enum'; import { handleSectionError } from '@osf/shared/helpers/state-error.handler'; import { DuplicatesService } from '@osf/shared/services/duplicates.service'; +import { FetchLicense } from '@osf/shared/stores/licenses'; import { GetRegistryProvider } from '@osf/shared/stores/registration-provider'; import { RegistryOverviewService } from '../../services'; @@ -19,7 +20,6 @@ import { GetRegistryById, GetRegistryIdentifiers, GetRegistryInstitutions, - GetRegistryLicense, GetRegistryReviewActions, GetRegistrySchemaResponses, GetRegistryWithRelatedData, @@ -96,7 +96,7 @@ export class RegistryState { ctx.dispatch(new GetRegistryProvider(registryOverview.providerId)); } - ctx.dispatch(new GetRegistryLicense(registryOverview.licenseId)); + ctx.dispatch(new FetchLicense(registryOverview.licenseId)); }), catchError((error) => handleSectionError(ctx, 'registry', error)) ); @@ -150,34 +150,6 @@ export class RegistryState { ); } - @Action(GetRegistryLicense) - getRegistryLicense(ctx: StateContext, action: GetRegistryLicense) { - if (!action.licenseId) { - return; - } - - const state = ctx.getState(); - ctx.patchState({ - license: { - ...state.license, - isLoading: true, - }, - }); - - return this.registryOverviewService.getRegistryLicense(action.licenseId).pipe( - tap((license) => { - ctx.patchState({ - license: { - data: license, - isLoading: false, - error: null, - }, - }); - }), - catchError((error) => handleSectionError(ctx, 'license', error)) - ); - } - @Action(GetSchemaBlocks) getSchemaBlocks(ctx: StateContext, action: GetSchemaBlocks) { const state = ctx.getState(); diff --git a/src/app/features/static/terms-of-use/terms-of-use.component.html b/src/app/features/static/terms-of-use/terms-of-use.component.html index 27627b279..dce788132 100644 --- a/src/app/features/static/terms-of-use/terms-of-use.component.html +++ b/src/app/features/static/terms-of-use/terms-of-use.component.html @@ -147,8 +147,7 @@

4. DEFINITIONS AND ACCEPTABLE USE

persistent metadata with a third party).
-
Contributing User.
- +
Contributing User. 
A Contributing User is used on OSF to describe a user who may access, deposit, and edit Content.

Active User.
diff --git a/src/app/shared/components/license/license.component.html b/src/app/shared/components/license/license.component.html index 3ad93cb67..8181970c4 100644 --- a/src/app/shared/components/license/license.component.html +++ b/src/app/shared/components/license/license.component.html @@ -1,58 +1,67 @@ -@if (selectedLicense()) { + +@let license = selectedLicense(); + +@if (license) { - @if (selectedLicense()!.requiredFields.length) { + @if (hasRequiredFields()) {
- + + + @if ( + licenseForm.controls.year.invalid && (licenseForm.controls.year.touched || licenseForm.controls.year.dirty) + ) { + + {{ requiredMessage | translate }} + + }
}

- +

- @if (selectedLicense()!.requiredFields.length && showInternalButtons()) { + @if (hasRequiredFields() && showInternalButtons()) {
} diff --git a/src/app/shared/components/license/license.component.spec.ts b/src/app/shared/components/license/license.component.spec.ts index c6d3438a3..c7b59ce96 100644 --- a/src/app/shared/components/license/license.component.spec.ts +++ b/src/app/shared/components/license/license.component.spec.ts @@ -2,7 +2,8 @@ import { MockComponents } from 'ng-mocks'; import { ComponentFixture, TestBed } from '@angular/core/testing'; -import { LicenseModel, LicenseOptions } from '@shared/models/license/license.model'; +import { INPUT_VALIDATION_MESSAGES } from '@osf/shared/constants/input-validation-messages.const'; +import { LicenseModel, LicenseOptions, LicenseState } from '@osf/shared/models/license/license.model'; import { MOCK_LICENSE } from '@testing/mocks/license.mock'; import { provideOSFCore } from '@testing/osf.testing.provider'; @@ -16,23 +17,30 @@ describe('LicenseComponent', () => { let component: LicenseComponent; let fixture: ComponentFixture; - const mockLicenses: LicenseModel[] = [ - { - ...MOCK_LICENSE, - id: 'license-1', - name: 'MIT License', - requiredFields: [], - text: 'MIT License text', - }, - MOCK_LICENSE, - ]; + const licenseWithoutFields: LicenseModel = { + ...MOCK_LICENSE, + id: 'license-1', + name: 'MIT License', + requiredFields: [], + text: 'MIT License text', + }; + + const licenseWithFields: LicenseModel = MOCK_LICENSE; + + const mockLicenses: LicenseModel[] = [licenseWithoutFields, licenseWithFields]; const mockLicenseOptions: LicenseOptions = { year: '2024', copyrightHolders: 'John Doe', }; - beforeEach(() => { + interface SetupOverrides { + selectedLicenseId?: string | null; + selectedLicenseOptions?: LicenseOptions | null; + showInternalButtons?: boolean; + } + + function setup(overrides: SetupOverrides = {}) { TestBed.configureTestingModule({ imports: [LicenseComponent, ...MockComponents(TextInputComponent, TruncatedTextComponent)], providers: [provideOSFCore()], @@ -42,97 +50,105 @@ describe('LicenseComponent', () => { component = fixture.componentInstance; fixture.componentRef.setInput('licenses', mockLicenses); - fixture.componentRef.setInput('selectedLicenseId', null); - fixture.componentRef.setInput('selectedLicenseOptions', null); - fixture.componentRef.setInput('isSubmitting', false); - fixture.componentRef.setInput('showInternalButtons', true); - fixture.componentRef.setInput('fullWidthSelect', false); - + fixture.componentRef.setInput('selectedLicenseId', overrides.selectedLicenseId ?? null); + fixture.componentRef.setInput('selectedLicenseOptions', overrides.selectedLicenseOptions ?? null); + fixture.componentRef.setInput('showInternalButtons', overrides.showInternalButtons ?? true); fixture.detectChanges(); - }); + } - it('should create', () => { - expect(component).toBeTruthy(); - }); + it('should initialize license form with current year and empty copyright holders', () => { + setup(); - it('should set licenses input', () => { - expect(component.licenses()).toEqual(mockLicenses); + expect(component.licenseForm.controls.year.value).toBe(new Date().getFullYear().toString()); + expect(component.licenseForm.controls.copyrightHolders.value).toBe(''); }); - it('should set selectedLicenseId input', () => { - expect(component.selectedLicenseId()).toBe(null); - }); + it('should sync selectedLicense from selectedLicenseId', () => { + setup({ selectedLicenseId: licenseWithoutFields.id }); - it('should set selectedLicenseOptions input', () => { - expect(component.selectedLicenseOptions()).toBe(null); + expect(component.selectedLicense()).toEqual(licenseWithoutFields); }); - it('should set isSubmitting input', () => { - expect(component.isSubmitting()).toBe(false); - }); + it('should clear selectedLicense when selectedLicenseId is not in licenses', () => { + setup({ selectedLicenseId: 'missing-id' }); - it('should set showInternalButtons input', () => { - expect(component.showInternalButtons()).toBe(true); + expect(component.selectedLicense()).toBeNull(); }); - it('should set fullWidthSelect input', () => { - expect(component.fullWidthSelect()).toBe(false); - }); + it('should emit selectLicense and keep pending selection until id updates', () => { + setup(); + const emitSpy = vi.spyOn(component.selectLicense, 'emit'); + + component.onSelectLicense(licenseWithFields); - it('should initialize license form with current year', () => { - const currentYear = new Date().getFullYear().toString(); - expect(component.licenseForm.get('year')?.value).toBe(currentYear); + expect(emitSpy).toHaveBeenCalledWith(licenseWithFields); + expect(component.selectedLicense()).toEqual(licenseWithFields); }); - it('should initialize license form with empty copyright holders', () => { - expect(component.licenseForm.get('copyrightHolders')?.value).toBe(''); + it('should patch form when selectedLicenseOptions change', () => { + setup({ selectedLicenseOptions: mockLicenseOptions }); + + expect(component.licenseForm.controls.year.value).toBe('2024'); + expect(component.licenseForm.controls.copyrightHolders.value).toBe('John Doe'); }); - it('should emit selectLicense when license without required fields is selected', () => { - const emitSpy = vi.spyOn(component.selectLicense, 'emit'); - const license = mockLicenses[0]; + it('should emit licenseStateChange with form values', () => { + setup({ selectedLicenseOptions: mockLicenseOptions }); + const states: LicenseState[] = []; - component.onSelectLicense(license); + component.licenseStateChange.subscribe((state) => states.push(state)); + component.licenseForm.patchValue({ + year: '2025', + copyrightHolders: 'Jane Doe', + }); - expect(emitSpy).toHaveBeenCalledWith(license); + expect(states.at(-1)).toEqual({ + licenseOptions: { + year: '2025', + copyrightHolders: 'Jane Doe', + }, + formInvalid: false, + }); }); it('should emit createLicense when save is called with valid form', () => { + setup({ selectedLicenseId: licenseWithFields.id }); const emitSpy = vi.spyOn(component.createLicense, 'emit'); - component.selectedLicense.set(mockLicenses[1]); - - component.licenseForm.patchValue({ - year: '2024', - copyrightHolders: 'John Doe', - }); - + component.licenseForm.patchValue(mockLicenseOptions); component.saveLicense(); expect(emitSpy).toHaveBeenCalledWith({ - id: MOCK_LICENSE.id, - licenseOptions: { - year: '2024', - copyrightHolders: 'John Doe', - }, + id: licenseWithFields.id, + licenseOptions: mockLicenseOptions, }); }); it('should not emit createLicense when form is invalid', () => { + setup({ selectedLicenseId: licenseWithFields.id }); const emitSpy = vi.spyOn(component.createLicense, 'emit'); - component.selectedLicense.set(mockLicenses[1]); component.licenseForm.patchValue({ year: '', copyrightHolders: '', }); + component.saveLicense(); + + expect(emitSpy).not.toHaveBeenCalled(); + }); + + it('should not emit createLicense when no license is selected', () => { + setup(); + const emitSpy = vi.spyOn(component.createLicense, 'emit'); + component.licenseForm.patchValue(mockLicenseOptions); component.saveLicense(); expect(emitSpy).not.toHaveBeenCalled(); }); - it('should reset form when cancel is called', () => { + it('should reset form to defaults when cancel is called without selected options', () => { + setup(); component.licenseForm.patchValue({ year: '2023', copyrightHolders: 'Test Holder', @@ -140,15 +156,82 @@ describe('LicenseComponent', () => { component.cancel(); - expect(component.licenseForm.get('year')?.value).toBe(''); - expect(component.licenseForm.get('copyrightHolders')?.value).toBe(''); + expect(component.licenseForm.controls.year.value).toBe(new Date().getFullYear().toString()); + expect(component.licenseForm.controls.copyrightHolders.value).toBe(''); }); - it('should update form when selectedLicenseOptions changes', () => { - fixture.componentRef.setInput('selectedLicenseOptions', mockLicenseOptions); + it('should restore selectedLicenseOptions when cancel is called', () => { + setup({ selectedLicenseOptions: mockLicenseOptions }); + component.licenseForm.patchValue({ + year: '2020', + copyrightHolders: 'Changed', + }); + + component.cancel(); + + expect(component.licenseForm.controls.year.value).toBe('2024'); + expect(component.licenseForm.controls.copyrightHolders.value).toBe('John Doe'); + }); + + it('should toggle saveButtonDisabled based on whether form matches selected options', () => { + setup({ + selectedLicenseId: licenseWithFields.id, + selectedLicenseOptions: mockLicenseOptions, + }); + + expect(component.saveButtonDisabled()).toBe(true); + + component.licenseForm.patchValue({ + year: '2025', + copyrightHolders: 'Jane Doe', + }); + fixture.detectChanges(); + + expect(component.saveButtonDisabled()).toBe(false); + }); + + it('should keep save enabled and form valid when license has no required fields', () => { + setup({ + selectedLicenseId: licenseWithoutFields.id, + selectedLicenseOptions: mockLicenseOptions, + }); + + expect(component.hasRequiredFields()).toBe(false); + expect(component.licenseForm.valid).toBe(true); + expect(component.saveButtonDisabled()).toBe(false); + }); + + it('should require year and copyright holders when license has required fields', () => { + setup({ selectedLicenseId: licenseWithFields.id }); + + expect(component.hasRequiredFields()).toBe(true); + expect(component.licenseForm.invalid).toBe(true); + + component.licenseForm.patchValue(mockLicenseOptions); + + expect(component.licenseForm.valid).toBe(true); + }); + + it('should render internal buttons only when showInternalButtons is true', () => { + setup({ selectedLicenseId: licenseWithFields.id }); + expect(fixture.nativeElement.querySelectorAll('p-button').length).toBe(2); + + setup({ + selectedLicenseId: licenseWithFields.id, + showInternalButtons: false, + }); + expect(fixture.nativeElement.querySelectorAll('p-button').length).toBe(0); + }); + + it('should show year required error when year control is invalid and dirty', () => { + setup({ selectedLicenseId: licenseWithFields.id }); + + component.licenseForm.controls.year.setValue(''); + component.licenseForm.controls.year.markAsDirty(); fixture.detectChanges(); - expect(component.licenseForm.get('year')?.value).toBe('2024'); - expect(component.licenseForm.get('copyrightHolders')?.value).toBe('John Doe'); + const message = fixture.nativeElement.querySelector('p-message'); + expect(message).toBeTruthy(); + expect(message.textContent).toContain(INPUT_VALIDATION_MESSAGES.required); }); }); diff --git a/src/app/shared/components/license/license.component.ts b/src/app/shared/components/license/license.component.ts index 6d8823827..4a901d2b4 100644 --- a/src/app/shared/components/license/license.component.ts +++ b/src/app/shared/components/license/license.component.ts @@ -3,18 +3,22 @@ import { TranslatePipe } from '@ngx-translate/core'; import { Button } from 'primeng/button'; import { DatePicker } from 'primeng/datepicker'; import { Divider } from 'primeng/divider'; +import { Message } from 'primeng/message'; import { Select } from 'primeng/select'; -import { ChangeDetectionStrategy, Component, effect, input, model, output, signal } from '@angular/core'; -import { toSignal } from '@angular/core/rxjs-interop'; +import { map, merge, startWith } from 'rxjs'; + +import { ChangeDetectionStrategy, Component, computed, effect, input, output, signal, untracked } from '@angular/core'; +import { outputFromObservable, toSignal } from '@angular/core/rxjs-interop'; import { FormControl, FormGroup, FormsModule, ReactiveFormsModule } from '@angular/forms'; import { InputLimits } from '@osf/shared/constants/input-limits.const'; +import { INPUT_VALIDATION_MESSAGES } from '@osf/shared/constants/input-validation-messages.const'; import { CustomValidators } from '@osf/shared/helpers/custom-form-validators.helper'; import { StringOrNullOrUndefined } from '@osf/shared/helpers/types.helper'; +import { LicenseDetails, LicenseModel, LicenseOptions, LicenseState } from '@osf/shared/models/license/license.model'; import { LicenseForm } from '@osf/shared/models/license/license-form.model'; -import { LicenseModel, LicenseOptions } from '@shared/models/license/license.model'; -import { InterpolatePipe } from '@shared/pipes/interpolate.pipe'; +import { InterpolatePipe } from '@osf/shared/pipes/interpolate.pipe'; import { TextInputComponent } from '../text-input/text-input.component'; import { TruncatedTextComponent } from '../truncated-text/truncated-text.component'; @@ -32,71 +36,97 @@ import { TruncatedTextComponent } from '../truncated-text/truncated-text.compone Button, TruncatedTextComponent, InterpolatePipe, + Message, ], templateUrl: './license.component.html', styleUrl: './license.component.scss', changeDetection: ChangeDetectionStrategy.OnPush, }) export class LicenseComponent { - selectedLicenseId = input(null); - selectedLicenseOptions = input(null); - licenses = input.required(); - isSubmitting = input(false); - showInternalButtons = input(true); - fullWidthSelect = input(false); - appendTo = input(null); - selectedLicense = model(null); - createLicense = output<{ id: string; licenseOptions: LicenseOptions }>(); - selectLicense = output(); - inputLimits = InputLimits; - saveButtonDisabled = signal(false); - - currentYear = new Date(); - licenseForm = new FormGroup({ - year: new FormControl(this.currentYear.getFullYear().toString(), { - nonNullable: true, - validators: [CustomValidators.requiredTrimmed()], - }), - copyrightHolders: new FormControl('', { - nonNullable: true, - validators: [CustomValidators.requiredTrimmed()], - }), + readonly selectedLicenseId = input(null); + readonly selectedLicenseOptions = input(null); + readonly licenses = input.required(); + readonly showInternalButtons = input(true); + readonly appendTo = input(null); + readonly createLicense = output(); + readonly selectLicense = output(); + + readonly inputLimits = InputLimits; + readonly requiredMessage = INPUT_VALIDATION_MESSAGES.required; + readonly today = new Date(); + readonly yearInputId = `license-year-${Math.random().toString(36).substring(2, 15)}`; + + private readonly pendingLicense = signal(null); + private appliedOptions: LicenseOptions | null = null; + + readonly selectedLicense = computed(() => { + const licenses = this.licenses(); + const pending = this.pendingLicense(); + + if (pending) { + return licenses.find((license) => license.id === pending.id) ?? pending; + } + + return licenses.find((license) => license.id === this.selectedLicenseId()) ?? null; + }); + + readonly hasRequiredFields = computed(() => !!this.selectedLicense()?.requiredFields.length); + + readonly licenseForm = new FormGroup({ + year: new FormControl(this.today.getFullYear().toString(), { nonNullable: true }), + copyrightHolders: new FormControl('', { nonNullable: true }), + }); + + readonly licenseFormValue = toSignal(this.licenseForm.valueChanges.pipe(map(() => this.licenseForm.getRawValue())), { + initialValue: this.licenseForm.getRawValue(), + }); + readonly licenseFormInvalid = toSignal(this.licenseForm.statusChanges.pipe(map((status) => status === 'INVALID')), { + initialValue: this.licenseForm.invalid, + }); + + readonly licenseStateChange = outputFromObservable( + merge(this.licenseForm.valueChanges, this.licenseForm.statusChanges).pipe( + startWith(null), + map(() => ({ + licenseOptions: this.licenseForm.getRawValue(), + formInvalid: this.licenseForm.invalid, + })) + ) + ); + + readonly saveButtonDisabled = computed(() => { + const baseline = this.selectedLicenseOptions(); + return this.hasRequiredFields() && !!baseline && this.isSameOptions(baseline, this.licenseFormValue()); }); - licenseFormValue = toSignal(this.licenseForm.valueChanges); constructor() { effect(() => { - const license = this.licenses().find((l) => l.id === this.selectedLicenseId()); - this.selectedLicense.set(license || null); + this.selectedLicenseId(); + untracked(() => this.pendingLicense.set(null)); }); effect(() => { - const options = this.selectedLicenseOptions(); - if (this.selectedLicenseOptions()) { - this.licenseForm.patchValue({ - year: options!.year, - copyrightHolders: options!.copyrightHolders, - }); + const options = this.resolveLicenseOptions(this.selectedLicenseOptions()); + if (this.appliedOptions && this.isSameOptions(this.appliedOptions, options)) { + return; } + + this.appliedOptions = options; + untracked(() => this.licenseForm.patchValue(options)); }); effect(() => { - const licenseOptionsInput = this.selectedLicenseOptions(); - const licenseOptionsFormValue = this.licenseFormValue(); - - if (!this.selectedLicense() || !this.selectedLicense()?.requiredFields.length) { - return; - } + const required = this.hasRequiredFields(); - if (JSON.stringify(licenseOptionsInput) === JSON.stringify(licenseOptionsFormValue)) { - this.saveButtonDisabled.set(true); - } else { - this.saveButtonDisabled.set(false); - } + untracked(() => { + this.setRequired(this.licenseForm.controls.year, required); + this.setRequired(this.licenseForm.controls.copyrightHolders, required); + }); }); } onSelectLicense(license: LicenseModel): void { + this.pendingLicense.set(license); this.selectLicense.emit(license); } @@ -104,19 +134,35 @@ export class LicenseComponent { if (this.licenseForm.invalid) { return; } - const selectedLicenseId = this.selectedLicense()!.id; - const model = this.licenseForm.value as LicenseOptions; + const selectedLicense = this.selectedLicense(); + if (!selectedLicense) { + return; + } + this.createLicense.emit({ - id: selectedLicenseId, - licenseOptions: model, + id: selectedLicense.id, + licenseOptions: this.licenseForm.getRawValue(), }); } cancel() { - this.licenseForm.reset({ - year: '', - copyrightHolders: '', - }); + this.licenseForm.reset(this.resolveLicenseOptions(this.selectedLicenseOptions())); + } + + private setRequired(control: FormControl, required: boolean): void { + control.setValidators(required ? [CustomValidators.requiredTrimmed()] : null); + control.updateValueAndValidity(); + } + + private isSameOptions(a: LicenseOptions, b: LicenseOptions): boolean { + return a.year === b.year && a.copyrightHolders === b.copyrightHolders; + } + + private resolveLicenseOptions(options: LicenseOptions | null | undefined): LicenseOptions { + return { + year: options?.year ?? this.today.getFullYear().toString(), + copyrightHolders: options?.copyrightHolders ?? '', + }; } } diff --git a/src/app/shared/components/migrated-label/migrated-label.component.html b/src/app/shared/components/migrated-label/migrated-label.component.html new file mode 100644 index 000000000..a46c39b69 --- /dev/null +++ b/src/app/shared/components/migrated-label/migrated-label.component.html @@ -0,0 +1,8 @@ +@if (isMigrated()) { + +} diff --git a/src/app/shared/components/migrated-label/migrated-label.component.scss b/src/app/shared/components/migrated-label/migrated-label.component.scss new file mode 100644 index 000000000..a7ed32708 --- /dev/null +++ b/src/app/shared/components/migrated-label/migrated-label.component.scss @@ -0,0 +1,4 @@ +.migrated-label { + --p-tag-padding: 0.125rem 0.5rem; + --p-tag-font-size: 0.75rem; +} diff --git a/src/app/shared/components/migrated-label/migrated-label.component.spec.ts b/src/app/shared/components/migrated-label/migrated-label.component.spec.ts new file mode 100644 index 000000000..ac6ae7baf --- /dev/null +++ b/src/app/shared/components/migrated-label/migrated-label.component.spec.ts @@ -0,0 +1,34 @@ +import { ComponentFixture, TestBed } from '@angular/core/testing'; + +import { provideOSFCore } from '@testing/osf.testing.provider'; + +import { MigratedLabelComponent } from './migrated-label.component'; + +describe('MigratedLabelComponent', () => { + let fixture: ComponentFixture; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [MigratedLabelComponent], + providers: [provideOSFCore()], + }); + + fixture = TestBed.createComponent(MigratedLabelComponent); + }); + + it('should render migrated tag when isMigrated is true', () => { + fixture.componentRef.setInput('isMigrated', true); + fixture.detectChanges(); + + const label = fixture.nativeElement.querySelector('[data-test-migrated-label]'); + expect(label).toBeTruthy(); + expect(label.textContent).toContain('common.labels.migrated'); + }); + + it('should not render migrated tag when isMigrated is false', () => { + fixture.componentRef.setInput('isMigrated', false); + fixture.detectChanges(); + + expect(fixture.nativeElement.querySelector('[data-test-migrated-label]')).toBeNull(); + }); +}); diff --git a/src/app/shared/components/migrated-label/migrated-label.component.ts b/src/app/shared/components/migrated-label/migrated-label.component.ts new file mode 100644 index 000000000..4cf3432a6 --- /dev/null +++ b/src/app/shared/components/migrated-label/migrated-label.component.ts @@ -0,0 +1,16 @@ +import { TranslatePipe } from '@ngx-translate/core'; + +import { Tag } from 'primeng/tag'; + +import { ChangeDetectionStrategy, Component, input } from '@angular/core'; + +@Component({ + selector: 'osf-migrated-label', + imports: [Tag, TranslatePipe], + templateUrl: './migrated-label.component.html', + styleUrl: './migrated-label.component.scss', + changeDetection: ChangeDetectionStrategy.OnPush, +}) +export class MigratedLabelComponent { + readonly isMigrated = input(false); +} diff --git a/src/app/shared/components/my-projects-table/my-projects-table.component.html b/src/app/shared/components/my-projects-table/my-projects-table.component.html index 29e9de1d1..eef57c800 100644 --- a/src/app/shared/components/my-projects-table/my-projects-table.component.html +++ b/src/app/shared/components/my-projects-table/my-projects-table.component.html @@ -8,7 +8,6 @@ [totalRecords]="tableParams().totalRecords" paginatorDropdownAppendTo="body" [scrollable]="true" - [sortMode]="'single'" [lazy]="true" [sortField]="sortColumn()" [sortOrder]="sortOrder()" @@ -44,6 +43,7 @@

{{ item.title }} +

diff --git a/src/app/shared/components/my-projects-table/my-projects-table.component.spec.ts b/src/app/shared/components/my-projects-table/my-projects-table.component.spec.ts index 6dcaddc1d..b9ba0fb6b 100644 --- a/src/app/shared/components/my-projects-table/my-projects-table.component.spec.ts +++ b/src/app/shared/components/my-projects-table/my-projects-table.component.spec.ts @@ -5,16 +5,18 @@ import { TablePageEvent } from 'primeng/table'; import { TemplateRef } from '@angular/core'; import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { By } from '@angular/platform-browser'; import { SortOrder } from '@osf/shared/enums/sort-order.enum'; import { MyResourcesItem } from '@osf/shared/models/my-resources/my-resources-item.model'; import { TableParameters } from '@osf/shared/models/table-parameters.model'; -import { MOCK_CONTRIBUTOR } from '@testing/mocks/contributors.mock'; +import { MOCK_MY_RESOURCES_ITEM_PROJECT } from '@testing/mocks/my-resources.mock'; import { provideOSFCore } from '@testing/osf.testing.provider'; import { ContributorsListShortenerComponent } from '../contributors-list-shortener/contributors-list-shortener.component'; import { IconComponent } from '../icon/icon.component'; +import { MigratedLabelComponent } from '../migrated-label/migrated-label.component'; import { MyProjectsTableComponent } from './my-projects-table.component'; @@ -33,21 +35,21 @@ describe('MyProjectsTableComponent', () => { defaultSortColumn: 'name', }; - const mockItem: MyResourcesItem = { - id: 'project-1', - title: 'Test Project 1', - isPublic: true, - dateModified: '2024-01-01T10:00:00Z', - contributors: [MOCK_CONTRIBUTOR], - type: 'nodes', - dateCreated: '2024-01-01T00:00:00Z', - }; - - const mockItems = [mockItem]; - - beforeEach(() => { + function setup( + overrides: { + items?: MyResourcesItem[]; + isLoading?: boolean; + emptyMessageKey?: string; + downloadCellTemplate?: TemplateRef<{ $implicit: MyResourcesItem }>; + sortColumn?: string; + sortOrder?: SortOrder; + } = {} + ) { TestBed.configureTestingModule({ - imports: [MyProjectsTableComponent, ...MockComponents(IconComponent, ContributorsListShortenerComponent)], + imports: [ + MyProjectsTableComponent, + ...MockComponents(IconComponent, ContributorsListShortenerComponent, MigratedLabelComponent), + ], providers: [provideOSFCore()], }); @@ -55,101 +57,74 @@ describe('MyProjectsTableComponent', () => { component = fixture.componentInstance; fixture.componentRef.setInput('tableParams', mockTableParams); - }); - - it('should create with default input values', () => { - expect(component).toBeTruthy(); - }); - - it('should default items to an empty array', () => { - expect(component.items()).toEqual([]); - }); - - it('should accept items input', () => { - fixture.componentRef.setInput('items', mockItems); - - expect(component.items()).toEqual(mockItems); - }); - - it('should accept tableParams input', () => { - expect(component.tableParams()).toEqual(mockTableParams); - }); - - it('should default sortColumn to undefined and sortOrder to Asc', () => { - expect(component.sortColumn()).toBeUndefined(); - expect(component.sortOrder()).toBe(SortOrder.Asc); - }); + fixture.componentRef.setInput('items', overrides.items ?? []); + fixture.componentRef.setInput('isLoading', overrides.isLoading ?? false); + fixture.componentRef.setInput('emptyMessageKey', overrides.emptyMessageKey ?? 'common.search.noResultsFound'); + fixture.componentRef.setInput('sortColumn', overrides.sortColumn); + fixture.componentRef.setInput('sortOrder', overrides.sortOrder ?? SortOrder.Asc); - it('should accept sortColumn and sortOrder inputs', () => { - fixture.componentRef.setInput('sortColumn', 'title'); - fixture.componentRef.setInput('sortOrder', SortOrder.Desc); + if (overrides.downloadCellTemplate) { + fixture.componentRef.setInput('downloadCellTemplate', overrides.downloadCellTemplate); + } - expect(component.sortColumn()).toBe('title'); - expect(component.sortOrder()).toBe(SortOrder.Desc); - }); + fixture.detectChanges(); + } - it('should default isLoading to false', () => { - expect(component.isLoading()).toBe(false); - }); + it('should render items and emit itemClick on row click', () => { + setup({ items: [MOCK_MY_RESOURCES_ITEM_PROJECT] }); + const itemClickSpy = vi.fn(); + component.itemClick.subscribe(itemClickSpy); - it('should accept isLoading input', () => { - fixture.componentRef.setInput('isLoading', true); + expect(fixture.nativeElement.textContent).toContain(MOCK_MY_RESOURCES_ITEM_PROJECT.title); - expect(component.isLoading()).toBe(true); - }); + const row = fixture.nativeElement.querySelector('tbody tr') as HTMLTableRowElement; + row.click(); - it('should default emptyMessageKey to common.search.noResultsFound', () => { - expect(component.emptyMessageKey()).toBe('common.search.noResultsFound'); + expect(itemClickSpy).toHaveBeenCalledWith(MOCK_MY_RESOURCES_ITEM_PROJECT); }); - it('should accept emptyMessageKey input', () => { - fixture.componentRef.setInput('emptyMessageKey', 'myProjects.empty.noProjects'); + it('should show loading skeletons when isLoading is true', () => { + setup({ isLoading: true, items: [MOCK_MY_RESOURCES_ITEM_PROJECT] }); - expect(component.emptyMessageKey()).toBe('myProjects.empty.noProjects'); + expect(fixture.nativeElement.querySelectorAll('.loading-row')).toHaveLength(10); + expect(fixture.nativeElement.querySelector('p-skeleton')).toBeTruthy(); + expect(fixture.nativeElement.textContent).not.toContain(MOCK_MY_RESOURCES_ITEM_PROJECT.title); }); - it('should default downloadCellTemplate to undefined', () => { - expect(component.downloadCellTemplate()).toBeUndefined(); - }); + it('should show empty message key when there are no items', () => { + setup({ + items: [], + emptyMessageKey: 'myProjects.table.emptyState.all.both', + }); - it('should return columnCount of 3 when download column is hidden', () => { - expect(component.columnCount()).toBe(3); + expect(fixture.nativeElement.textContent).toContain('myProjects.table.emptyState.all.both'); }); - it('should return columnCount of 4 when downloadCellTemplate is provided', () => { - fixture.componentRef.setInput('downloadCellTemplate', {} as TemplateRef<{ $implicit: MyResourcesItem }>); + it('should show download column when downloadCellTemplate is provided', () => { + setup({ + isLoading: true, + downloadCellTemplate: {} as TemplateRef<{ $implicit: MyResourcesItem }>, + }); + expect(fixture.nativeElement.querySelectorAll('thead th')).toHaveLength(4); expect(component.columnCount()).toBe(4); }); - it('should expose skeletonData with 10 placeholder items', () => { - expect(component.skeletonData).toHaveLength(10); - expect(component.skeletonData.every((item) => !item.id)).toBe(true); - }); - - it('should emit pageChange when onPageChange is called', () => { - vi.spyOn(component.pageChange, 'emit'); - const event = { first: 10, rows: 10 } as TablePageEvent; - - component.onPageChange(event); - - expect(component.pageChange.emit).toHaveBeenCalledWith(event); - }); - - it('should emit sort when onSort is called', () => { - vi.spyOn(component.sort, 'emit'); - const event = { field: 'title', order: SortOrder.Desc } as SortEvent; - - component.onSort(event); - - expect(component.sort.emit).toHaveBeenCalledWith(event); - }); + it('should emit pageChange and sort from table events', () => { + setup({ items: [MOCK_MY_RESOURCES_ITEM_PROJECT] }); + const pageChangeSpy = vi.fn(); + const sortSpy = vi.fn(); + component.pageChange.subscribe(pageChangeSpy); + component.sort.subscribe(sortSpy); - it('should emit itemClick when onItemClick is called', () => { - vi.spyOn(component.itemClick, 'emit'); + const pageEvent = { first: 10, rows: 10 } as TablePageEvent; + const sortEvent = { field: 'title', order: SortOrder.Desc } as SortEvent; + const table = fixture.debugElement.query(By.css('p-table')); - component.onItemClick(mockItems[0]); + table.triggerEventHandler('onPage', pageEvent); + table.triggerEventHandler('onSort', sortEvent); - expect(component.itemClick.emit).toHaveBeenCalledWith(mockItems[0]); + expect(pageChangeSpy).toHaveBeenCalledWith(pageEvent); + expect(sortSpy).toHaveBeenCalledWith(sortEvent); }); }); diff --git a/src/app/shared/components/my-projects-table/my-projects-table.component.ts b/src/app/shared/components/my-projects-table/my-projects-table.component.ts index 1f9020c3b..07091d6ff 100644 --- a/src/app/shared/components/my-projects-table/my-projects-table.component.ts +++ b/src/app/shared/components/my-projects-table/my-projects-table.component.ts @@ -13,6 +13,7 @@ import { TableParameters } from '@osf/shared/models/table-parameters.model'; import { ContributorsListShortenerComponent } from '../contributors-list-shortener/contributors-list-shortener.component'; import { IconComponent } from '../icon/icon.component'; +import { MigratedLabelComponent } from '../migrated-label/migrated-label.component'; @Component({ selector: 'osf-my-projects-table', @@ -21,6 +22,7 @@ import { IconComponent } from '../icon/icon.component'; Skeleton, IconComponent, ContributorsListShortenerComponent, + MigratedLabelComponent, NgTemplateOutlet, TranslatePipe, DatePipe, diff --git a/src/app/shared/components/resource-card/resource-card.component.html b/src/app/shared/components/resource-card/resource-card.component.html index c6bf66204..676bfd6ee 100644 --- a/src/app/shared/components/resource-card/resource-card.component.html +++ b/src/app/shared/components/resource-card/resource-card.component.html @@ -23,9 +23,9 @@

@if (isWithdrawn()) { - {{ - 'resourceCard.labels.withdrawn' | translate - }} + + {{ 'resourceCard.labels.withdrawn' | translate }} + } @let orcidValues = orcids(); diff --git a/src/app/shared/components/resource-card/resource-card.component.ts b/src/app/shared/components/resource-card/resource-card.component.ts index 033a5dc6f..4631c3f90 100644 --- a/src/app/shared/components/resource-card/resource-card.component.ts +++ b/src/app/shared/components/resource-card/resource-card.component.ts @@ -110,9 +110,7 @@ export class ResourceCardComponent { return []; }); - isWithdrawn = computed(() => { - return !!this.resource().dateWithdrawn; - }); + isWithdrawn = computed(() => !!this.resource().dateWithdrawn); dateFields = computed(() => { const resource = this.resource(); diff --git a/src/app/shared/mappers/collections/collections.mapper.ts b/src/app/shared/mappers/collections/collections.mapper.ts index 3b79793ca..b3a2d7aee 100644 --- a/src/app/shared/mappers/collections/collections.mapper.ts +++ b/src/app/shared/mappers/collections/collections.mapper.ts @@ -61,6 +61,7 @@ export class CollectionsMapper { type: response.relationships.primary_collection.data!.type, }, defaultLicenseId: response.attributes?.default_license_id, + licensesLink: response.relationships?.licenses_acceptable?.links?.related?.href ?? '', brand: response.embeds.brand.data ? { id: response.embeds.brand.data.id, diff --git a/src/app/shared/mappers/my-resources.mapper.ts b/src/app/shared/mappers/my-resources.mapper.ts index b28f4241b..e1af0b1ad 100644 --- a/src/app/shared/mappers/my-resources.mapper.ts +++ b/src/app/shared/mappers/my-resources.mapper.ts @@ -15,6 +15,7 @@ export class MyResourcesMapper { dateModified: response.attributes.date_modified, isPublic: response.attributes.public, contributors: ContributorsMapper.getContributors(response.embeds?.bibliographic_contributors?.data), + isMigrated: !!response.attributes.is_migrated, }; } } diff --git a/src/app/shared/mappers/registration-provider.mapper.ts b/src/app/shared/mappers/registration-provider.mapper.ts index 8feb41303..2b0376189 100644 --- a/src/app/shared/mappers/registration-provider.mapper.ts +++ b/src/app/shared/mappers/registration-provider.mapper.ts @@ -36,6 +36,7 @@ export class RegistrationProviderMapper { reviewsWorkflow: response.attributes.reviews_workflow, allowSubmissions: response.attributes.allow_submissions, allowUpdates: response.attributes.allow_updates, + licensesLink: response.relationships?.licenses_acceptable?.links?.related?.href ?? '', }; } } diff --git a/src/app/shared/mappers/search/search.mapper.ts b/src/app/shared/mappers/search/search.mapper.ts index 2a4247b8d..41273f57e 100644 --- a/src/app/shared/mappers/search/search.mapper.ts +++ b/src/app/shared/mappers/search/search.mapper.ts @@ -80,8 +80,8 @@ export function MapResources(indexCardSearchResponseJsonApi: IndexCardSearchResp }))[0], storageByteCount: resourceMetadata.storageByteCount?.[0]?.['@value'], storageRegion: resourceMetadata.storageRegion?.[0]?.prefLabel?.[0]?.['@value'], - viewsCount: resourceMetadata.usage?.viewCount?.[0]?.['@value'], - downloadCount: resourceMetadata.usage?.downloadCount?.[0]?.['@value'], + viewsCount: resourceMetadata.usage?.[0]?.viewCount?.[0]?.['@value'], + downloadCount: resourceMetadata.usage?.[0]?.downloadCount?.[0]?.['@value'], addons: (resourceMetadata.hasOsfAddon ?? null)?.map((addon) => addon.prefLabel?.[0]?.['@value']), license: (resourceMetadata.rights ?? null)?.map((part) => ({ absoluteUrl: part?.['@id'], diff --git a/src/app/shared/models/collections/collection-provider-json-api.model.ts b/src/app/shared/models/collections/collection-provider-json-api.model.ts index 797df8dbe..998c1b290 100644 --- a/src/app/shared/models/collections/collection-provider-json-api.model.ts +++ b/src/app/shared/models/collections/collection-provider-json-api.model.ts @@ -3,7 +3,7 @@ import { CedarMetadataDataTemplateJsonApi } from '@osf/features/metadata/models/ import { BrandDataJsonApi } from '../brand/brand-json-api.model'; import { Embed } from '../common/json-api/embeds.model'; import { ResourceLinksJsonApi } from '../common/json-api/links.model'; -import { ToOneRel } from '../common/json-api/relationships.model'; +import { ToManyRel, ToOneRel } from '../common/json-api/relationships.model'; import { JsonApiResource } from '../common/json-api/resource.model'; import { ItemResponse } from '../common/json-api/responses.model'; import { CollectionsProviderAttributesJsonApi } from '../provider/collections-provider-json-api.model'; @@ -26,4 +26,5 @@ interface CollectionProviderEmbedsJsonApi { interface CollectionProviderRelationshipsJsonApi { primary_collection: ToOneRel<'collections'>; + licenses_acceptable?: Pick, 'links'>; } diff --git a/src/app/shared/models/collections/collection-provider.model.ts b/src/app/shared/models/collections/collection-provider.model.ts index 0a1f24408..7ee2afba9 100644 --- a/src/app/shared/models/collections/collection-provider.model.ts +++ b/src/app/shared/models/collections/collection-provider.model.ts @@ -10,6 +10,7 @@ export interface CollectionProvider extends BaseProviderModel { defaultLicenseId?: string | null; requiredMetadataTemplate?: CedarMetadataTemplateModel | null; iri?: string; + licensesLink?: string; } interface CollectionProviderAssets { diff --git a/src/app/shared/models/license/license.model.ts b/src/app/shared/models/license/license.model.ts index c9da318ac..214ccab68 100644 --- a/src/app/shared/models/license/license.model.ts +++ b/src/app/shared/models/license/license.model.ts @@ -11,6 +11,16 @@ export interface LicenseOptions { year: string; } +export interface LicenseDetails { + id: string; + licenseOptions: LicenseOptions; +} + +export interface LicenseState { + licenseOptions: LicenseOptions; + formInvalid: boolean; +} + export interface LicensesOption { copyrightHolders: string[] | null; year: string | null; diff --git a/src/app/shared/models/my-resources/my-resources-item.model.ts b/src/app/shared/models/my-resources/my-resources-item.model.ts index 935d5bfed..72ada36ff 100644 --- a/src/app/shared/models/my-resources/my-resources-item.model.ts +++ b/src/app/shared/models/my-resources/my-resources-item.model.ts @@ -8,4 +8,5 @@ export interface MyResourcesItem { contributors: ContributorModel[]; title: string; type: string; + isMigrated?: boolean; } diff --git a/src/app/shared/models/my-resources/my-resources-json-api.model.ts b/src/app/shared/models/my-resources/my-resources-json-api.model.ts index 0d112941a..9b3fa42b1 100644 --- a/src/app/shared/models/my-resources/my-resources-json-api.model.ts +++ b/src/app/shared/models/my-resources/my-resources-json-api.model.ts @@ -15,6 +15,7 @@ interface MyResourcesItemAttributesJsonApi { date_modified: string; public: boolean; title: string; + is_migrated?: boolean; } interface MyResourcesItemEmbedsJsonApi { diff --git a/src/app/shared/models/nodes/base-node-relationships-json-api.model.ts b/src/app/shared/models/nodes/base-node-relationships-json-api.model.ts index 9c007cc4e..10efcc471 100644 --- a/src/app/shared/models/nodes/base-node-relationships-json-api.model.ts +++ b/src/app/shared/models/nodes/base-node-relationships-json-api.model.ts @@ -22,7 +22,7 @@ export interface BaseNodeRelationships { logs?: ToManyRel<'logs'>; node_links?: ToManyRel<'node-links'>; parent?: ToOneRel<'nodes'>; - preprints?: ToManyRel<'preprints'>; + preprints?: ToManyRel<'preprints'> | null; region?: ToOneRel<'regions'>; registrations?: ToManyRel<'registrations'>; root?: ToOneRel<'nodes'>; diff --git a/src/app/shared/models/preprints/preprint-json-api.model.ts b/src/app/shared/models/preprints/preprint-json-api.model.ts index 84e760499..5967bb1e9 100644 --- a/src/app/shared/models/preprints/preprint-json-api.model.ts +++ b/src/app/shared/models/preprints/preprint-json-api.model.ts @@ -40,6 +40,7 @@ export interface PreprintAttributesJsonApi { has_data_links: ApplicabilityStatus | null; has_prereg_links: ApplicabilityStatus | null; is_latest_version: boolean; + is_migrated: boolean; is_preprint_orphan: boolean; is_published: boolean; license_record: LicenseRecordJsonApi | null; diff --git a/src/app/shared/models/provider/registration-provider-json-api.model.ts b/src/app/shared/models/provider/registration-provider-json-api.model.ts index 2fd111347..236ab70a8 100644 --- a/src/app/shared/models/provider/registration-provider-json-api.model.ts +++ b/src/app/shared/models/provider/registration-provider-json-api.model.ts @@ -1,6 +1,7 @@ import { BrandDataJsonApi } from '../brand/brand-json-api.model'; import { Embed } from '../common/json-api/embeds.model'; import { ResourceLinksJsonApi } from '../common/json-api/links.model'; +import { ToManyRel } from '../common/json-api/relationships.model'; import { JsonApiResource } from '../common/json-api/resource.model'; import { ItemResponse } from '../common/json-api/responses.model'; @@ -15,6 +16,9 @@ export interface RegistryProviderDetailsJsonApi extends JsonApiResource< embeds?: { brand: Embed; }; + relationships?: { + licenses_acceptable?: Pick, 'links'>; + }; links: ResourceLinksJsonApi; } diff --git a/src/app/shared/models/provider/registry-provider.model.ts b/src/app/shared/models/provider/registry-provider.model.ts index 9ccec98f6..112d7db51 100644 --- a/src/app/shared/models/provider/registry-provider.model.ts +++ b/src/app/shared/models/provider/registry-provider.model.ts @@ -12,4 +12,5 @@ export interface RegistryProviderDetails { reviewsWorkflow: string; allowSubmissions: boolean; allowUpdates: boolean; + licensesLink?: string; } diff --git a/src/app/shared/models/search/index-card-search-metadata-json-api.model.ts b/src/app/shared/models/search/index-card-search-metadata-json-api.model.ts index 320abbb3b..ee92c599b 100644 --- a/src/app/shared/models/search/index-card-search-metadata-json-api.model.ts +++ b/src/app/shared/models/search/index-card-search-metadata-json-api.model.ts @@ -19,7 +19,7 @@ export interface ResourceMetadataJsonApi { isPartOfCollection: MetadataFieldJsonApi[]; storageByteCount: ValueNodeJsonApi[]; storageRegion: { prefLabel: ValueNodeJsonApi[] }[]; - usage: UsageJsonApi; + usage: UsageJsonApi[]; hasOsfAddon: { prefLabel: ValueNodeJsonApi[] }[]; funder: MetadataFieldJsonApi[]; affiliation: MetadataFieldJsonApi[]; diff --git a/src/app/shared/services/licenses.service.spec.ts b/src/app/shared/services/licenses.service.spec.ts new file mode 100644 index 000000000..0c72f4fee --- /dev/null +++ b/src/app/shared/services/licenses.service.spec.ts @@ -0,0 +1,63 @@ +import { MockProvider } from 'ng-mocks'; + +import { firstValueFrom, of } from 'rxjs'; + +import { TestBed } from '@angular/core/testing'; + +import { LicensesMapper } from '@osf/shared/mappers/licenses.mapper'; +import { LicenseResponseJsonApi, LicensesResponseJsonApi } from '@osf/shared/models/license/licenses-json-api.model'; +import { JsonApiService } from '@osf/shared/services/json-api.service'; + +import { MOCK_LICENSE } from '@testing/mocks/license.mock'; +import { MOCK_API_URL, provideMockEnvironment } from '@testing/providers/environment.provider.mock'; +import { JsonApiServiceMock, JsonApiServiceMockType } from '@testing/providers/json-api.service.mock'; + +import { LicensesService } from './licenses.service'; + +describe('LicensesService', () => { + let service: LicensesService; + let jsonApiService: JsonApiServiceMockType; + + beforeEach(() => { + jsonApiService = JsonApiServiceMock.simple(); + + TestBed.configureTestingModule({ + providers: [LicensesService, MockProvider(JsonApiService, jsonApiService), provideMockEnvironment()], + }); + + service = TestBed.inject(LicensesService); + }); + + it('should expose apiUrl from environment', () => { + expect(service.apiUrl).toBe(MOCK_API_URL); + }); + + it('getLicenses should request licenses with sort and map response', async () => { + const licensesUrl = `${MOCK_API_URL}/licenses/`; + const apiResponse = { data: [] } as unknown as LicensesResponseJsonApi; + const mapperSpy = vi.spyOn(LicensesMapper, 'fromLicensesResponse').mockReturnValue([MOCK_LICENSE]); + jsonApiService.get.mockReturnValue(of(apiResponse)); + + const response = await firstValueFrom(service.getLicenses(licensesUrl)); + + expect(jsonApiService.get).toHaveBeenCalledWith(licensesUrl, { + 'page[size]': 100, + sort: 'name', + }); + expect(mapperSpy).toHaveBeenCalledWith(apiResponse); + expect(response).toEqual([MOCK_LICENSE]); + }); + + it('getLicenseById should request license and map response', async () => { + const licenseId = MOCK_LICENSE.id; + const licenseApiResponse = { data: { id: licenseId } } as LicenseResponseJsonApi; + const mapperSpy = vi.spyOn(LicensesMapper, 'fromLicenseDataJsonApi').mockReturnValue(MOCK_LICENSE); + jsonApiService.get.mockReturnValue(of(licenseApiResponse)); + + const response = await firstValueFrom(service.getLicenseById(licenseId)); + + expect(jsonApiService.get).toHaveBeenCalledWith(`${MOCK_API_URL}/licenses/${licenseId}/`); + expect(mapperSpy).toHaveBeenCalledWith(licenseApiResponse.data); + expect(response).toEqual(MOCK_LICENSE); + }); +}); diff --git a/src/app/shared/services/licenses.service.ts b/src/app/shared/services/licenses.service.ts index 505b546cc..8143fe5a5 100644 --- a/src/app/shared/services/licenses.service.ts +++ b/src/app/shared/services/licenses.service.ts @@ -1,28 +1,40 @@ import { map, Observable } from 'rxjs'; -import { HttpClient } from '@angular/common/http'; import { inject, Injectable } from '@angular/core'; import { ENVIRONMENT } from '@core/provider/environment.provider'; import { LicensesMapper } from '../mappers/licenses.mapper'; import { LicenseModel } from '../models/license/license.model'; -import { LicensesResponseJsonApi } from '../models/license/licenses-json-api.model'; +import { LicenseResponseJsonApi, LicensesResponseJsonApi } from '../models/license/licenses-json-api.model'; + +import { JsonApiService } from './json-api.service'; @Injectable({ providedIn: 'root', }) export class LicensesService { - private readonly http = inject(HttpClient); + private readonly jsonApiService = inject(JsonApiService); private readonly environment = inject(ENVIRONMENT); get apiUrl() { return `${this.environment.apiDomainUrl}/v2`; } - getAllLicenses(): Observable { - return this.http - .get(`${this.apiUrl}/licenses/?page[size]=20`) + getLicenses(licensesUrl: string): Observable { + const params: Record = { + 'page[size]': 100, + sort: 'name', + }; + + return this.jsonApiService + .get(licensesUrl, params) .pipe(map((licenses) => LicensesMapper.fromLicensesResponse(licenses))); } + + getLicenseById(licenseId: string): Observable { + return this.jsonApiService + .get(`${this.apiUrl}/licenses/${licenseId}/`) + .pipe(map((response) => LicensesMapper.fromLicenseDataJsonApi(response.data))); + } } diff --git a/src/app/shared/services/my-resources.service.spec.ts b/src/app/shared/services/my-resources.service.spec.ts index d145ef5f6..bb9e2a899 100644 --- a/src/app/shared/services/my-resources.service.spec.ts +++ b/src/app/shared/services/my-resources.service.spec.ts @@ -4,13 +4,14 @@ import { firstValueFrom, of } from 'rxjs'; import { TestBed } from '@angular/core/testing'; -import { ENVIRONMENT } from '@core/provider/environment.provider'; import { ResourceSearchMode } from '@osf/shared/enums/resource-search-mode.enum'; +import { CurrentResourceType } from '@osf/shared/enums/resource-type.enum'; import { ResourceVisibilityFilter } from '@osf/shared/enums/resource-visibility-filter.enum'; import { SortOrder } from '@osf/shared/enums/sort-order.enum'; import { MyResourcesMapper } from '@osf/shared/mappers/my-resources.mapper'; import { MOCK_MY_RESOURCES_ITEM_PROJECT } from '@testing/mocks/my-resources.mock'; +import { MOCK_API_URL, provideMockEnvironment } from '@testing/providers/environment.provider.mock'; import { JsonApiServiceMock, JsonApiServiceMockType } from '@testing/providers/json-api.service.mock'; import { MyResourcesResponseJsonApi } from '../models/my-resources/my-resources-json-api.model'; @@ -18,19 +19,19 @@ import { MyResourcesResponseJsonApi } from '../models/my-resources/my-resources- import { JsonApiService } from './json-api.service'; import { MyResourcesService } from './my-resources.service'; -const API_URL = 'https://api.test/v2'; - const BASE_GET_PARAMS: Record = { 'embed[]': ['bibliographic_contributors'], 'fields[users]': 'family_name,full_name,given_name,middle_name', }; +const RESOURCE_FIELDS = 'title,date_created,date_modified,public,bibliographic_contributors'; + function getProjectsApiResponse(): MyResourcesResponseJsonApi { return { data: [ { id: 'node-1', - type: 'nodes', + type: CurrentResourceType.Projects, attributes: { title: 'Test Project', date_created: '2024-01-01T00:00:00.000Z', @@ -53,49 +54,52 @@ function getProjectsApiResponse(): MyResourcesResponseJsonApi { }; } +function expectedResourceParams( + resourceType: CurrentResourceType, + extra: Record = {} +): Record { + const fields = resourceType === CurrentResourceType.Preprints ? `${RESOURCE_FIELDS},is_migrated` : RESOURCE_FIELDS; + + return { + ...BASE_GET_PARAMS, + [`fields[${resourceType}]`]: fields, + ...extra, + }; +} + describe('MyResourcesService', () => { let service: MyResourcesService; let jsonApiService: JsonApiServiceMockType; - function setup() { + beforeEach(() => { jsonApiService = JsonApiServiceMock.simple(); TestBed.configureTestingModule({ - providers: [ - MyResourcesService, - MockProvider(JsonApiService, jsonApiService), - MockProvider(ENVIRONMENT, { - apiDomainUrl: 'https://api.test', - }), - ], + providers: [MyResourcesService, MockProvider(JsonApiService, jsonApiService), provideMockEnvironment()], }); service = TestBed.inject(MyResourcesService); - } + }); it('should expose apiUrl from environment', () => { - setup(); - expect(service.apiUrl).toBe(API_URL); + expect(service.apiUrl).toBe(MOCK_API_URL); }); it('getMyProjects should request user nodes and map response', async () => { - setup(); const mapperSpy = vi.spyOn(MyResourcesMapper, 'fromResponse').mockReturnValue(MOCK_MY_RESOURCES_ITEM_PROJECT); jsonApiService.get.mockReturnValue(of(getProjectsApiResponse())); const response = await firstValueFrom(service.getMyProjects()); - expect(jsonApiService.get).toHaveBeenCalledWith(`${API_URL}/users/me/nodes/`, { - ...BASE_GET_PARAMS, - 'fields[nodes]': 'title,date_created,date_modified,public,bibliographic_contributors', - sort: '-date_modified', - }); + expect(jsonApiService.get).toHaveBeenCalledWith( + `${MOCK_API_URL}/users/me/${CurrentResourceType.Projects}/`, + expectedResourceParams(CurrentResourceType.Projects, { sort: '-date_modified' }) + ); expect(mapperSpy).toHaveBeenCalled(); expect(response.data).toEqual([MOCK_MY_RESOURCES_ITEM_PROJECT]); }); it('getMyProjects should include search, pagination, and sort params', async () => { - setup(); jsonApiService.get.mockReturnValue(of(getProjectsApiResponse())); await firstValueFrom( @@ -111,158 +115,106 @@ describe('MyResourcesService', () => { ) ); - expect(jsonApiService.get).toHaveBeenCalledWith(`${API_URL}/users/me/nodes/`, { - ...BASE_GET_PARAMS, - 'fields[nodes]': 'title,date_created,date_modified,public,bibliographic_contributors', - 'filter[title,description]': 'alpha', - page: 2, - 'page[size]': 25, - sort: '-title', - }); + expect(jsonApiService.get).toHaveBeenCalledWith( + `${MOCK_API_URL}/users/me/${CurrentResourceType.Projects}/`, + expectedResourceParams(CurrentResourceType.Projects, { + 'filter[title,description]': 'alpha', + page: 2, + 'page[size]': 25, + sort: '-title', + }) + ); }); - it('getMyProjects should request public nodes endpoint when search mode is All', async () => { - setup(); + it('getMyProjects should request public nodes without sort for All search mode', async () => { jsonApiService.get.mockReturnValue(of(getProjectsApiResponse())); await firstValueFrom(service.getMyProjects(undefined, 1, 10, ResourceSearchMode.All)); - expect(jsonApiService.get).toHaveBeenCalledWith(`${API_URL}/nodes/`, { - ...BASE_GET_PARAMS, - 'fields[nodes]': 'title,date_created,date_modified,public,bibliographic_contributors', - page: 1, - 'page[size]': 10, - }); + expect(jsonApiService.get).toHaveBeenCalledWith( + `${MOCK_API_URL}/${CurrentResourceType.Projects}/`, + expectedResourceParams(CurrentResourceType.Projects, { + page: 1, + 'page[size]': 10, + }) + ); expect(jsonApiService.get.mock.calls[0][1]).not.toHaveProperty('sort'); }); - it('getMyProjects should add root project filter when rootProjectId is provided', async () => { - setup(); - jsonApiService.get.mockReturnValue(of(getProjectsApiResponse())); - - await firstValueFrom(service.getMyProjects(undefined, 1, 10, ResourceSearchMode.User, 'root-id')); - - expect(jsonApiService.get).toHaveBeenCalledWith(`${API_URL}/users/me/nodes/`, { - ...BASE_GET_PARAMS, - 'fields[nodes]': 'title,date_created,date_modified,public,bibliographic_contributors', - 'filter[root][ne]': 'root-id', - page: 1, - 'page[size]': 10, - sort: '-date_modified', - }); - }); - - it('getMyProjects should add parent filter for Root search mode', async () => { - setup(); + it('getMyProjects should apply parent filters for Root and Component search modes', async () => { jsonApiService.get.mockReturnValue(of(getProjectsApiResponse())); await firstValueFrom(service.getMyProjects(undefined, 1, 10, ResourceSearchMode.Root)); + expect(jsonApiService.get).toHaveBeenCalledWith( + `${MOCK_API_URL}/users/me/${CurrentResourceType.Projects}/`, + expectedResourceParams(CurrentResourceType.Projects, { + 'filter[parent]': null, + page: 1, + 'page[size]': 10, + sort: '-date_modified', + }) + ); - expect(jsonApiService.get).toHaveBeenCalledWith(`${API_URL}/users/me/nodes/`, { - ...BASE_GET_PARAMS, - 'fields[nodes]': 'title,date_created,date_modified,public,bibliographic_contributors', - 'filter[parent]': null, - page: 1, - 'page[size]': 10, - sort: '-date_modified', - }); - }); - - it('getMyProjects should add parent filter for Component search mode', async () => { - setup(); - jsonApiService.get.mockReturnValue(of(getProjectsApiResponse())); - + jsonApiService.get.mockClear(); await firstValueFrom(service.getMyProjects(undefined, 1, 10, ResourceSearchMode.Component)); - - expect(jsonApiService.get).toHaveBeenCalledWith(`${API_URL}/users/me/nodes/`, { - ...BASE_GET_PARAMS, - 'fields[nodes]': 'title,date_created,date_modified,public,bibliographic_contributors', - 'filter[parent][ne]': null, - page: 1, - 'page[size]': 10, - sort: '-date_modified', - }); + expect(jsonApiService.get).toHaveBeenCalledWith( + `${MOCK_API_URL}/users/me/${CurrentResourceType.Projects}/`, + expectedResourceParams(CurrentResourceType.Projects, { + 'filter[parent][ne]': null, + page: 1, + 'page[size]': 10, + sort: '-date_modified', + }) + ); }); - it('getMyProjects should add public visibility filter when visibility is Public', async () => { - setup(); + it('getMyProjects should apply visibility filters', async () => { jsonApiService.get.mockReturnValue(of(getProjectsApiResponse())); await firstValueFrom( - service.getMyProjects(undefined, 1, 10, ResourceSearchMode.User, undefined, ResourceVisibilityFilter.Public) + service.getMyProjects(undefined, 1, 10, ResourceSearchMode.User, ResourceVisibilityFilter.Public) ); + expect(jsonApiService.get.mock.calls[0][1]).toMatchObject({ 'filter[public]': true }); - expect(jsonApiService.get).toHaveBeenCalledWith(`${API_URL}/users/me/nodes/`, { - ...BASE_GET_PARAMS, - 'fields[nodes]': 'title,date_created,date_modified,public,bibliographic_contributors', - 'filter[public]': true, - page: 1, - 'page[size]': 10, - sort: '-date_modified', - }); - }); - - it('getMyProjects should add private visibility filter when visibility is Private', async () => { - setup(); - jsonApiService.get.mockReturnValue(of(getProjectsApiResponse())); - + jsonApiService.get.mockClear(); await firstValueFrom( - service.getMyProjects(undefined, 1, 10, ResourceSearchMode.User, undefined, ResourceVisibilityFilter.Private) + service.getMyProjects(undefined, 1, 10, ResourceSearchMode.User, ResourceVisibilityFilter.Private) ); + expect(jsonApiService.get.mock.calls[0][1]).toMatchObject({ 'filter[public]': false }); - expect(jsonApiService.get).toHaveBeenCalledWith(`${API_URL}/users/me/nodes/`, { - ...BASE_GET_PARAMS, - 'fields[nodes]': 'title,date_created,date_modified,public,bibliographic_contributors', - 'filter[public]': false, - page: 1, - 'page[size]': 10, - sort: '-date_modified', - }); - }); - - it('getMyProjects should not add visibility filter when visibility is All', async () => { - setup(); - jsonApiService.get.mockReturnValue(of(getProjectsApiResponse())); - + jsonApiService.get.mockClear(); await firstValueFrom( - service.getMyProjects(undefined, 1, 10, ResourceSearchMode.User, undefined, ResourceVisibilityFilter.All) + service.getMyProjects(undefined, 1, 10, ResourceSearchMode.User, ResourceVisibilityFilter.All) ); - expect(jsonApiService.get.mock.calls[0][1]).not.toHaveProperty('filter[public]'); }); - it('getMyRegistrations should request user registrations endpoint', async () => { - setup(); + it('getMyRegistrations and getMyPreprints should request matching endpoints and fields', async () => { jsonApiService.get.mockReturnValue(of(getProjectsApiResponse())); await firstValueFrom(service.getMyRegistrations(undefined, 1, 10)); + expect(jsonApiService.get).toHaveBeenCalledWith( + `${MOCK_API_URL}/users/me/${CurrentResourceType.Registrations}/`, + expectedResourceParams(CurrentResourceType.Registrations, { + page: 1, + 'page[size]': 10, + sort: '-date_modified', + }) + ); - expect(jsonApiService.get).toHaveBeenCalledWith(`${API_URL}/users/me/registrations/`, { - ...BASE_GET_PARAMS, - 'fields[registrations]': 'title,date_created,date_modified,public,bibliographic_contributors', - page: 1, - 'page[size]': 10, - sort: '-date_modified', - }); - }); - - it('getMyPreprints should request user preprints endpoint', async () => { - setup(); - jsonApiService.get.mockReturnValue(of(getProjectsApiResponse())); - + jsonApiService.get.mockClear(); await firstValueFrom(service.getMyPreprints(undefined, 1, 10)); - - expect(jsonApiService.get).toHaveBeenCalledWith(`${API_URL}/users/me/preprints/`, { - ...BASE_GET_PARAMS, - 'fields[preprints]': 'title,date_created,date_modified,public,bibliographic_contributors', - page: 1, - 'page[size]': 10, - sort: '-date_modified', - }); + expect(jsonApiService.get).toHaveBeenCalledWith( + `${MOCK_API_URL}/users/me/${CurrentResourceType.Preprints}/`, + expectedResourceParams(CurrentResourceType.Preprints, { + page: 1, + 'page[size]': 10, + sort: '-date_modified', + }) + ); }); it('createProject should post project payload and map response', async () => { - setup(); const mapperSpy = vi.spyOn(MyResourcesMapper, 'fromResponse').mockReturnValue(MOCK_MY_RESOURCES_ITEM_PROJECT); jsonApiService.post.mockReturnValue( of({ @@ -275,10 +227,10 @@ describe('MyResourcesService', () => { ); expect(jsonApiService.post).toHaveBeenCalledWith( - `${API_URL}/nodes/`, + `${MOCK_API_URL}/${CurrentResourceType.Projects}/`, { data: { - type: 'nodes', + type: CurrentResourceType.Projects, attributes: { title: 'New Project', description: 'Description', @@ -301,7 +253,7 @@ describe('MyResourcesService', () => { }, { 'embed[]': ['bibliographic_contributors'], - 'fields[nodes]': 'title,date_modified,public,bibliographic_contributors', + [`fields[${CurrentResourceType.Projects}]`]: 'title,date_modified,public,bibliographic_contributors', 'fields[users]': 'family_name,full_name,given_name,middle_name', } ); @@ -310,7 +262,6 @@ describe('MyResourcesService', () => { }); it('createProject should omit optional fields when not provided', async () => { - setup(); vi.spyOn(MyResourcesMapper, 'fromResponse').mockReturnValue(MOCK_MY_RESOURCES_ITEM_PROJECT); jsonApiService.post.mockReturnValue( of({ @@ -321,10 +272,10 @@ describe('MyResourcesService', () => { await firstValueFrom(service.createProject('New Project', '', '', 'us', [])); expect(jsonApiService.post).toHaveBeenCalledWith( - `${API_URL}/nodes/`, + `${MOCK_API_URL}/${CurrentResourceType.Projects}/`, { data: { - type: 'nodes', + type: CurrentResourceType.Projects, attributes: { title: 'New Project', category: 'project', diff --git a/src/app/shared/services/my-resources.service.ts b/src/app/shared/services/my-resources.service.ts index f434c5e85..7851b87f8 100644 --- a/src/app/shared/services/my-resources.service.ts +++ b/src/app/shared/services/my-resources.service.ts @@ -7,10 +7,10 @@ import { ENVIRONMENT } from '@core/provider/environment.provider'; import { DEFAULT_TABLE_PARAMS } from '../constants/default-table-params.constants'; import { ResourceSearchMode } from '../enums/resource-search-mode.enum'; +import { CurrentResourceType } from '../enums/resource-type.enum'; import { ResourceVisibilityFilter } from '../enums/resource-visibility-filter.enum'; import { SortOrder } from '../enums/sort-order.enum'; import { MyResourcesMapper } from '../mappers/my-resources.mapper'; -import { EndpointType } from '../models/my-resources/my-resources-endpoint.type'; import { MyResourcesItem } from '../models/my-resources/my-resources-item.model'; import { MyResourcesItemResponseJsonApi, @@ -39,20 +39,22 @@ export class MyResourcesService { } private buildCommonParams( + resourceType: CurrentResourceType, filters?: MyResourcesSearchFilters, pageNumber?: number, - pageSize?: number, - resourceType?: string + pageSize?: number ): Record { + const fields = ['title', 'date_created', 'date_modified', 'public', 'bibliographic_contributors']; + if (resourceType === CurrentResourceType.Preprints) { + fields.push('is_migrated'); + } + const params: Record = { 'embed[]': ['bibliographic_contributors'], 'fields[users]': 'family_name,full_name,given_name,middle_name', + [`fields[${resourceType}]`]: fields.join(','), }; - if (resourceType) { - params[`fields[${resourceType}]`] = 'title,date_created,date_modified,public,bibliographic_contributors'; - } - if (filters?.searchValue && filters.searchFields?.length) { params[`filter[${filters.searchFields.join(',')}]`] = filters.searchValue; } @@ -69,16 +71,14 @@ export class MyResourcesService { } private getResources( - endpoint: EndpointType, + resourceType: CurrentResourceType, filters?: MyResourcesSearchFilters, pageNumber?: number, pageSize?: number, - resourceType?: string, searchMode?: ResourceSearchMode, - rootProjectId?: string, visibilityFilter?: ResourceVisibilityFilter ): Observable> { - const params = this.buildCommonParams(filters, pageNumber, pageSize, resourceType); + const params = this.buildCommonParams(resourceType, filters, pageNumber, pageSize); if (searchMode !== ResourceSearchMode.All) { if (filters?.sortColumn && this.sortFieldMap[filters.sortColumn]) { @@ -90,12 +90,10 @@ export class MyResourcesService { } } - if (rootProjectId) { - params['filter[root][ne]'] = rootProjectId; - } - const url = - searchMode === ResourceSearchMode.All ? `${this.apiUrl}/${endpoint}` : `${this.apiUrl}/users/me/${endpoint}`; + searchMode === ResourceSearchMode.All + ? `${this.apiUrl}/${resourceType}/` + : `${this.apiUrl}/users/me/${resourceType}/`; if (searchMode === ResourceSearchMode.Component) { params['filter[parent][ne]'] = null; @@ -125,37 +123,18 @@ export class MyResourcesService { pageNumber?: number, pageSize?: number, searchMode?: ResourceSearchMode, - rootProjectId?: string, visibilityFilter?: ResourceVisibilityFilter ): Observable> { - return this.getResources( - 'nodes/', - filters, - pageNumber, - pageSize, - 'nodes', - searchMode, - rootProjectId, - visibilityFilter - ); + return this.getResources(CurrentResourceType.Projects, filters, pageNumber, pageSize, searchMode, visibilityFilter); } getMyRegistrations( filters?: MyResourcesSearchFilters, pageNumber?: number, pageSize?: number, - searchMode?: ResourceSearchMode, - rootProjectId?: string + searchMode?: ResourceSearchMode ): Observable> { - return this.getResources( - 'registrations/', - filters, - pageNumber, - pageSize, - 'registrations', - searchMode, - rootProjectId - ); + return this.getResources(CurrentResourceType.Registrations, filters, pageNumber, pageSize, searchMode); } getMyPreprints( @@ -163,7 +142,7 @@ export class MyResourcesService { pageNumber?: number, pageSize?: number ): Observable> { - return this.getResources('preprints/', filters, pageNumber, pageSize, 'preprints'); + return this.getResources(CurrentResourceType.Preprints, filters, pageNumber, pageSize); } createProject( @@ -175,7 +154,7 @@ export class MyResourcesService { ): Observable { const payload: CreateProjectPayloadJsoApi = { data: { - type: 'nodes', + type: CurrentResourceType.Projects, attributes: { title, ...(description && { description }), @@ -204,12 +183,12 @@ export class MyResourcesService { const params: Record = { 'embed[]': ['bibliographic_contributors'], - 'fields[nodes]': 'title,date_modified,public,bibliographic_contributors', + [`fields[${CurrentResourceType.Projects}]`]: 'title,date_modified,public,bibliographic_contributors', 'fields[users]': 'family_name,full_name,given_name,middle_name', }; return this.jsonApiService - .post(`${this.apiUrl}/nodes/`, payload, params) + .post(`${this.apiUrl}/${CurrentResourceType.Projects}/`, payload, params) .pipe(map((response) => MyResourcesMapper.fromResponse(response.data))); } } diff --git a/src/app/shared/stores/licenses/licenses.actions.ts b/src/app/shared/stores/licenses/licenses.actions.ts index cd4727b5c..2f6bc323e 100644 --- a/src/app/shared/stores/licenses/licenses.actions.ts +++ b/src/app/shared/stores/licenses/licenses.actions.ts @@ -1,3 +1,11 @@ -export class LoadAllLicenses { - static readonly type = '[Licenses] Load All'; +export class FetchLicenses { + static readonly type = '[Licenses] Fetch Licenses'; + + constructor(public licensesUrl?: string) {} +} + +export class FetchLicense { + static readonly type = '[Licenses] Fetch License'; + + constructor(public licenseId?: string) {} } diff --git a/src/app/shared/stores/licenses/licenses.model.ts b/src/app/shared/stores/licenses/licenses.model.ts index 26f0c7629..506400d84 100644 --- a/src/app/shared/stores/licenses/licenses.model.ts +++ b/src/app/shared/stores/licenses/licenses.model.ts @@ -3,6 +3,7 @@ import { AsyncStateModel } from '@osf/shared/models/store/async-state.model'; export interface LicensesStateModel { licenses: AsyncStateModel; + license: AsyncStateModel; } export const LICENSES_STATE_DEFAULTS: LicensesStateModel = { @@ -11,4 +12,9 @@ export const LICENSES_STATE_DEFAULTS: LicensesStateModel = { isLoading: false, error: null, }, + license: { + data: null, + isLoading: false, + error: null, + }, }; diff --git a/src/app/shared/stores/licenses/licenses.selectors.ts b/src/app/shared/stores/licenses/licenses.selectors.ts index 3fa6ae827..10e73f650 100644 --- a/src/app/shared/stores/licenses/licenses.selectors.ts +++ b/src/app/shared/stores/licenses/licenses.selectors.ts @@ -17,7 +17,12 @@ export class LicensesSelectors { } @Selector([LicensesState]) - static getError(state: LicensesStateModel): string | null { - return state.licenses.error; + static getLicense(state: LicensesStateModel): LicenseModel | null { + return state.license.data; + } + + @Selector([LicensesState]) + static isLicenseLoading(state: LicensesStateModel): boolean { + return state.license.isLoading; } } diff --git a/src/app/shared/stores/licenses/licenses.state.ts b/src/app/shared/stores/licenses/licenses.state.ts index a246f0841..6cafb8881 100644 --- a/src/app/shared/stores/licenses/licenses.state.ts +++ b/src/app/shared/stores/licenses/licenses.state.ts @@ -1,5 +1,6 @@ import { Action, State, StateContext } from '@ngxs/store'; +import { EMPTY } from 'rxjs'; import { catchError, tap } from 'rxjs/operators'; import { inject, Injectable } from '@angular/core'; @@ -7,7 +8,7 @@ import { inject, Injectable } from '@angular/core'; import { handleSectionError } from '@osf/shared/helpers/state-error.handler'; import { LicensesService } from '@osf/shared/services/licenses.service'; -import { LoadAllLicenses } from './licenses.actions'; +import { FetchLicense, FetchLicenses } from './licenses.actions'; import { LICENSES_STATE_DEFAULTS, LicensesStateModel } from './licenses.model'; @State({ @@ -18,8 +19,12 @@ import { LICENSES_STATE_DEFAULTS, LicensesStateModel } from './licenses.model'; export class LicensesState { private readonly licensesService = inject(LicensesService); - @Action(LoadAllLicenses) - loadAllLicenses(ctx: StateContext) { + @Action(FetchLicenses) + fetchLicenses(ctx: StateContext, { licensesUrl }: FetchLicenses) { + if (!licensesUrl) { + return EMPTY; + } + ctx.patchState({ licenses: { data: [], @@ -28,11 +33,11 @@ export class LicensesState { }, }); - return this.licensesService.getAllLicenses().pipe( + return this.licensesService.getLicenses(licensesUrl).pipe( tap((data) => { ctx.patchState({ licenses: { - data: data, + data, isLoading: false, error: null, }, @@ -41,4 +46,39 @@ export class LicensesState { catchError((error) => handleSectionError(ctx, 'licenses', error)) ); } + + @Action(FetchLicense, { cancelUncompleted: true }) + fetchLicense(ctx: StateContext, { licenseId }: FetchLicense) { + if (!licenseId) { + ctx.patchState({ + license: { + data: null, + isLoading: false, + error: null, + }, + }); + return EMPTY; + } + + ctx.patchState({ + license: { + data: null, + isLoading: true, + error: null, + }, + }); + + return this.licensesService.getLicenseById(licenseId).pipe( + tap((license) => { + ctx.patchState({ + license: { + data: license, + isLoading: false, + error: null, + }, + }); + }), + catchError((error) => handleSectionError(ctx, 'license', error)) + ); + } } diff --git a/src/app/shared/stores/my-resources/my-resources.actions.ts b/src/app/shared/stores/my-resources/my-resources.actions.ts index b8eb935f8..daaae9996 100644 --- a/src/app/shared/stores/my-resources/my-resources.actions.ts +++ b/src/app/shared/stores/my-resources/my-resources.actions.ts @@ -10,7 +10,6 @@ export class GetMyProjects { public pageSize: number, public filters: MyResourcesSearchFilters, public searchMode?: ResourceSearchMode, - public rootProjectId?: string, public visibilityFilter?: ResourceVisibilityFilter ) {} } @@ -22,8 +21,7 @@ export class GetMyRegistrations { public pageNumber: number, public pageSize: number, public filters: MyResourcesSearchFilters, - public searchMode?: ResourceSearchMode, - public rootRegistrationId?: string + public searchMode?: ResourceSearchMode ) {} } diff --git a/src/app/shared/stores/my-resources/my-resources.state.ts b/src/app/shared/stores/my-resources/my-resources.state.ts index 8809ac1ad..1c3f92d43 100644 --- a/src/app/shared/stores/my-resources/my-resources.state.ts +++ b/src/app/shared/stores/my-resources/my-resources.state.ts @@ -1,6 +1,6 @@ -import { Action, State, StateContext } from '@ngxs/store'; +import { Action, Actions, ofActionDispatched, State, StateContext } from '@ngxs/store'; -import { catchError, tap } from 'rxjs'; +import { catchError, Observable, takeUntil, tap } from 'rxjs'; import { inject, Injectable } from '@angular/core'; @@ -22,97 +22,97 @@ import { MY_RESOURCES_STATE_DEFAULTS, MyResourcesStateModel } from './my-resourc }) @Injectable() export class MyResourcesState { + private readonly actions$ = inject(Actions); private readonly myResourcesService = inject(MyResourcesService); - @Action(GetMyProjects) + @Action(GetMyProjects, { cancelUncompleted: true }) getProjects(ctx: StateContext, action: GetMyProjects) { - const state = ctx.getState(); ctx.patchState({ projects: { - ...state.projects, + ...ctx.getState().projects, isLoading: true, + error: null, }, }); - return this.myResourcesService - .getMyProjects( - action.filters, - action.pageNumber, - action.pageSize, - action.searchMode, - action.rootProjectId, - action.visibilityFilter - ) - .pipe( - tap((res) => { - ctx.patchState({ - projects: { - data: res.data, - isLoading: false, - error: null, - totalCount: res.totalCount, - }, - }); - }), - catchError((error) => handleSectionError(ctx, 'projects', error)) - ); + return this.untilCleared( + this.myResourcesService + .getMyProjects(action.filters, action.pageNumber, action.pageSize, action.searchMode, action.visibilityFilter) + .pipe( + tap((res) => { + const projects = ctx.getState().projects; + ctx.patchState({ + projects: { + ...projects, + data: res.data, + isLoading: false, + error: null, + totalCount: res.totalCount, + }, + }); + }), + catchError((error) => handleSectionError(ctx, 'projects', error)) + ) + ); } - @Action(GetMyRegistrations) + @Action(GetMyRegistrations, { cancelUncompleted: true }) getRegistrations(ctx: StateContext, action: GetMyRegistrations) { - const state = ctx.getState(); ctx.patchState({ registrations: { - ...state.registrations, + ...ctx.getState().registrations, isLoading: true, + error: null, }, }); - return this.myResourcesService - .getMyRegistrations( - action.filters, - action.pageNumber, - action.pageSize, - action.searchMode, - action.rootRegistrationId - ) - .pipe( - tap((res) => { - ctx.patchState({ - registrations: { - data: res.data, - isLoading: false, - error: null, - totalCount: res.totalCount, - }, - }); - }), - catchError((error) => handleSectionError(ctx, 'registrations', error)) - ); + return this.untilCleared( + this.myResourcesService + .getMyRegistrations(action.filters, action.pageNumber, action.pageSize, action.searchMode) + .pipe( + tap((res) => { + const registrations = ctx.getState().registrations; + ctx.patchState({ + registrations: { + ...registrations, + data: res.data, + isLoading: false, + error: null, + totalCount: res.totalCount, + }, + }); + }), + catchError((error) => handleSectionError(ctx, 'registrations', error)) + ) + ); } - @Action(GetMyPreprints) + @Action(GetMyPreprints, { cancelUncompleted: true }) getPreprints(ctx: StateContext, action: GetMyPreprints) { - const state = ctx.getState(); ctx.patchState({ preprints: { - ...state.preprints, + ...ctx.getState().preprints, isLoading: true, + error: null, }, }); - return this.myResourcesService.getMyPreprints(action.filters, action.pageNumber, action.pageSize).pipe( - tap((res) => { - ctx.patchState({ - preprints: { - data: res.data, - isLoading: false, - error: null, - totalCount: res.totalCount, - }, - }); - }), - catchError((error) => handleSectionError(ctx, 'preprints', error)) + return this.untilCleared( + this.myResourcesService.getMyPreprints(action.filters, action.pageNumber, action.pageSize).pipe( + tap((res) => { + const preprints = ctx.getState().preprints; + ctx.patchState({ + preprints: { + ...preprints, + data: res.data, + isLoading: false, + error: null, + totalCount: res.totalCount, + }, + }); + }), + catchError((error) => handleSectionError(ctx, 'preprints', error)) + ) ); } @@ -123,29 +123,36 @@ export class MyResourcesState { @Action(CreateProject) createProject(ctx: StateContext, action: CreateProject) { - const state = ctx.getState(); ctx.patchState({ projects: { - ...state.projects, + ...ctx.getState().projects, isSubmitting: true, + error: null, }, }); - return this.myResourcesService - .createProject(action.title, action.description, action.templateFrom, action.region, action.affiliations) - .pipe( - tap((project) => { - ctx.patchState({ - projects: { - data: [project, ...state.projects.data], - isLoading: false, - isSubmitting: false, - error: null, - totalCount: state.projects.totalCount + 1, - }, - }); - }), - catchError((error) => handleSectionError(ctx, 'projects', error)) - ); + return this.untilCleared( + this.myResourcesService + .createProject(action.title, action.description, action.templateFrom, action.region, action.affiliations) + .pipe( + tap((project) => { + const projects = ctx.getState().projects; + ctx.patchState({ + projects: { + ...projects, + data: [project, ...projects.data], + isSubmitting: false, + error: null, + totalCount: projects.totalCount + 1, + }, + }); + }), + catchError((error) => handleSectionError(ctx, 'projects', error)) + ) + ); + } + + private untilCleared(source: Observable): Observable { + return source.pipe(takeUntil(this.actions$.pipe(ofActionDispatched(ClearMyResources)))); } } diff --git a/src/assets/i18n/en.json b/src/assets/i18n/en.json index 7304da4ff..7f80fe1ea 100644 --- a/src/assets/i18n/en.json +++ b/src/assets/i18n/en.json @@ -518,6 +518,7 @@ "license": "License", "makePublic": "Make Public", "metadata": "Metadata", + "migrated": "Migrated", "modified": "Modified", "more": "more", "no": "No", @@ -807,7 +808,6 @@ "createProjectDisabledTooltip": "Project creation is no longer available. OSF is transitioning away from Projects as part of a platform update. Your existing projects remain accessible.", "getStartedHelp": "Visit Get Started Help Guides", "images": { - "osfCollectionsImageAltText": "OSF Collections", "osfInstitutionsImageAltText": "OSF Institutions", "osfPreprintsImageAltTest": "OSF Preprints", "osfRegistriesImageAltTest": "OSF Registries" @@ -1436,6 +1436,7 @@ "withdrawn": "Withdrawn" }, "supplementalMaterials": "Supplemental Materials", + "migratedBanner": "This preprint was migrated off this platform.", "warningBanner": "OSF preprints are not peer reviewed and acceptance into OSF preprints is not an indicator of scholarly merit.", "withdrawDialog": { "justificationInputError": "Comment must be at least {{length}} characters.", @@ -1541,13 +1542,8 @@ "success": "Preprint draft successfully deleted." }, "file": { - "note": "Note: You cannot switch options once a file is attached.", "selectFromProject": "Select From Existing OSF Project", "title": "File", - "tooltips": { - "computerDisabled": "Start a new preprint to attach a file from your computer.", - "projectDisabled": "Start a new preprint to attach a file from your project." - }, "uploadDescription": "Please Upload your {{preprintWord}}", "uploadFileButton": "Upload file", "uploadFromComputer": "Upload From Your Computer" @@ -1831,6 +1827,7 @@ "publishedText": "This metadata has a status of 'Published' and is publicly viewable.", "recordCreatedSuccessfully": "Record created successfully", "recordUpdatedSuccessfully": "Record updated successfully", + "saveDraft": "Save draft", "select": "Select", "selectTemplate": "Select a Metadata Template", "title": "Add community metadata record", diff --git a/src/assets/images/dashboard/products/osf-collections.png b/src/assets/images/dashboard/products/osf-collections.png deleted file mode 100644 index c85939d6e..000000000 Binary files a/src/assets/images/dashboard/products/osf-collections.png and /dev/null differ diff --git a/src/testing/mocks/preprint-provider-details.ts b/src/testing/mocks/preprint-provider-details.ts index e70e4c090..56035b4ed 100644 --- a/src/testing/mocks/preprint-provider-details.ts +++ b/src/testing/mocks/preprint-provider-details.ts @@ -31,5 +31,6 @@ export const PREPRINT_PROVIDER_DETAILS_MOCK: PreprintProviderDetails = { facebookAppId: '1234567890', reviewsCommentsPrivate: null, reviewsCommentsAnonymous: null, + licensesLink: 'https://api.osf.io/v2/providers/preprints/osf-preprints/licenses/', lastFetched: Date.now(), }; diff --git a/src/testing/mocks/preprint-short-info.mock.ts b/src/testing/mocks/preprint-short-info.mock.ts index c3eda6726..c53eb10d8 100644 --- a/src/testing/mocks/preprint-short-info.mock.ts +++ b/src/testing/mocks/preprint-short-info.mock.ts @@ -9,6 +9,7 @@ export const PREPRINT_SHORT_INFO_ARRAY_MOCK: PreprintShortInfo[] = [ dateModified: '2024-01-01T00:00:00Z', contributors: [MOCK_CONTRIBUTOR, MOCK_CONTRIBUTOR_WITHOUT_HISTORY], providerId: 'provider-1', + isMigrated: false, }, { id: 'preprint-2', @@ -16,6 +17,7 @@ export const PREPRINT_SHORT_INFO_ARRAY_MOCK: PreprintShortInfo[] = [ dateModified: '2024-01-02T00:00:00Z', contributors: [MOCK_CONTRIBUTOR, MOCK_CONTRIBUTOR_WITHOUT_HISTORY], providerId: 'provider-2', + isMigrated: false, }, { id: 'preprint-3', @@ -23,6 +25,7 @@ export const PREPRINT_SHORT_INFO_ARRAY_MOCK: PreprintShortInfo[] = [ dateModified: '2024-01-03T00:00:00Z', contributors: [], providerId: 'provider-1', + isMigrated: false, }, { id: 'preprint-4', @@ -30,6 +33,7 @@ export const PREPRINT_SHORT_INFO_ARRAY_MOCK: PreprintShortInfo[] = [ dateModified: '2024-01-04T00:00:00Z', contributors: [MOCK_CONTRIBUTOR], providerId: 'provider-3', + isMigrated: false, }, { id: 'preprint-5', @@ -37,5 +41,6 @@ export const PREPRINT_SHORT_INFO_ARRAY_MOCK: PreprintShortInfo[] = [ dateModified: '2024-01-05T00:00:00Z', contributors: [MOCK_CONTRIBUTOR], providerId: 'provider-2', + isMigrated: false, }, ]; diff --git a/src/testing/mocks/preprint.mock.ts b/src/testing/mocks/preprint.mock.ts index 45e47936a..7bda2764c 100644 --- a/src/testing/mocks/preprint.mock.ts +++ b/src/testing/mocks/preprint.mock.ts @@ -22,6 +22,7 @@ export const PREPRINT_MOCK: PreprintModel = { isPublic: true, version: 1, isLatestVersion: true, + isMigrated: false, isPreprintOrphan: false, withdrawalJustification: null, nodeId: 'node-123', diff --git a/src/testing/mocks/project-overview.mock.ts b/src/testing/mocks/project-overview.mock.ts index 3a6e21045..af352c322 100644 --- a/src/testing/mocks/project-overview.mock.ts +++ b/src/testing/mocks/project-overview.mock.ts @@ -57,4 +57,5 @@ export const MOCK_PROJECT_OVERVIEW: ProjectOverviewModel = { contributors: [], forksCount: 0, viewOnlyLinksCount: 0, + preprintsUrl: 'https://api.osf.io/v2/nodes/project-1/preprints/', }; diff --git a/src/testing/mocks/provider.mock.ts b/src/testing/mocks/provider.mock.ts index d027b2e6e..48cfdcc38 100644 --- a/src/testing/mocks/provider.mock.ts +++ b/src/testing/mocks/provider.mock.ts @@ -28,6 +28,7 @@ export const MOCK_PROVIDER = { facebookAppId: null, reviewsCommentsPrivate: null, reviewsCommentsAnonymous: null, + licensesLink: 'https://api.osf.io/v2/providers/collections/1/licenses/', primaryCollection: { id: 'collection-1', title: 'Test Collection',