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/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.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/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/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/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/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/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/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/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/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 d75329824..d741af54c 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", @@ -1435,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.", 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',