[ACS-12333][ACS-12335][ACS-12334] Add Checkout / Check-in Support (#5360)

Co-authored-by: Adam Świderski <adam.tomasz.swiderski@gmail.com>
This commit is contained in:
Mykyta Maliarchuk
2026-09-08 10:57:16 +02:00
committed by GitHub
co-authored by Adam Świderski
parent ff7560b7fc
commit c4f3e988c8
40 changed files with 1271 additions and 311 deletions
+1
View File
@@ -39,6 +39,7 @@
"textitem",
"thumbnailed",
"versionable",
"workingcopy",
"любимый",
"сайт"
],
+4
View File
@@ -61,6 +61,10 @@ Application related evaluators which can be used to check various different aspe
| 7.4.0 | app.selection.isCheckedOut | Checks if selected node contains `cm:checkedOut` aspect. |
| 8.0.0 | app.isKnowledgeDiscoveryUrlPresent | Checks if the Knowledge Discovery URL is specified in the app config. |
| 8.1.0 | app.selection.file.isVersionable | Checks if the selected file has the `cm:versionable` aspect. |
| 8.1.0 | app.selection.isWorkingCopy | Checks if the selected node is a working copy (has the `cm:workingcopy` aspect). |
| 8.1.0 | app.selection.isLockedOrWorkingCopy | Checks if the selected node is locked or checked-out (`cm:workingcopy`/`cm:checkedOut` aspect). |
| 8.1.0 | app.selection.canCheckout | Checks if the selected file can be checked out. |
| 8.1.0 | app.selection.canCancelCheckout | Checks if checkout can be cancelled for the selected checked-out original or working copy. |
#### Navigation Rules/Evaluators
@@ -1,6 +1,17 @@
{
"all": {
"XAT-4845": "https://hyland.atlassian.net/browse/ACS-12214",
"XAT-4835": "https://hyland.atlassian.net/browse/ACS-12214"
"XAT-4835": "https://hyland.atlassian.net/browse/ACS-12214",
"XAT-4843": "https://hyland.atlassian.net/browse/ACS-12752",
"XAT-4859": "https://hyland.atlassian.net/browse/ACS-12752",
"XAT-4860": "https://hyland.atlassian.net/browse/ACS-12752",
"XAT-4846": "https://hyland.atlassian.net/browse/ACS-12752",
"XAT-4861": "https://hyland.atlassian.net/browse/ACS-12752",
"XAT-4862": "https://hyland.atlassian.net/browse/ACS-12752",
"XAT-4863": "https://hyland.atlassian.net/browse/ACS-12752",
"XAT-4864": "https://hyland.atlassian.net/browse/ACS-12752",
"XAT-4865": "https://hyland.atlassian.net/browse/ACS-12752",
"XAT-4866": "https://hyland.atlassian.net/browse/ACS-12752",
"XAT-4867": "https://hyland.atlassian.net/browse/ACS-12752"
}
}
@@ -156,9 +156,9 @@ export function filesLockedByCurrentUser(userDemoted: string, siteName?: string)
await myLibrariesPage.dataTable.performClickFolderOrFileToOpen(siteName);
await checkActionsAvailable(
myLibrariesPage,
testData.fileLockedByUser,
testData.collaboratorToolbarPrimary,
testData.collaboratorLockCurrentUserToolbarMore
testData.fileLockedByUserWorkingCopyName,
testData.collaboratorWorkingCopyToolbarPrimary,
testData.collaboratorLockWorkingCopyToolbarMore
);
});
@@ -167,8 +167,8 @@ export function filesLockedByCurrentUser(userDemoted: string, siteName?: string)
await checkActionsAvailable(
myLibrariesPage,
testData.fileLockedByUser,
testData.collaboratorToolbarPrimary,
testData.collaboratorLockCurrentUserToolbarMore
testData.collaboratorLockedToolbarPrimary,
testData.collaboratorLockedSharedViewerToolbarMore
);
});
@@ -177,18 +177,18 @@ export function filesLockedByCurrentUser(userDemoted: string, siteName?: string)
await checkActionsAvailable(
myLibrariesPage,
testData.fileLockedByUser,
testData.collaboratorToolbarPrimary,
testData.favoritesCollaboratorToolbarMore
testData.collaboratorLockedToolbarPrimary,
testData.favoritesCheckedOutCollaboratorToolbarMore
);
});
test('[XAT-4855] Toolbar - Correct actions appear for file - on Search Results - Locked File', async ({ searchPage, myLibrariesPage }) => {
await searchPage.searchWithin(testData.fileLockedByUser, 'filesAndFolders');
await searchPage.searchWithin(testData.fileLockedByUserWorkingCopyName, 'filesAndFolders');
await checkActionsAvailable(
myLibrariesPage,
testData.fileLockedByUser,
testData.collaboratorToolbarPrimary,
testData.collaboratorLockCurrentUserToolbarMore
testData.fileLockedByUserWorkingCopyName,
testData.collaboratorWorkingCopyToolbarPrimary,
testData.lockedWorkingCopyToolbarMore
);
});
});
@@ -199,9 +199,9 @@ export function filesLockedByCurrentUser(userDemoted: string, siteName?: string)
await myLibrariesPage.dataTable.performClickFolderOrFileToOpen(siteName);
await checkActionsViewerAvailable(
myLibrariesPage,
testData.fileLockedByUser,
testData.collaboratorSharedToolbarPrimary,
testData.collaboratorLockCurrentUserToolbarMore
testData.fileLockedByUserWorkingCopyName,
testData.collaboratorSharedWorkingCopyToolbarPrimary,
testData.collaboratorLockWorkingCopyToolbarMore
);
});
@@ -210,8 +210,8 @@ export function filesLockedByCurrentUser(userDemoted: string, siteName?: string)
await checkActionsViewerAvailable(
myLibrariesPage,
testData.fileLockedByUser,
testData.collaboratorSharedToolbarPrimary,
testData.collaboratorLockCurrentUserToolbarMore
testData.collaboratorLockedOriginalSharedViewerToolbarPrimary,
testData.collaboratorLockedSharedViewerToolbarMore
);
});
@@ -220,16 +220,16 @@ export function filesLockedByCurrentUser(userDemoted: string, siteName?: string)
await checkActionsViewerAvailable(
myLibrariesPage,
testData.fileLockedByUser,
testData.collaboratorSharedToolbarPrimary,
testData.collaboratorLockCurrentUserToolbarMore
testData.collaboratorLockedOriginalSharedViewerToolbarPrimary,
testData.collaboratorLockedSharedViewerToolbarMore
);
});
test('[XAT-4859] Correct actions appear for file opened from Search Results - Locked File', async ({ searchPage, myLibrariesPage }) => {
await searchPage.searchWithin(testData.fileLockedByUser, 'filesAndFolders');
await searchPage.searchWithin(testData.fileLockedByUserWorkingCopyName, 'filesAndFolders');
await checkActionsViewerAvailable(
myLibrariesPage,
testData.fileLockedByUser,
testData.fileLockedByUserWorkingCopyName,
testData.collaboratorSharedToolbarPrimary,
testData.collaboratorLockCurrentUserToolbarMore
);
@@ -68,7 +68,6 @@ test.describe('Special permissions : ', () => {
let folderFav2Id: string;
let managerNodeActions: NodesApi;
let demotedUserActions: NodesApi;
let consumerFavoritesActions: FavoritesPageApi;
let managerFavoritesActions: FavoritesPageApi;
let collaboratorFavoritesActions: FavoritesPageApi;
@@ -78,6 +77,7 @@ test.describe('Special permissions : ', () => {
let consumerShareActions: SharedLinksApi;
let managerSiteActions: SitesApi;
let managerFileActions: FileActionsApi;
let demotedUserFileActions: FileActionsApi;
let managerSearchActions: SearchApi;
test.beforeAll(async () => {
@@ -89,7 +89,6 @@ test.describe('Special permissions : ', () => {
await apiClientFactory.createUser({ username: userDemoted });
managerNodeActions = await NodesApi.initialize(userManager, userManager);
demotedUserActions = await NodesApi.initialize(userDemoted, userDemoted);
consumerFavoritesActions = await FavoritesPageApi.initialize(userConsumer, userConsumer);
collaboratorFavoritesActions = await FavoritesPageApi.initialize(userCollaborator, userCollaborator);
demotedUserFavoritesActions = await FavoritesPageApi.initialize(userDemoted, userDemoted);
@@ -97,6 +96,7 @@ test.describe('Special permissions : ', () => {
managerSearchActions = await SearchApi.initialize(userManager, userManager);
managerSiteActions = await SitesApi.initialize(userManager, userManager);
managerFileActions = await FileActionsApi.initialize(userManager, userManager);
demotedUserFileActions = await FileActionsApi.initialize(userDemoted, userDemoted);
managerUserShareActions = await SharedLinksApi.initialize(userManager, userManager);
demotedUserShareActions = await SharedLinksApi.initialize(userDemoted, userDemoted);
consumerShareActions = await SharedLinksApi.initialize(userConsumer, userConsumer);
@@ -132,7 +132,7 @@ test.describe('Special permissions : ', () => {
.entry.id;
fileLockedByUserId = (await managerNodeActions.createFile(testData.fileLockedByUser, docLibId, '', '', '', true, ['cm:versionable'])).entry.id;
await demotedUserActions.lockNodes([fileLockedByUserId]);
await demotedUserFileActions.checkoutNode(fileLockedByUserId);
await demotedUserFavoritesActions.addFavoriteById('file', fileLockedByUserId);
await demotedUserShareActions.shareFileById(fileLockedByUserId);
await managerSiteActions.updateSiteMember(sitePrivate, userDemoted, Site.RoleEnum.SiteConsumer);
@@ -164,7 +164,12 @@ test.describe('Special permissions : ', () => {
fileGranularPermissionId
]);
await managerNodeActions.lockNodes([fileLockedId, fileFavLockedId, fileSharedLockedId, fileSharedFavLockedId]);
await Promise.all([
managerFileActions.checkoutNode(fileLockedId),
managerFileActions.checkoutNode(fileFavLockedId),
managerFileActions.checkoutNode(fileSharedLockedId),
managerFileActions.checkoutNode(fileSharedFavLockedId)
]);
await managerNodeActions.setGranularPermission(fileGranularPermissionId, userConsumer, Site.RoleEnum.SiteManager, false);
@@ -137,7 +137,7 @@ export function viewerTests(userConsumer: string, siteName: string) {
await checkViewerActions(
loginPage,
myLibrariesPage,
testData.fileLocked.name,
testData.fileLocked.workingCopyName,
testData.fileLocked.viewerToolbarPrimary,
testData.fileLocked.viewerToolbarMore
);
@@ -147,9 +147,9 @@ export function viewerTests(userConsumer: string, siteName: string) {
await checkViewerActions(
loginPage,
myLibrariesPage,
testData.fileFavLocked.name,
testData.fileFavLocked.workingCopyName,
testData.fileFavLocked.viewerToolbarPrimary,
testData.fileFavLocked.viewerToolbarMore
testData.fileFavLocked.workingCopyViewerToolbarMore
);
});
@@ -157,7 +157,7 @@ export function viewerTests(userConsumer: string, siteName: string) {
await checkViewerActions(
loginPage,
myLibrariesPage,
testData.fileSharedLocked.name,
testData.fileSharedLocked.workingCopyName,
testData.fileSharedLocked.viewerToolbarPrimary,
testData.fileSharedLocked.viewerToolbarMore
);
@@ -167,9 +167,9 @@ export function viewerTests(userConsumer: string, siteName: string) {
await checkViewerActions(
loginPage,
myLibrariesPage,
testData.fileSharedFavLocked.name,
testData.fileSharedFavLocked.workingCopyName,
testData.fileSharedFavLocked.viewerToolbarPrimary,
testData.fileSharedFavLocked.viewerToolbarMore
testData.fileSharedFavLocked.workingCopyViewerToolbarMore
);
});
});
@@ -443,7 +443,7 @@ export function viewerTests(userConsumer: string, siteName: string) {
await checkViewerActions(
loginPage,
searchPage,
testData.fileLocked.name,
testData.fileLocked.workingCopyName,
testData.fileLocked.viewerToolbarPrimary,
testData.fileLocked.viewerToolbarMore
);
@@ -453,9 +453,9 @@ export function viewerTests(userConsumer: string, siteName: string) {
await checkViewerActions(
loginPage,
searchPage,
testData.fileFavLocked.name,
testData.fileFavLocked.workingCopyName,
testData.fileFavLocked.viewerToolbarPrimary,
testData.fileFavLocked.viewerToolbarMore
testData.fileFavLocked.workingCopyViewerToolbarMore
);
});
@@ -463,7 +463,7 @@ export function viewerTests(userConsumer: string, siteName: string) {
await checkViewerActions(
loginPage,
searchPage,
testData.fileSharedLocked.name,
testData.fileSharedLocked.workingCopyName,
testData.fileSharedLocked.viewerToolbarPrimary,
testData.fileSharedLocked.viewerToolbarMore
);
@@ -473,7 +473,7 @@ export function viewerTests(userConsumer: string, siteName: string) {
await checkViewerActions(
loginPage,
searchPage,
testData.fileSharedFavLocked.name,
testData.fileSharedFavLocked.workingCopyName,
testData.fileSharedFavLocked.viewerToolbarPrimary,
testData.fileSharedFavLocked.viewerToolbarMore
);
@@ -224,9 +224,8 @@ test.describe('viewer action file', () => {
test('[XAT-5423] Viewer - Edit Offline action - Personal Files', async ({ personalFiles }) => {
await openFileInViewer(personalFiles, fileForEditOffline);
await personalFiles.viewer.toolbar.clickMoreActions();
await personalFiles.matMenu.clickMenuItem('Edit Offline');
const downloadPromise = personalFiles.page.waitForEvent('download');
await personalFiles.viewer.toolbar.downloadButton.click();
await personalFiles.matMenu.clickMenuItem('Edit Offline');
const download = await downloadPromise;
expect(download.suggestedFilename(), 'File should found in download location').toBe(fileForEditOffline);
expect(await personalFiles.viewer.isViewerOpened(), 'Viewer is closed after pressing Full screen').toBe(true);
@@ -239,6 +238,7 @@ test.describe('viewer action file', () => {
const username = `user-${Utils.random()}`;
const fileForCancelEditing = `playwright-file2-${Utils.random()}.docx`;
let folderIdCancelEdit: string;
let workingCopyName: string;
let nodesApi: NodesApi;
let trashcanApi: TrashcanApi;
@@ -251,8 +251,9 @@ test.describe('viewer action file', () => {
const { fileActionsApi } = apis;
folderIdCancelEdit = (await nodesApi.createFolder(`viewer-action-5424-${Utils.random()}`)).entry.id;
const fileForCancelEditingId = (await fileActionsApi.uploadFile(TEST_FILES.DOCX.path, fileForCancelEditing, folderIdCancelEdit)).entry.id;
await fileActionsApi.lockNodes([fileForCancelEditingId]);
await fileActionsApi.isFileLockedWriteWithRetry(fileForCancelEditingId, true);
const workingCopy = await fileActionsApi.checkoutNode(fileForCancelEditingId);
workingCopyName = workingCopy.entry.name;
await fileActionsApi.isFileCheckedOutWithRetry(fileForCancelEditingId, true);
} catch (error) {
console.error(`beforeAll failed: ${error}`);
throw error;
@@ -269,9 +270,10 @@ test.describe('viewer action file', () => {
});
test('[XAT-5424] Viewer - Cancel Editing action - Personal Files', async ({ personalFiles }) => {
await openFileInViewer(personalFiles, fileForCancelEditing);
await openFileInViewer(personalFiles, workingCopyName);
await personalFiles.viewer.toolbar.clickMoreActions();
await personalFiles.matMenu.clickMenuItem('Cancel Editing');
await personalFiles.viewer.waitForViewerToOpen();
await personalFiles.viewer.toolbar.clickMoreActions();
expect(await personalFiles.matMenu.isMenuItemVisible('Edit Offline'), 'Edit offline menu should be visible').toBe(true);
});
+50 -29
View File
@@ -537,8 +537,7 @@
"visible": [
"app.selection.file",
"!app.navigation.isTrashcan",
"canToggleFileLock",
"!app.selection.isCheckedOut"
"canToggleFileLock"
]
}
},
@@ -570,7 +569,8 @@
"app.selection.notEmpty",
"!app.navigation.isTrashcan",
"!app.navigation.isLibraries",
"!isMultiSelection"
"!isMultiSelection",
"!app.selection.isWorkingCopy"
]
}
},
@@ -708,7 +708,8 @@
"app.selection.notEmpty",
"!app.navigation.isTrashcan",
"!app.navigation.isLibraries",
"!app.selection.isNodeLink"
"!app.selection.isNodeLink",
"!app.selection.isLockedOrWorkingCopy"
]
}
},
@@ -725,14 +726,20 @@
"!app.navigation.isTrashcan",
"!app.navigation.isLibraries",
"app.selection.notEmpty",
"app.selection.canDelete"
"app.selection.canDelete",
"!app.selection.isLockedOrWorkingCopy"
]
}
},
{
"id": "app.create.separator.3",
"type": "separator",
"order": 900
},
{
"id": "app.context.menu.node-info",
"title": "APP.ACTIONS.NODE_INFO",
"order": 800,
"order": 950,
"icon": "info",
"actions": {
"click": "NODE_INFORMATION"
@@ -747,11 +754,6 @@
]
}
},
{
"id": "app.create.separator.3",
"type": "separator",
"order": 900
},
{
"id": "app.toolbar.versions",
"order": 1100,
@@ -766,7 +768,8 @@
"app.selection.file.isVersionable",
"!app.navigation.isTrashcan",
"!app.selection.file.isLocked",
"!app.selection.isNodeLink"
"!app.selection.isNodeLink",
"!app.selection.isLockedOrWorkingCopy"
]
}
},
@@ -853,7 +856,8 @@
"app.selection.notEmpty",
"!app.navigation.isTrashcan",
"!app.navigation.isLibraries",
"!isMultiSelection"
"!isMultiSelection",
"!app.selection.isLockedOrWorkingCopy"
]
}
},
@@ -900,7 +904,8 @@
"rules": {
"visible": [
"app.selection.file",
"!app.navigation.isTrashcan"
"!app.navigation.isTrashcan",
"!app.selection.isLockedOrWorkingCopy"
]
}
},
@@ -918,8 +923,7 @@
"visible": [
"app.selection.file",
"!app.navigation.isTrashcan",
"canToggleFileLock",
"!app.selection.isCheckedOut"
"canToggleFileLock"
]
}
},
@@ -1075,7 +1079,8 @@
"app.selection.notEmpty",
"!app.navigation.isTrashcan",
"!app.navigation.isLibraries",
"!app.selection.isNodeLink"
"!app.selection.isNodeLink",
"!app.selection.isLockedOrWorkingCopy"
]
}
},
@@ -1092,14 +1097,20 @@
"!app.navigation.isTrashcan",
"!app.navigation.isLibraries",
"app.selection.notEmpty",
"app.selection.canDelete"
"app.selection.canDelete",
"!app.selection.isLockedOrWorkingCopy"
]
}
},
{
"id": "app.create.separator.3",
"type": "separator",
"order": 1300
},
{
"id": "app.context.menu.node-info",
"title": "APP.ACTIONS.NODE_INFO",
"order": 1200,
"order": 1350,
"icon": "info",
"actions": {
"click": "NODE_INFORMATION"
@@ -1114,11 +1125,6 @@
]
}
},
{
"id": "app.create.separator.3",
"type": "separator",
"order": 1300
},
{
"id": "app.context.menu.versions",
"title": "APP.ACTIONS.VERSIONS",
@@ -1133,7 +1139,8 @@
"app.selection.file.isVersionable",
"!app.navigation.isTrashcan",
"!app.selection.file.isLocked",
"!app.selection.isNodeLink"
"!app.selection.isNodeLink",
"!app.selection.isLockedOrWorkingCopy"
]
}
},
@@ -1365,8 +1372,7 @@
"visible": [
"app.selection.file",
"!app.navigation.isTrashcan",
"canToggleFileLock",
"!app.selection.isCheckedOut"
"canToggleFileLock"
]
}
},
@@ -1487,7 +1493,8 @@
"!app.navigation.isTrashcan",
"!app.navigation.isLibraries",
"app.selection.notEmpty",
"app.selection.canDelete"
"app.selection.canDelete",
"!app.selection.isLockedOrWorkingCopy"
]
}
},
@@ -1510,7 +1517,8 @@
"app.selection.file.isVersionable",
"!app.navigation.isTrashcan",
"!app.selection.file.isLocked",
"!app.selection.isNodeLink"
"!app.selection.isNodeLink",
"!app.selection.isLockedOrWorkingCopy"
]
}
},
@@ -3193,6 +3201,19 @@
}
}
]
},
"badges": [
{
"id": "app.badge.lock",
"icon": "lock",
"tooltip": "",
"component": "app.badge.lock",
"rules": {
"visible": [
"app.selection.isLockedOrWorkingCopy"
]
}
}
]
}
}
+4 -1
View File
@@ -504,7 +504,9 @@
"COLLAPSE_SECTION": "Collapse section",
"EDIT": "Edit",
"CANCEL": "Cancel",
"SAVE": "Save"
"SAVE": "Save",
"LOCK_BADGE": "This document is locked by {{ owner }} for offline editing.",
"WORKING_COPY_BADGE": "Original document is locked by {{ owner }} for offline editing."
},
"NODE_INFO": {
"ICON": "Node Icon",
@@ -746,6 +748,7 @@
}
},
"CHECKOUT": {
"CHECKED_OUT_BY": "Original locked by: ",
"ERRORS": {
"CHECKOUT": {
"400": "This node cannot be checked out. It must be a content (cm:content) node.",
@@ -50,6 +50,7 @@ import { PreviewComponent } from '@alfresco/aca-content/viewer';
import { ToggleEditOfflineComponent } from './components/toolbar/toggle-edit-offline/toggle-edit-offline.component';
import { ToggleFavoriteLibraryComponent } from './components/toolbar/toggle-favorite-library/toggle-favorite-library.component';
import { ToggleFavoriteComponent } from './components/toolbar/toggle-favorite/toggle-favorite.component';
import { LockIconComponent } from './components/dl-custom-components/lock-icon/lock-icon.component';
import { ToggleInfoDrawerComponent } from './components/toolbar/toggle-info-drawer/toggle-info-drawer.component';
import { ToggleJoinLibraryButtonComponent } from './components/toolbar/toggle-join-library/toggle-join-library-button.component';
import { ToggleJoinLibraryMenuComponent } from './components/toolbar/toggle-join-library/toggle-join-library-menu.component';
@@ -124,7 +125,8 @@ import { IsFeatureSupportedInCurrentAcsPipe } from './pipes/is-feature-supported
'app.user.menu': UserMenuComponent,
'app.search.columns.name': SearchResultsRowComponent,
'app.search.navbar': SaveSearchSidenavComponent,
'app.knowledgeDiscovery.sidenav': KnowledgeDiscoverySidenavComponent
'app.knowledgeDiscovery.sidenav': KnowledgeDiscoverySidenavComponent,
'app.badge.lock': LockIconComponent
},
evaluators: {
canToggleJoinLibrary: rules.canToggleJoinLibrary,
@@ -155,7 +157,11 @@ import { IsFeatureSupportedInCurrentAcsPipe } from './pipes/is-feature-supported
'app.selection.folder': rules.hasFolderSelected,
'app.selection.folder.canUpdate': rules.canUpdateSelectedFolder,
'app.selection.isCheckedOut': rules.isCheckedOut,
'app.selection.isWorkingCopy': rules.isWorkingCopy,
'app.selection.canCheckout': rules.canCheckout,
'app.selection.canCancelCheckout': rules.canCancelCheckout,
'app.selection.isNodeLink': rules.isNodeLink,
'app.selection.isLockedOrWorkingCopy': rules.isLockedOrWorkingCopy,
'app.navigation.folder.canCreate': rules.canCreateFolder,
'app.navigation.isTrashcan': rules.isTrashcan,
@@ -0,0 +1,128 @@
/*!
* Copyright © 2005-2026 Hyland Software, Inc. and its affiliates. All rights reserved.
*
* Alfresco Example Content Application
*
* This file is part of the Alfresco Example Content Application.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* The Alfresco Example Content Application is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The Alfresco Example Content Application is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* from Hyland Software. If not, see <http://www.gnu.org/licenses/>.
*/
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { LockIconComponent } from './lock-icon.component';
import { NoopTranslateModule } from '@alfresco/adf-core';
import { NodeEntry } from '@alfresco/js-api';
import { TranslateService } from '@ngx-translate/core';
const lockOwner = { id: 'jdoe', displayName: 'Jane Doe' };
const workingCopyOwner = { id: 'jsmith', displayName: 'John Smith' };
function makeNode(aspectNames: string[], properties: Record<string, unknown> = {}): { node: NodeEntry } {
return {
node: {
entry: {
isFile: true,
id: 'node-id',
aspectNames,
properties
}
} as NodeEntry
};
}
describe('LockIconComponent', () => {
let fixture: ComponentFixture<LockIconComponent>;
let component: LockIconComponent;
let translate: TranslateService;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [NoopTranslateModule, LockIconComponent]
});
fixture = TestBed.createComponent(LockIconComponent);
component = fixture.componentInstance;
translate = TestBed.inject(TranslateService);
spyOn(translate, 'instant').and.callFake((key: string, params?: Record<string, string>) => `${key}:${params?.owner ?? ''}`);
});
describe('working copy (cm:workingcopy aspect)', () => {
beforeEach(() => {
component.data = makeNode(['cm:workingcopy'], { 'cm:workingCopyOwner': workingCopyOwner });
component.ngOnInit();
});
it('should use WORKING_COPY_BADGE translation key', () => {
expect(translate.instant).toHaveBeenCalledWith('APP.TOOLTIPS.WORKING_COPY_BADGE', { owner: workingCopyOwner.displayName });
});
it('should set tooltip with working copy owner name', () => {
expect(component.tooltip).toBe(`APP.TOOLTIPS.WORKING_COPY_BADGE:${workingCopyOwner.displayName}`);
});
});
describe('checked-out original (cm:checkedOut aspect)', () => {
beforeEach(() => {
component.data = makeNode(['cm:checkedOut'], { 'cm:lockOwner': lockOwner });
component.ngOnInit();
});
it('should use LOCK_BADGE translation key', () => {
expect(translate.instant).toHaveBeenCalledWith('APP.TOOLTIPS.LOCK_BADGE', { owner: lockOwner.displayName });
});
it('should set tooltip with lock owner name', () => {
expect(component.tooltip).toBe(`APP.TOOLTIPS.LOCK_BADGE:${lockOwner.displayName}`);
});
});
describe('generic lock (no checkout aspects)', () => {
beforeEach(() => {
component.data = makeNode([], { 'cm:lockOwner': lockOwner });
component.ngOnInit();
});
it('should use LOCK_BADGE translation key', () => {
expect(translate.instant).toHaveBeenCalledWith('APP.TOOLTIPS.LOCK_BADGE', { owner: lockOwner.displayName });
});
it('should set tooltip with lock owner name', () => {
expect(component.tooltip).toBe(`APP.TOOLTIPS.LOCK_BADGE:${lockOwner.displayName}`);
});
});
describe('fallback when owner has no displayName', () => {
it('should fall back to owner id when displayName is absent', () => {
component.data = makeNode([], { 'cm:lockOwner': { id: 'admin' } });
component.ngOnInit();
expect(translate.instant).toHaveBeenCalledWith('APP.TOOLTIPS.LOCK_BADGE', { owner: 'admin' });
});
it('should use empty string when owner property is absent', () => {
component.data = makeNode([], {});
component.ngOnInit();
expect(translate.instant).toHaveBeenCalledWith('APP.TOOLTIPS.LOCK_BADGE', { owner: '' });
});
});
describe('missing data', () => {
it('should not throw when data is undefined', () => {
component.data = undefined;
expect(() => component.ngOnInit()).not.toThrow();
});
});
});
@@ -0,0 +1,55 @@
/*!
* Copyright © 2005-2026 Hyland Software, Inc. and its affiliates. All rights reserved.
*
* Alfresco Example Content Application
*
* This file is part of the Alfresco Example Content Application.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* The Alfresco Example Content Application is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The Alfresco Example Content Application is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* from Hyland Software. If not, see <http://www.gnu.org/licenses/>.
*/
import { Component, inject, Input, OnInit, ViewEncapsulation } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
import { NodeEntry } from '@alfresco/js-api';
import { MatIconModule } from '@angular/material/icon';
@Component({
selector: 'aca-lock-icon',
template: `<mat-icon class="adf-datatable-cell-badge" [title]="tooltip" aria-hidden="true">lock</mat-icon>`,
imports: [MatIconModule],
encapsulation: ViewEncapsulation.None
})
export class LockIconComponent implements OnInit {
private readonly translate = inject(TranslateService);
@Input()
data: { node: NodeEntry };
tooltip: string;
ngOnInit() {
const entry = this.data?.node?.entry;
const aspectNames = entry?.aspectNames ?? [];
const props = entry?.properties ?? {};
// cspell:ignore workingcopy
const isWorkingCopy = aspectNames.includes('cm:workingcopy');
const ownerProp = isWorkingCopy ? props['cm:workingCopyOwner'] : props['cm:lockOwner'];
const key = isWorkingCopy ? 'APP.TOOLTIPS.WORKING_COPY_BADGE' : 'APP.TOOLTIPS.LOCK_BADGE';
this.tooltip = this.translate.instant(key, { owner: ownerProp?.displayName ?? ownerProp?.id ?? '' });
}
}
@@ -15,9 +15,9 @@
{{ displayText$ | async }}
</span>
<ng-container *ngIf="isFile && isFileWriteLocked">
@if (isFile && (isFileWriteLocked || isWorkingCopy)) {
<aca-locked-by [node]="context.row.node" />
</ng-container>
}
</div>
<aca-datatable-cell-badges [node]="node" />
</div>
@@ -23,14 +23,16 @@
*/
import { CustomNameColumnComponent } from './name-column.component';
import { DatatableCellBadgesComponent } from '../datatable-cell-badges/datatable-cell-badges.component';
import { LockedByComponent } from '@alfresco/aca-shared';
import { provideStore } from '@ngrx/store';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { NoopTranslateModule, provideCoreAuth } from '@alfresco/adf-core';
import { NoopTranslateModule, provideCoreAuth, UnitTestingUtils } from '@alfresco/adf-core';
describe('CustomNameColumnComponent', () => {
let fixture: ComponentFixture<CustomNameColumnComponent>;
let component: CustomNameColumnComponent;
let testingUtils: UnitTestingUtils;
beforeEach(() => {
TestBed.configureTestingModule({
@@ -57,6 +59,7 @@ describe('CustomNameColumnComponent', () => {
fixture = TestBed.createComponent(CustomNameColumnComponent);
component = fixture.componentInstance;
testingUtils = new UnitTestingUtils(fixture.debugElement);
});
it('should not render lock element if file is not locked', () => {
@@ -76,7 +79,7 @@ describe('CustomNameColumnComponent', () => {
component.ngOnInit();
fixture.detectChanges();
expect(fixture.debugElement.nativeElement.querySelector('aca-locked-by')).toBe(null);
expect(testingUtils.getByDirective(LockedByComponent)).toBe(null);
});
it('should not render lock element if node is not a file', () => {
@@ -96,7 +99,7 @@ describe('CustomNameColumnComponent', () => {
component.ngOnInit();
fixture.detectChanges();
expect(fixture.debugElement.nativeElement.querySelector('aca-locked-by')).toBe(null);
expect(testingUtils.getByDirective(LockedByComponent)).toBe(null);
});
it('should render lock element if file is locked', () => {
@@ -117,7 +120,7 @@ describe('CustomNameColumnComponent', () => {
component.ngOnInit();
fixture.detectChanges();
expect(fixture.debugElement.nativeElement.querySelector('aca-locked-by')).not.toBe(null);
expect(testingUtils.getByDirective(LockedByComponent)).not.toBe(null);
});
it('should call parent component onClick method', () => {
@@ -138,8 +141,30 @@ describe('CustomNameColumnComponent', () => {
});
it('should pass node to badge component', () => {
const badgeElement = fixture.debugElement.query(By.css('aca-datatable-cell-badges'));
const badgeElement = testingUtils.getByDirective(DatatableCellBadgesComponent);
expect(badgeElement).not.toBe(null);
expect(badgeElement.componentInstance.node).toBe(component.node);
});
it('should render lock element for a working copy (cm:workingcopy aspect)', () => {
component.context = {
row: {
node: {
entry: {
isFile: true,
id: 'nodeId',
name: 'working-copy.txt',
aspectNames: ['cm:workingcopy'],
properties: {}
}
},
getValue: (key: string) => key
}
};
component.ngOnInit();
fixture.detectChanges();
expect(testingUtils.getByDirective(LockedByComponent)).not.toBe(null);
});
});
@@ -27,7 +27,7 @@ import { ChangeDetectorRef, Component, DestroyRef, inject, OnInit, ViewEncapsula
import { Actions, ofType } from '@ngrx/effects';
import { filter } from 'rxjs/operators';
import { NodeActionTypes } from '@alfresco/aca-shared/store';
import { isLocked, LockedByComponent } from '@alfresco/aca-shared';
import { isLocked, isWorkingCopy, LockedByComponent } from '@alfresco/aca-shared';
import { CommonModule } from '@angular/common';
import { TranslatePipe } from '@ngx-translate/core';
import { DatatableCellBadgesComponent } from '../datatable-cell-badges/datatable-cell-badges.component';
@@ -46,6 +46,7 @@ import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
export class CustomNameColumnComponent extends NameColumnComponent implements OnInit {
isFile: boolean;
isFileWriteLocked: boolean;
isWorkingCopy: boolean;
private readonly destroy = inject(DestroyRef);
private readonly cd = inject(ChangeDetectorRef);
@@ -56,6 +57,7 @@ export class CustomNameColumnComponent extends NameColumnComponent implements On
this.updateValue();
this.isFile = this.node?.entry && !this.node.entry.isFolder;
this.isFileWriteLocked = isLocked(this.node);
this.isWorkingCopy = isWorkingCopy(this.node);
this.nodesService.nodeUpdated.pipe(takeUntilDestroyed(this.destroy)).subscribe((node: any) => {
const row = this.context.row;
@@ -72,6 +74,7 @@ export class CustomNameColumnComponent extends NameColumnComponent implements On
this.isFile = this.node?.entry && !this.node.entry.isFolder;
this.isFileWriteLocked = isLocked(this.node);
this.isWorkingCopy = isWorkingCopy(this.node);
}
});
@@ -83,6 +86,7 @@ export class CustomNameColumnComponent extends NameColumnComponent implements On
)
.subscribe(() => {
this.isFileWriteLocked = isLocked(this.node);
this.isWorkingCopy = isWorkingCopy(this.node);
this.cd.detectChanges();
});
}
@@ -61,8 +61,8 @@ describe('RecentFilesComponent', () => {
isFolder: false,
createdAt: null,
modifiedAt: null,
modifiedByUser: null,
createdByUser: null
modifiedByUser: { id: '', displayName: '' },
createdByUser: { id: '', displayName: '' }
}
},
{
@@ -74,8 +74,8 @@ describe('RecentFilesComponent', () => {
isFolder: false,
createdAt: null,
modifiedAt: null,
modifiedByUser: null,
createdByUser: null
modifiedByUser: { id: '', displayName: '' },
createdByUser: { id: '', displayName: '' }
}
}
],
@@ -27,11 +27,9 @@ import { ComponentFixture, TestBed } from '@angular/core/testing';
import { of } from 'rxjs';
import { Store } from '@ngrx/store';
import { NodeEntry } from '@alfresco/js-api';
import { DownloadNodesAction, EditOfflineAction } from '@alfresco/aca-shared/store';
import { CancelCheckoutNodeAction, CheckoutNodeAction } from '@alfresco/aca-shared/store';
import { AppTestingModule } from '../../../testing/app-testing.module';
import { AppExtensionService } from '@alfresco/aca-shared';
import { NotificationService } from '@alfresco/adf-core';
import { MatSnackBarModule } from '@angular/material/snack-bar';
describe('ToggleEditOfflineComponent', () => {
let fixture: ComponentFixture<ToggleEditOfflineComponent>;
@@ -40,7 +38,6 @@ describe('ToggleEditOfflineComponent', () => {
let dispatchSpy: jasmine.Spy;
let selectSpy: jasmine.Spy;
let selection: any;
let showErrorSpy: jasmine.Spy;
const extensionsMock = {
updateSidebarActions: jasmine.createSpy('updateSidebarActions')
@@ -48,7 +45,7 @@ describe('ToggleEditOfflineComponent', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [AppTestingModule, ToggleEditOfflineComponent, MatSnackBarModule],
imports: [AppTestingModule, ToggleEditOfflineComponent],
providers: [
{
provide: Store,
@@ -66,88 +63,71 @@ describe('ToggleEditOfflineComponent', () => {
fixture = TestBed.createComponent(ToggleEditOfflineComponent);
component = fixture.componentInstance;
spyOn(component, 'unlockNode').and.returnValue(Promise.resolve(null));
spyOn(component, 'lockNode').and.returnValue(Promise.resolve(null));
store = TestBed.inject(Store);
store = TestBed.inject(Store);
dispatchSpy = spyOn(store, 'dispatch');
selectSpy = spyOn(store, 'select');
selection = { file: { entry: { name: 'test', properties: {}, isLocked: false } } };
const notificationService = TestBed.inject(NotificationService);
showErrorSpy = spyOn(notificationService, 'showError');
});
it('should initialized with data from store', () => {
it('should initialize selection from store', () => {
selectSpy.and.returnValue(of(selection));
fixture.detectChanges();
expect(component.selection).toEqual(selection.file);
});
it('should download content when node is locked', async () => {
it('should dispatch CheckoutNodeAction when node is not locked', () => {
selectSpy.and.returnValue(of(selection));
fixture.detectChanges();
selection.file.entry.isLocked = false;
await component.onClick();
fixture.detectChanges();
expect(dispatchSpy.calls.argsFor(0)).toEqual([new DownloadNodesAction([selection.file as NodeEntry])]);
});
it('should not download content if node is not locked', () => {
selectSpy.and.returnValue(of(selection));
fixture.detectChanges();
component.onClick();
fixture.detectChanges();
expect(dispatchSpy.calls.argsFor(0)).not.toEqual([new DownloadNodesAction([selection.file as NodeEntry])]);
expect(dispatchSpy).toHaveBeenCalledWith(new CheckoutNodeAction(selection.file as NodeEntry));
});
it('should dispatch EditOfflineAction action', async () => {
selectSpy.and.returnValue(of(selection));
it('should dispatch CancelCheckoutNodeAction when node is locked', () => {
selection.file.entry.isLocked = true;
fixture.detectChanges();
await component.onClick();
fixture.detectChanges();
expect(dispatchSpy.calls.argsFor(0)).toEqual([new EditOfflineAction(selection.file as NodeEntry)]);
});
it('should raise notification on lock error', () => {
selectSpy.and.returnValue(of(selection));
fixture.detectChanges();
component.onLockError();
fixture.detectChanges();
expect(showErrorSpy).toHaveBeenCalledWith('APP.MESSAGES.ERRORS.LOCK_NODE', null, { fileName: 'test' });
});
it('should raise notification on unlock error', () => {
selectSpy.and.returnValue(of(selection));
fixture.detectChanges();
component.onUnlockError();
fixture.detectChanges();
expect(showErrorSpy).toHaveBeenCalledWith('APP.MESSAGES.ERRORS.UNLOCK_NODE', null, { fileName: 'test' });
});
it('should call updateSidebarActions on click', async () => {
selectSpy.and.returnValue(of(selection));
fixture.detectChanges();
await component.onClick();
component.onClick();
expect(dispatchSpy).toHaveBeenCalledWith(new CancelCheckoutNodeAction(selection.file as NodeEntry));
});
it('should dispatch CancelCheckoutNodeAction when node is a working copy', () => {
selection.file.entry.aspectNames = ['cm:workingcopy'];
selectSpy.and.returnValue(of(selection));
fixture.detectChanges();
expect(extensionsMock.updateSidebarActions).toHaveBeenCalled();
component.onClick();
expect(dispatchSpy).toHaveBeenCalledWith(new CancelCheckoutNodeAction(selection.file as NodeEntry));
});
it('should set isNodeLocked to false and nodeTitle to EDIT_OFFLINE for a plain unlocked file', () => {
selectSpy.and.returnValue(of(selection));
fixture.detectChanges();
expect(component.isNodeLocked).toBeFalse();
expect(component.nodeTitle).toBe('APP.ACTIONS.EDIT_OFFLINE');
});
it('should set isNodeLocked to true and nodeTitle to EDIT_OFFLINE_CANCEL for a locked file', () => {
selection.file.entry.isLocked = true;
selectSpy.and.returnValue(of(selection));
fixture.detectChanges();
expect(component.isNodeLocked).toBeTrue();
expect(component.nodeTitle).toBe('APP.ACTIONS.EDIT_OFFLINE_CANCEL');
});
it('should set isNodeLocked to true for a working copy', () => {
selection.file.entry.aspectNames = ['cm:workingcopy'];
selectSpy.and.returnValue(of(selection));
fixture.detectChanges();
expect(component.isNodeLocked).toBeTrue();
});
});
@@ -22,13 +22,11 @@
* from Hyland Software. If not, see <http://www.gnu.org/licenses/>.
*/
import { AppStore, DownloadNodesAction, EditOfflineAction, SetSelectedNodesAction, getAppSelection } from '@alfresco/aca-shared/store';
import { NodeEntry, SharedLinkEntry, Node, NodesApi, LazyApi } from '@alfresco/js-api';
import { AppStore, CancelCheckoutNodeAction, CheckoutNodeAction, getAppSelection } from '@alfresco/aca-shared/store';
import { NodeEntry } from '@alfresco/js-api';
import { Component, inject, OnInit, ViewChild, ViewEncapsulation } from '@angular/core';
import { Store } from '@ngrx/store';
import { AppExtensionService, isLocked } from '@alfresco/aca-shared';
import { NotificationService } from '@alfresco/adf-core';
import { AlfrescoApiService } from '@alfresco/adf-content-services';
import { CommonModule } from '@angular/common';
import { TranslatePipe } from '@ngx-translate/core';
import { MatMenuItem, MatMenuModule } from '@angular/material/menu';
@@ -48,17 +46,11 @@ import { MatIconModule } from '@angular/material/icon';
})
export class ToggleEditOfflineComponent implements OnInit {
private readonly store = inject<Store<AppStore>>(Store);
private readonly alfrescoApiService = inject(AlfrescoApiService);
private readonly extensions = inject(AppExtensionService);
@ViewChild(MatMenuItem)
menuItem: MatMenuItem;
private readonly notificationService = inject(NotificationService);
@LazyApi((self: ToggleEditOfflineComponent) => new NodesApi(self.alfrescoApiService.getInstance()))
declare private readonly nodesApi: NodesApi;
selection: NodeEntry;
nodeTitle = '';
isNodeLocked = false;
@@ -66,71 +58,21 @@ export class ToggleEditOfflineComponent implements OnInit {
ngOnInit() {
this.store.select(getAppSelection).subscribe(({ file }) => {
this.selection = file;
this.isNodeLocked = this.selection && isLocked(this.selection);
this.isNodeLocked = this.selection && this.isCancelable(this.selection);
this.nodeTitle = this.isNodeLocked ? 'APP.ACTIONS.EDIT_OFFLINE_CANCEL' : 'APP.ACTIONS.EDIT_OFFLINE';
});
}
async onClick() {
await this.toggleLock(this.selection);
onClick() {
if (this.isCancelable(this.selection)) {
this.store.dispatch(new CancelCheckoutNodeAction(this.selection));
} else {
this.store.dispatch(new CheckoutNodeAction(this.selection));
}
this.extensions.updateSidebarActions();
}
private async toggleLock(node: NodeEntry | SharedLinkEntry) {
const id = (node as SharedLinkEntry).entry.nodeId || node.entry.id;
if (isLocked(this.selection)) {
try {
const response = await this.unlockNode(id);
this.update(response?.entry);
this.store.dispatch(new EditOfflineAction(this.selection));
this.store.dispatch(new SetSelectedNodesAction([this.selection]));
} catch {
this.onUnlockError();
}
} else {
try {
const response = await this.lockNode(id);
this.update(response?.entry);
this.store.dispatch(new DownloadNodesAction([this.selection]));
this.store.dispatch(new EditOfflineAction(this.selection));
this.store.dispatch(new SetSelectedNodesAction([this.selection]));
} catch {
this.onLockError();
}
}
}
onLockError() {
this.notificationService.showError('APP.MESSAGES.ERRORS.LOCK_NODE', null, { fileName: this.selection.entry.name });
}
onUnlockError() {
this.notificationService.showError('APP.MESSAGES.ERRORS.UNLOCK_NODE', null, { fileName: this.selection.entry.name });
}
lockNode(nodeId: string) {
return this.nodesApi.lockNode(nodeId, {
type: 'ALLOW_OWNER_CHANGES',
lifetime: 'PERSISTENT'
});
}
unlockNode(nodeId: string) {
return this.nodesApi.unlockNode(nodeId);
}
private update(data: Node) {
if (data?.properties) {
const properties = this.selection.entry.properties || {};
properties['cm:lockLifetime'] = data.properties['cm:lockLifetime'];
properties['cm:lockOwner'] = data.properties['cm:lockOwner'];
properties['cm:lockType'] = data.properties['cm:lockType'];
this.selection.entry.properties = properties;
}
private isCancelable(node: NodeEntry): boolean {
return isLocked(node) || (node?.entry?.aspectNames ?? []).includes('cm:workingcopy');
}
}
@@ -368,4 +368,49 @@ describe('DocumentListDirective', () => {
expect(elementRefMock.nativeElement.querySelector).not.toHaveBeenCalled();
expect(documentListMock.preselectNodes).toEqual([]);
}));
describe('rowFilter for cm:checkedOut nodes', () => {
beforeEach(() => {
documentListMock.rowFilter = undefined;
});
it('should set rowFilter on folder views (personal-files)', () => {
mockRouter.url = '/personal-files';
documentListDirective.ngOnInit();
expect(documentListMock.rowFilter).toBeDefined();
});
it('should not set rowFilter on /favorites', () => {
mockRouter.url = '/favorites';
documentListDirective.ngOnInit();
expect(documentListMock.rowFilter).toBeUndefined();
});
it('should not set rowFilter on /shared', () => {
mockRouter.url = '/shared';
documentListDirective.ngOnInit();
expect(documentListMock.rowFilter).toBeUndefined();
});
it('rowFilter should return false for cm:checkedOut nodes', () => {
mockRouter.url = '/personal-files';
documentListDirective.ngOnInit();
const result = documentListMock.rowFilter({ node: { entry: { aspectNames: ['cm:checkedOut'] } } });
expect(result).toBeFalse();
});
it('rowFilter should return true for nodes without cm:checkedOut', () => {
mockRouter.url = '/personal-files';
documentListDirective.ngOnInit();
const result = documentListMock.rowFilter({ node: { entry: { aspectNames: ['cm:titled'] } } });
expect(result).toBeTrue();
});
it('rowFilter should return true when aspectNames is undefined', () => {
mockRouter.url = '/personal-files';
documentListDirective.ngOnInit();
const result = documentListMock.rowFilter({ node: { entry: {} } });
expect(result).toBeTrue();
});
});
});
@@ -64,6 +64,13 @@ export class DocumentListDirective implements OnInit {
ngOnInit() {
this.documentList.stickyHeader = true;
this.documentList.includeFields = this.documentList.currentFolderId === '-recent-' ? SEARCH_INCLUDE_FIELDS : INCLUDE_FIELDS;
const url = this.router.url;
const isFolderView = !url.startsWith('/favorites') && !url.startsWith('/shared');
if (isFolderView) {
this.documentList.rowFilter = ({ node }) => !(node?.entry?.aspectNames ?? []).includes('cm:checkedOut');
}
this.isLibrary =
this.documentList.currentFolderId === '-mysites-' ||
// workaround for custom node list
@@ -39,6 +39,7 @@ import {
ShareNodeAction,
ShowLoaderAction,
UnlockWriteAction,
ViewNodeAction,
ViewNodeVersionAction
} from '@alfresco/aca-shared/store';
import { NodeEffects } from '../store/effects/node.effects';
@@ -1625,8 +1626,9 @@ describe('ContentManagementService', () => {
spyOnOpenUploadNewVersionDialog.and.returnValue(
of({ action: NewVersionUploaderDataAction.upload, newVersion: mockNewVersion, currentVersion: fakeNode })
);
spyOn(documentListService, 'reload');
contentManagementService.versionUpdateDialog(fakeNode, fakeFile);
expect(spyOnDispatch).toHaveBeenCalledOnceWith(new UnlockWriteAction(mockNewVersion.value));
expect(spyOnDispatch).toHaveBeenCalledWith(new UnlockWriteAction(mockNewVersion.value));
});
it('should unlock node if is locked when uploading a file', () => {
@@ -1636,6 +1638,53 @@ describe('ContentManagementService', () => {
expect(showErrorSpy).toHaveBeenCalledOnceWith(fakeError);
});
it('should reload document list after upload', () => {
const uploadData = {
action: NewVersionUploaderDataAction.upload,
newVersion: { value: { entry: { id: 'uploaded-id', properties: {} } } },
currentVersion: fakeNode
};
spyOnOpenUploadNewVersionDialog.and.returnValue(of(uploadData));
spyOn(documentListService, 'reload');
contentManagementService.versionUpdateDialog(fakeNode, fakeFile);
expect(documentListService.reload).toHaveBeenCalled();
});
it('should dispatch RefreshPreviewAction for a regular (non-working-copy) upload', () => {
const uploadedEntry = { id: 'uploaded-id', properties: {} };
const uploadData = {
action: NewVersionUploaderDataAction.upload,
newVersion: { value: { entry: uploadedEntry } },
currentVersion: fakeNode
};
spyOnOpenUploadNewVersionDialog.and.returnValue(of(uploadData));
spyOn(documentListService, 'reload');
contentManagementService.versionUpdateDialog(fakeNode, fakeFile);
expect(spyOnDispatch).toHaveBeenCalledWith(new RefreshPreviewAction(uploadedEntry as Node));
});
it('should dispatch ViewNodeAction when checking in a working copy from the viewer', () => {
fakeNode.aspectNames = ['cm:workingcopy'];
fakeNode.id = 'wc-id';
const uploadedEntry = { id: 'original-id', properties: {} };
const uploadData = {
action: NewVersionUploaderDataAction.upload,
newVersion: { value: { entry: uploadedEntry } },
currentVersion: fakeNode
};
spyOnOpenUploadNewVersionDialog.and.returnValue(of(uploadData));
spyOn(documentListService, 'reload');
spyOnProperty(router, 'url', 'get').and.returnValue('/personal-files/preview/wc-id');
contentManagementService.versionUpdateDialog(fakeNode, fakeFile);
expect(spyOnDispatch).toHaveBeenCalledWith(new ViewNodeAction('original-id', { location: '/personal-files/preview/wc-id' }));
});
});
describe('manageVersions', () => {
@@ -35,6 +35,7 @@ import {
SetSelectedNodesAction,
ShowLoaderAction,
UnlockWriteAction,
ViewNodeAction,
ViewNodeVersionAction
} from '@alfresco/aca-shared/store';
import {
@@ -187,9 +188,21 @@ export class ContentManagementService {
this.newVersionUploaderService.openUploadNewVersionDialog(newVersionUploaderDialogData, dialogConfig).subscribe(
(data) => {
if (data.action === NewVersionUploaderDataAction.upload) {
if (data.newVersion.value.entry.properties['cm:lockType'] === 'WRITE_LOCK') {
const uploadedEntry = data.newVersion.value.entry;
if (uploadedEntry.properties?.['cm:lockType'] === 'WRITE_LOCK') {
this.store.dispatch(new UnlockWriteAction(data.newVersion.value));
}
this.documentListService.reload();
const isWorkingCopy = (node.aspectNames ?? []).includes('cm:workingcopy');
if (isWorkingCopy && uploadedEntry.id !== node.id && this.isInViewer()) {
const location = this.activatedRoute.snapshot.queryParams['location'] || this.router.url;
this.store.dispatch(new ViewNodeAction(uploadedEntry.id, { location }));
} else {
this.store.dispatch(new RefreshPreviewAction(uploadedEntry));
}
}
},
(error) => this.notificationService.showError(error)
@@ -1285,4 +1298,9 @@ export class ContentManagementService {
width: '700px'
});
}
private isInViewer(): boolean {
const url = this.router.url;
return url.includes('/preview/') || url.includes('viewer:view') || url.includes('/view/');
}
}
@@ -29,11 +29,14 @@ import { provideEffects } from '@ngrx/effects';
import { Store } from '@ngrx/store';
import { ContentManagementService } from '../../services/content-management.service';
import {
CancelCheckoutNodeAction,
CheckoutNodeAction,
CopyNodesAction,
CreateFolderAction,
DeletedNodeInfo,
DeleteNodesAction,
EditFolderAction,
EditOfflineAction,
ExpandInfoDrawerAction,
NodeInformationAction,
FullscreenViewerAction,
@@ -52,16 +55,18 @@ import {
UndoDeleteNodesAction,
UnlockWriteAction,
UnshareNodesAction,
ViewNodeAction,
LinkNodesAction,
LocateLinkedItemAction
} from '@alfresco/aca-shared/store';
import { RenditionService } from '@alfresco/adf-content-services';
import { DocumentListService, RenditionService } from '@alfresco/adf-content-services';
import { AppHookService } from '@alfresco/aca-shared';
import { ViewerEffects } from './viewer.effects';
import { ActivatedRoute, NavigationEnd, Router } from '@angular/router';
import { of } from 'rxjs';
import { MatDialogModule } from '@angular/material/dialog';
import { MatSnackBarModule } from '@angular/material/snack-bar';
import { NodeEntry, UserInfo } from '@alfresco/js-api';
import { NodeEntry, SharedLinkEntry, UserInfo } from '@alfresco/js-api';
import { Node } from '@alfresco/js-api/typings/src/api/content-rest-api/model/node';
describe('NodeEffects', () => {
@@ -745,4 +750,103 @@ describe('NodeEffects', () => {
expect(contentService.showNodeInformation).toHaveBeenCalledWith(node);
}));
});
describe('checkout$', () => {
let documentListService: DocumentListService;
let appHookService: AppHookService;
beforeEach(() => {
documentListService = TestBed.inject(DocumentListService);
appHookService = TestBed.inject(AppHookService);
spyOn(documentListService, 'reload').and.stub();
spyOn(appHookService.nodeToSelect$, 'next');
});
it('should call checkout with the node id from payload', () => {
const node = { entry: { id: 'node-id' } } as NodeEntry;
spyOn(contentService, 'checkout').and.returnValue(of({ entry: { id: 'wc-id' } } as NodeEntry));
store.dispatch(new CheckoutNodeAction(node));
expect(contentService.checkout).toHaveBeenCalledWith('node-id');
});
it('should prefer nodeId over id for shared link nodes', () => {
const node = { entry: { nodeId: 'shared-node-id', id: 'link-id' } } as SharedLinkEntry;
spyOn(contentService, 'checkout').and.returnValue(of({ entry: { id: 'wc-id' } } as NodeEntry));
store.dispatch(new CheckoutNodeAction(node as NodeEntry));
expect(contentService.checkout).toHaveBeenCalledWith('shared-node-id');
});
it('should reload document list and dispatch EditOfflineAction on success', () => {
const node = { entry: { id: 'node-id' } } as NodeEntry;
const workingCopy = { entry: { id: 'wc-id' } } as NodeEntry;
spyOn(contentService, 'checkout').and.returnValue(of(workingCopy));
spyOn(store, 'dispatch').and.callThrough();
store.dispatch(new CheckoutNodeAction(node));
expect(documentListService.reload).toHaveBeenCalled();
expect(appHookService.nodeToSelect$.next).toHaveBeenCalledWith(workingCopy);
expect(store.dispatch).toHaveBeenCalledWith(jasmine.objectContaining({ ...new EditOfflineAction(node) }));
});
it('should preselect original node and not open viewer on favorites/shared where working copy is not shown', () => {
spyOnProperty(router, 'url', 'get').and.returnValue('/favorites');
const node = { entry: { id: 'node-id' } } as NodeEntry;
const workingCopy = { entry: { id: 'wc-id' } } as NodeEntry;
spyOn(contentService, 'checkout').and.returnValue(of(workingCopy));
spyOn(store, 'dispatch').and.callThrough();
store.dispatch(new CheckoutNodeAction(node));
expect(appHookService.nodeToSelect$.next).toHaveBeenCalledWith(node);
expect(store.dispatch).not.toHaveBeenCalledWith(jasmine.objectContaining({ ...new ViewNodeAction(workingCopy.entry.id) }));
});
});
describe('cancelCheckout$', () => {
let documentListService: DocumentListService;
let appHookService: AppHookService;
beforeEach(() => {
documentListService = TestBed.inject(DocumentListService);
appHookService = TestBed.inject(AppHookService);
spyOn(documentListService, 'reload').and.stub();
spyOn(appHookService.nodeToSelect$, 'next');
});
it('should call cancelCheckout with the node id from payload', () => {
const node = { entry: { id: 'wc-id' } } as NodeEntry;
spyOn(contentService, 'cancelCheckout').and.returnValue(of({ entry: { id: 'original-id' } } as NodeEntry));
store.dispatch(new CancelCheckoutNodeAction(node));
expect(contentService.cancelCheckout).toHaveBeenCalledWith('wc-id');
});
it('should prefer nodeId over id for shared link nodes', () => {
const node = { entry: { nodeId: 'shared-node-id', id: 'link-id' } } as SharedLinkEntry;
spyOn(contentService, 'cancelCheckout').and.returnValue(of({ entry: { id: 'original-id' } } as NodeEntry));
store.dispatch(new CancelCheckoutNodeAction(node as NodeEntry));
expect(contentService.cancelCheckout).toHaveBeenCalledWith('shared-node-id');
});
it('should reload document list and dispatch EditOfflineAction on success', () => {
const node = { entry: { id: 'wc-id' } } as NodeEntry;
const originalNode = { entry: { id: 'original-id' } } as NodeEntry;
spyOn(contentService, 'cancelCheckout').and.returnValue(of(originalNode));
spyOn(store, 'dispatch').and.callThrough();
store.dispatch(new CancelCheckoutNodeAction(node));
expect(documentListService.reload).toHaveBeenCalled();
expect(appHookService.nodeToSelect$.next).toHaveBeenCalledWith(originalNode);
expect(store.dispatch).toHaveBeenCalledWith(jasmine.objectContaining({ ...new EditOfflineAction(node) }));
});
});
});
@@ -28,10 +28,14 @@ import { first, map, take } from 'rxjs/operators';
import { Store } from '@ngrx/store';
import {
AppStore,
CancelCheckoutNodeAction,
CheckoutNodeAction,
CopyNodesAction,
CreateFolderAction,
DeleteNodesAction,
DownloadNodesAction,
EditFolderAction,
EditOfflineAction,
ExpandInfoDrawerAction,
getAppSelection,
getCurrentFolder,
@@ -54,13 +58,15 @@ import {
ShareNodeAction,
UndoDeleteNodesAction,
UnlockWriteAction,
UnshareNodesAction
UnshareNodesAction,
ViewNodeAction
} from '@alfresco/aca-shared/store';
import { ContentManagementService } from '../../services/content-management.service';
import { RenditionService } from '@alfresco/adf-content-services';
import { AppHookService } from '@alfresco/aca-shared';
import { DocumentListService, RenditionService } from '@alfresco/adf-content-services';
import { ActivatedRoute, NavigationEnd, Router } from '@angular/router';
import { DomSanitizer } from '@angular/platform-browser';
import { Node } from '@alfresco/js-api';
import { Node, SharedLink } from '@alfresco/js-api';
@Injectable()
export class NodeEffects {
@@ -68,6 +74,8 @@ export class NodeEffects {
private readonly actions$ = inject(Actions);
private readonly router = inject(Router);
private readonly contentService = inject(ContentManagementService);
private readonly documentListService = inject(DocumentListService);
private readonly appHookService = inject(AppHookService);
private readonly renditionViewer = inject(RenditionService);
private readonly activatedRoute = inject(ActivatedRoute);
private readonly sanitizer = inject(DomSanitizer);
@@ -454,6 +462,58 @@ export class NodeEffects {
{ dispatch: false }
);
checkout$ = createEffect(
() =>
this.actions$.pipe(
ofType<CheckoutNodeAction>(NodeActionTypes.CheckoutNode),
map((action) => {
const nodeEntry = action.payload;
const id = (nodeEntry.entry as SharedLink).nodeId ?? nodeEntry.entry.id;
const inViewer = this.isInViewer();
const viewerExtras = inViewer ? this.currentViewerExtras() : undefined;
this.contentService.checkout(id).subscribe({
next: (workingCopy) => {
const nodeToSelect = this.isWorkingCopyVisible() ? workingCopy : nodeEntry;
this.appHookService.nodeToSelect$.next(nodeToSelect);
this.documentListService.reload();
this.store.dispatch(new DownloadNodesAction([nodeEntry]));
this.store.dispatch(new EditOfflineAction(nodeEntry));
if (inViewer && this.isWorkingCopyVisible()) {
this.store.dispatch(new ViewNodeAction(workingCopy.entry.id, viewerExtras));
}
}
});
})
),
{ dispatch: false }
);
cancelCheckout$ = createEffect(
() =>
this.actions$.pipe(
ofType<CancelCheckoutNodeAction>(NodeActionTypes.CancelCheckoutNode),
map((action) => {
const nodeEntry = action.payload;
const id = (nodeEntry.entry as SharedLink).nodeId ?? nodeEntry.entry.id;
const inViewer = this.isInViewer();
const viewerExtras = inViewer ? this.currentViewerExtras() : undefined;
this.contentService.cancelCheckout(id).subscribe({
next: (originalNode) => {
this.appHookService.nodeToSelect$.next(originalNode);
this.documentListService.reload();
this.store.dispatch(new EditOfflineAction(nodeEntry));
if (inViewer) {
this.store.dispatch(new ViewNodeAction(originalNode.entry.id, viewerExtras));
}
}
});
})
),
{ dispatch: false }
);
aspectList$ = createEffect(
() =>
this.actions$.pipe(
@@ -536,4 +596,26 @@ export class NodeEffects {
const isRepository = location?.includes('/repository') || getNodeContentSource(entry?.path) === 'repository';
return `${isRepository ? 'repository' : 'personal-files'}/details`;
}
private isInViewer(): boolean {
const url = this.router.url;
return url.includes('/preview/') || url.includes('viewer:view') || url.includes('/view/');
}
private isWorkingCopyVisible(): boolean {
const url = this.router.url;
return !url.startsWith('/favorites') && !url.startsWith('/shared');
}
private currentViewerExtras() {
const tree = this.router.parseUrl(this.router.url);
const { location, path } = tree.queryParams;
if (location) {
return { location };
}
if (path) {
return { path };
}
return undefined;
}
}
@@ -5,6 +5,7 @@
}"
[maxRetries]="settings.viewerMaxRetries"
[nodeId]="nodeId"
[readOnly]="node?.aspectNames?.includes('cm:checkedOut')"
[versionId]="versionId"
[allowNavigate]="navigateMultiple"
[allowRightSidebar]="true"
@@ -24,8 +24,15 @@
import { ActivatedRoute, Router } from '@angular/router';
import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing';
import { AuthenticationService } from '@alfresco/adf-core';
import { DiscoveryApiService, DocumentListService, FileUploadCompleteEvent, NodesApiService, UploadService } from '@alfresco/adf-content-services';
import { AuthenticationService, UnitTestingUtils } from '@alfresco/adf-core';
import {
AlfrescoViewerComponent,
DiscoveryApiService,
DocumentListService,
FileUploadCompleteEvent,
NodesApiService,
UploadService
} from '@alfresco/adf-content-services';
import { ClosePreviewAction, RefreshPreviewAction, ViewNodeAction } from '@alfresco/aca-shared/store';
import { AcaViewerComponent } from './viewer.component';
import { of } from 'rxjs';
@@ -64,6 +71,7 @@ describe('AcaViewerComponent', () => {
let appHookService: AppHookService;
let documentListService: DocumentListService;
let store: Store<any>;
let testingUtils: UnitTestingUtils;
beforeEach(() => {
TestBed.configureTestingModule({
@@ -86,6 +94,7 @@ describe('AcaViewerComponent', () => {
appHookService = TestBed.inject(AppHookService);
documentListService = TestBed.inject(DocumentListService);
store = TestBed.inject(Store);
testingUtils = new UnitTestingUtils(fixture.debugElement);
});
it('should set folderId and call displayNode with nodeId upon init', () => {
@@ -189,6 +198,39 @@ describe('AcaViewerComponent', () => {
expect(contentApi.getNodeInfo).toHaveBeenCalledWith('displayed-node');
}));
it('should navigate the viewer to the original node when a working copy is checked in on new version upload', fakeAsync(() => {
spyOn(store, 'dispatch');
spyOn(component, 'displayNode').and.stub();
fixture.detectChanges();
component.nodeId = 'working-copy-node';
component.node = { id: 'working-copy-node', aspectNames: ['cm:workingcopy'] } as Node;
uploadService.fileUploadComplete.next({
file: { id: 'working-copy-node' },
data: { entry: { id: 'original-node' } }
} as FileUploadCompleteEvent);
tick(300);
expect(store.dispatch).toHaveBeenCalledWith(jasmine.objectContaining({ ...new ViewNodeAction('original-node', { location: router.url }) }));
expect(component.displayNode).not.toHaveBeenCalled();
}));
it('should set readOnly on the viewer when the node is a checked-out original (cm:checkedOut aspect)', () => {
component.nodeId = 'checked-out-node';
component.node = { id: 'checked-out-node', aspectNames: ['cm:checkedOut'] } as Node;
fixture.detectChanges();
expect(testingUtils.getByDirective(AlfrescoViewerComponent).componentInstance.readOnly).toBe(true);
});
it('should not set readOnly on the viewer when the node is not checked out', () => {
component.nodeId = 'regular-node';
component.node = { id: 'regular-node', aspectNames: [] } as Node;
fixture.detectChanges();
expect(testingUtils.getByDirective(AlfrescoViewerComponent).componentInstance.readOnly).toBe(false);
});
describe('return on event', () => {
beforeEach(async () => {
spyOn<any>(component, 'navigateToFileLocation');
@@ -187,10 +187,15 @@ export class AcaViewerComponent implements OnInit, OnDestroy {
this.uploadService.fileUploadDeleted.pipe(takeUntilDestroyed(this.destroyRef)).subscribe(() => this.navigateToFileLocation());
this.uploadService.fileUploadComplete.pipe(debounceTime(300), takeUntilDestroyed(this.destroyRef)).subscribe((file) => {
this.nodesApiService.nodeUpdated.next(file.data.entry);
if (file.data.entry.id === this.nodeId) {
void this.displayNode(file.data.entry.id);
this.uploadService.fileUploadComplete.pipe(debounceTime(300), takeUntilDestroyed(this.destroyRef)).subscribe((event) => {
const uploadedEntry = event.data.entry;
this.nodesApiService.nodeUpdated.next(uploadedEntry);
if (this.node?.aspectNames?.includes('cm:workingcopy') && event.file?.id === this.nodeId && uploadedEntry.id !== this.nodeId) {
const location = this.route.snapshot.queryParams['location'] || this.router.url;
this.store.dispatch(new ViewNodeAction(uploadedEntry.id, { location }));
} else if (uploadedEntry.id === this.nodeId) {
void this.displayNode(uploadedEntry.id);
}
});
@@ -218,4 +218,66 @@ describe('ViewerService', () => {
it('should return empty array when there are no nodes', async () => {
expect(await viewerService.getFileIds('', null)).toEqual([]);
});
describe('cm:checkedOut filtering for personal-files and libraries', () => {
beforeEach(() => {
spyOn(preferences, 'get').and.returnValues(...preferencesNoCurSortValues);
});
it('should exclude cm:checkedOut nodes from personal-files results', async () => {
const listWithCheckedOut = {
list: {
entries: [
{ entry: { id: 'node1', name: 'node 1', aspectNames: [] } },
{ entry: { id: 'node2', name: 'node 2', aspectNames: ['cm:checkedOut'] } },
{ entry: { id: 'node3', name: 'node 3', aspectNames: ['cm:titled'] } }
]
}
} as NodePaging;
spyOn(contentApi, 'getNodeChildren').and.returnValue(of(listWithCheckedOut));
const ids = await viewerService.getFileIds('personal-files', 'folder1');
expect(ids).toEqual(['node1', 'node3']);
});
it('should exclude cm:checkedOut nodes from libraries results', async () => {
const listWithCheckedOut = {
list: {
entries: [
{ entry: { id: 'node1', name: 'node 1', aspectNames: ['cm:checkedOut'] } },
{ entry: { id: 'node2', name: 'node 2', aspectNames: [] } }
]
}
} as NodePaging;
spyOn(contentApi, 'getNodeChildren').and.returnValue(of(listWithCheckedOut));
const ids = await viewerService.getFileIds('libraries', 'folder1');
expect(ids).toEqual(['node2']);
});
it('should include nodes when aspectNames is undefined', async () => {
const listWithUndefinedAspects = {
list: {
entries: [{ entry: { id: 'node1', name: 'node 1' } }, { entry: { id: 'node2', name: 'node 2', aspectNames: undefined } }]
}
} as NodePaging;
spyOn(contentApi, 'getNodeChildren').and.returnValue(of(listWithUndefinedAspects));
const ids = await viewerService.getFileIds('personal-files', 'folder1');
expect(ids).toEqual(['node1', 'node2']);
});
it('should pass aspectNames in include and fields to getNodeChildren', async () => {
spyOn(contentApi, 'getNodeChildren').and.returnValue(of(list as NodePaging));
await viewerService.getFileIds('personal-files', 'folder1');
const callArgs = (contentApi.getNodeChildren as jasmine.Spy).calls.mostRecent().args[1];
expect(callArgs.include).toEqual(['aspectNames']);
expect(callArgs.fields).toContain('aspectNames');
});
});
});
@@ -111,13 +111,18 @@ export class ViewerService {
return [];
}
const orderBy = isClient ? null : ['isFolder desc', `${sortKey} ${sortDirection}`];
nodes = await this.contentApi
const result = await this.contentApi
.getNodeChildren(folderId, {
orderBy: orderBy,
fields: this.getFields(sortKey, previousSortKey),
include: ['aspectNames'],
fields: [...this.getFields(sortKey, previousSortKey), 'aspectNames'],
where: '(isFile=true)'
})
.toPromise();
if (result) {
result.list.entries = result.list.entries.filter((e) => !e.entry.aspectNames?.includes('cm:checkedOut'));
}
nodes = result;
}
if (source === 'favorites') {
@@ -135,6 +135,10 @@ export class FileActionsApi {
} catch {}
}
async checkoutNode(nodeId: string): Promise<NodeEntry> {
return this.apiService.nodes.checkoutNode(nodeId);
}
async getNodeById(id: string): Promise<NodeEntry | null> {
try {
return this.apiService.nodes.getNode(id);
@@ -143,42 +147,21 @@ export class FileActionsApi {
}
}
async getNodeProperty(nodeId: string, property: string): Promise<string> {
async isFileCheckedOutWithRetry(nodeId: string, expect: boolean): Promise<boolean> {
const data = { expect, retry: 5 };
let isCheckedOut = false;
try {
const check = async () => {
const node = await this.getNodeById(nodeId);
return node?.entry?.properties?.[property] || '';
} catch {
return '';
isCheckedOut = (node?.entry?.aspectNames ?? []).includes('cm:checkedOut');
if (isCheckedOut !== data.expect) {
return Promise.reject(new Error(`Checked-out state mismatch: expected=${data.expect}, actual=${isCheckedOut}`));
}
}
private async getLockType(nodeId: string): Promise<string> {
try {
const lockType = await this.getNodeProperty(nodeId, 'cm:lockType');
return lockType || '';
} catch {
return '';
}
}
async isFileLockedWriteWithRetry(nodeId: string, expect: boolean): Promise<boolean> {
const data = {
expect: expect,
retry: 5
return Promise.resolve(isCheckedOut);
};
let isLocked = false;
try {
const locked = async () => {
isLocked = (await this.getLockType(nodeId)) === 'WRITE_LOCK';
if (isLocked !== data.expect) {
return Promise.reject(isLocked);
} else {
return Promise.resolve(isLocked);
}
};
return await Utils.retryCall(locked, data.retry);
return await Utils.retryCall(check, data.retry);
} catch {}
return isLocked;
return isCheckedOut;
}
private async queryNodesNames(searchTerm: string): Promise<ResultSetPaging> {
@@ -43,6 +43,7 @@ const consumerToolbarMore = ['Favorite', 'Copy', 'Manage Versions'];
const consumerFavToolbarMore = ['Remove Favorite', 'Copy', 'Manage Versions'];
export const collaboratorToolbarPrimary = ['Shared Link Settings', 'Download', 'View', 'View Details', 'More Actions'];
export const collaboratorWorkingCopyToolbarPrimary = ['View', 'View Details', 'More Actions'];
export const collaboratorEditRowToolbarMore = [
'Edit Offline',
'Upload New Version',
@@ -52,6 +53,7 @@ export const collaboratorEditRowToolbarMore = [
'Edit Aspects',
'Permissions'
];
export const favoritesCheckedOutCollaboratorToolbarMore = ['Cancel Editing', 'Upload New Version', 'Remove Favorite', 'Copy', 'Information'];
export const favoritesCollaboratorToolbarMore = ['Upload New Version', 'Remove Favorite', 'Move', 'Copy', 'Delete', 'Manage Versions'];
export const collaboratorSharedToolbarPrimary = [
'Activate full-screen mode',
@@ -71,7 +73,18 @@ export const collaboratorDocToolbarMore = [
'Edit Aspects',
'Permissions'
];
export const collaboratorSharedWorkingCopyToolbarPrimary = ['Activate full-screen mode', 'View Details', 'More Actions'];
export const collaboratorLockedToolbarPrimary = ['Shared Link Settings', 'View', 'View Details', 'More Actions'];
export const collaboratorLockedOriginalSharedViewerToolbarPrimary = [
'Activate full-screen mode',
'Shared Link Settings',
'View Details',
'More Actions'
];
export const collaboratorLockedSharedViewerToolbarMore = ['Cancel Editing', 'Upload New Version', 'Remove Favorite', 'Copy'];
export const collaboratorLockCurrentUserToolbarMore = ['Cancel Editing', 'Upload New Version', 'Remove Favorite', 'Copy', 'Manage Versions'];
export const collaboratorLockWorkingCopyToolbarMore = ['Cancel Editing', 'Upload New Version', 'Favorite', 'Copy'];
export const lockedWorkingCopyToolbarMore = ['Cancel Editing', 'Upload New Version', 'Favorite', 'Move', 'Copy', 'Information', 'Permissions'];
export const collaboratorLockOtherUserToolbarMore = ['Cancel Editing', 'Remove Favorite', 'Move', 'Copy', 'Delete', 'Manage Versions', 'Permissions'];
export const collaboratorLockOtherUserSearchToolbarMore = ['Cancel Editing', 'Remove Favorite', 'Copy', 'Manage Versions', 'Permissions'];
@@ -79,8 +92,11 @@ export const collaboratorLockOtherUserSearchToolbarMore = ['Cancel Editing', 'Re
const consumerViewerSharedToolbarPrimary = ['Activate full-screen mode', 'Shared Link Settings', 'Download', 'Print', 'View Details', 'More Actions'];
const consumerViewerToolbarPrimary = ['Activate full-screen mode', 'Share', 'Download', 'Print', 'View Details', 'More Actions'];
const consumerViewerLockedToolbarPrimary = ['Activate full-screen mode', 'View Details', 'More Actions'];
const consumerViewerFavToolbarMore = ['Remove Favorite', 'Copy', 'Manage Versions'];
const consumerViewerToolbarMore = ['Favorite', 'Copy', 'Manage Versions'];
const consumerViewerLockedToolbarMore = ['Favorite', 'Copy'];
const consumerViewerLockedFavToolbarMore = ['Remove Favorite', 'Copy'];
// ---- FAVORITES workarounds ----
@@ -271,26 +287,29 @@ export const fileSharedFav = {
export const fileLocked = {
name: `file-${random}-locked.txt`,
workingCopyName: `file-${random}-locked (Working Copy).txt`,
description: 'file not shared, not fav, not office, locked',
contextMenu: consumerContextMenu,
toolbarPrimary: consumerToolbarPrimary,
toolbarMore: consumerToolbarMore,
viewerToolbarPrimary: consumerViewerToolbarPrimary,
viewerToolbarMore: consumerViewerToolbarMore,
viewerToolbarPrimary: consumerViewerLockedToolbarPrimary,
viewerToolbarMore: consumerViewerLockedToolbarMore,
searchToolbarPrimary: searchConsumerToolbarPrimary
};
export const fileFavLocked = {
name: `file-${random}-fav-locked.txt`,
workingCopyName: `file-${random}-fav-locked (Working Copy).txt`,
description: 'file not shared, fav, not office, locked',
contextMenu: consumerFavContextMenu,
toolbarPrimary: consumerToolbarPrimary,
toolbarMore: consumerFavToolbarMore,
viewerToolbarPrimary: consumerViewerToolbarPrimary,
viewerToolbarMore: consumerViewerFavToolbarMore,
viewerToolbarPrimary: consumerViewerLockedToolbarPrimary,
viewerToolbarMore: consumerViewerLockedFavToolbarMore,
workingCopyViewerToolbarMore: consumerViewerLockedToolbarMore,
favoritesToolbarMore: favoritesConsumerToolbarMore,
favoritesContextMenu: favoritesConsumerContextMenu,
@@ -300,13 +319,14 @@ export const fileFavLocked = {
export const fileSharedLocked = {
name: `file-${random}-shared-locked.txt`,
workingCopyName: `file-${random}-shared-locked (Working Copy).txt`,
description: 'file shared, not fav, not office, locked',
contextMenu: consumerSharedContextMenu,
toolbarPrimary: consumerSharedToolbarPrimary,
toolbarMore: consumerToolbarMore,
viewerToolbarPrimary: consumerViewerSharedToolbarPrimary,
viewerToolbarMore: consumerViewerToolbarMore,
viewerToolbarPrimary: consumerViewerLockedToolbarPrimary,
viewerToolbarMore: consumerViewerLockedToolbarMore,
sharedToolbarMore: sharedConsumerLockedToolbarMore,
sharedContextMenu: sharedConsumerLockedContextMenu,
@@ -316,13 +336,15 @@ export const fileSharedLocked = {
export const fileSharedFavLocked = {
name: `file-${random}-shared-fav-locked.txt`,
workingCopyName: `file-${random}-shared-fav-locked (Working Copy).txt`,
description: 'file shared, fav, not office, locked',
contextMenu: consumerSharedFavContextMenu,
toolbarPrimary: consumerSharedToolbarPrimary,
toolbarMore: consumerFavToolbarMore,
viewerToolbarPrimary: consumerViewerSharedToolbarPrimary,
viewerToolbarMore: consumerViewerFavToolbarMore,
viewerToolbarPrimary: consumerViewerLockedToolbarPrimary,
viewerToolbarMore: consumerViewerLockedFavToolbarMore,
workingCopyViewerToolbarMore: consumerViewerLockedToolbarMore,
favoritesToolbarMore: favoritesConsumerToolbarMore,
favoritesContextMenu: favoritesConsumerSharedContextMenu,
@@ -335,6 +357,7 @@ export const fileSharedFavLocked = {
export const fileGranularPermission = `file-${random}-granular.txt`;
export const fileLockedByUser = `file-${random}-my-locked.txt`;
export const fileLockedByUserWorkingCopyName = `file-${random}-my-locked (Working Copy).txt`;
// ---- non-versionable file (no cm:versionable aspect) ----
+165 -2
View File
@@ -25,7 +25,7 @@
import * as app from './app.rules';
import { createVersionRule, getFileExtension, isPreferencesApiAvailable, isNodeInfoAvailable, isBulkActionsAvailable } from './app.rules';
import { TestRuleContext } from './test-rule-context';
import { NodeEntry, RepositoryInfo, StatusInfo } from '@alfresco/js-api';
import { NodeEntry, RepositoryInfo, SharedLink, StatusInfo } from '@alfresco/js-api';
import { ProfileState, RuleContext } from '@alfresco/adf-extensions';
describe('app.evaluators', () => {
@@ -1114,7 +1114,9 @@ describe('app.evaluators', () => {
});
it('should return true when file is locked and user is the owner of the lock', () => {
context.selection.file = { entry: { properties: { 'cm:lockType': 'WRITE_LOCK', 'cm:lockOwner': { id: 'test1' } } } } as NodeEntry;
const file = { entry: { isFile: true, properties: { 'cm:lockType': 'WRITE_LOCK', 'cm:lockOwner': { id: 'test1' } } } } as NodeEntry;
context.selection.file = file;
context.selection.first = file;
context.profile.id = 'test1';
context.permissions = { check: () => false };
expect(app.canToggleFileLock(context)).toBeTrue();
@@ -1206,6 +1208,42 @@ describe('app.evaluators', () => {
});
});
describe('isLockedOrWorkingCopy', () => {
it('should return false when there is no entry', () => {
expect(app.isLockedOrWorkingCopy(context, { entry: null })).toBeFalse();
});
it('should return false for a folder (not a file and no nodeId)', () => {
expect(app.isLockedOrWorkingCopy(context, { entry: { isFolder: true, isFile: false } } as NodeEntry)).toBeFalse();
});
it('should return true for a locked file', () => {
expect(app.isLockedOrWorkingCopy(context, { entry: { isFile: true, isLocked: true, aspectNames: [] } } as NodeEntry)).toBeTrue();
});
it('should return true for a file with cm:checkedOut aspect', () => {
expect(
app.isLockedOrWorkingCopy(context, { entry: { isFile: true, isLocked: false, aspectNames: ['cm:checkedOut'] } } as NodeEntry)
).toBeTrue();
});
it('should return true for a file with cm:workingcopy aspect', () => {
expect(
app.isLockedOrWorkingCopy(context, { entry: { isFile: true, isLocked: false, aspectNames: ['cm:workingcopy'] } } as NodeEntry)
).toBeTrue();
});
it('should return true for a shared link (no isFile) with cm:checkedOut aspect - ensures lock badge shows on shared page', () => {
const sharedLinkEntry = { nodeId: 'node-1', isFile: undefined, isFolder: undefined, aspectNames: ['cm:checkedOut'] } as SharedLink;
expect(app.isLockedOrWorkingCopy(context, { entry: sharedLinkEntry } as NodeEntry)).toBeTrue();
});
it('should return false for a shared link (no isFile) without lock aspects', () => {
const sharedLinkEntry = { nodeId: 'node-1', isFile: undefined, isFolder: undefined, aspectNames: [] } as SharedLink;
expect(app.isLockedOrWorkingCopy(context, { entry: sharedLinkEntry } as NodeEntry)).toBeFalse();
});
});
describe('isCheckedOut', () => {
it('should return false when there is no selection', () => {
context.selection.isEmpty = true;
@@ -1225,6 +1263,131 @@ describe('app.evaluators', () => {
});
});
describe('isWorkingCopy', () => {
it('should return false when selection is empty', () => {
context.selection.isEmpty = true;
expect(app.isWorkingCopy(context)).toBeFalse();
});
it('should return false when node does not have cm:workingcopy aspect', () => {
context.selection.isEmpty = false;
context.selection.first = { entry: { aspectNames: ['cm:checkedOut'] } } as NodeEntry;
expect(app.isWorkingCopy(context)).toBeFalse();
});
it('should return true when node has cm:workingcopy aspect', () => {
context.selection.isEmpty = false;
context.selection.first = { entry: { aspectNames: ['cm:workingcopy'] } } as NodeEntry;
expect(app.isWorkingCopy(context)).toBeTrue();
});
});
describe('canCheckout', () => {
beforeEach(() => {
context.selection.isEmpty = false;
context.selection.file = { entry: { isFile: true, aspectNames: [], properties: {} } } as NodeEntry;
context.selection.first = context.selection.file;
context.selection.nodes = [context.selection.file] as NodeEntry[];
context.permissions = { check: () => true };
});
it('should return false when no file is selected', () => {
context.selection.file = null;
expect(app.canCheckout(context)).toBeFalse();
});
it('should return false when in trashcan', () => {
context.navigation = { url: '/trashcan' };
expect(app.canCheckout(context)).toBeFalse();
});
it('should return false when selected node is a link', () => {
context.selection.nodes = [{ entry: { nodeType: 'app:filelink' } }] as NodeEntry[];
expect(app.canCheckout(context)).toBeFalse();
});
it('should return false when user has no update permission', () => {
context.permissions = { check: () => false };
expect(app.canCheckout(context)).toBeFalse();
});
it('should return false when node is already checked out', () => {
context.selection.first = {
entry: { isFile: true, aspectNames: ['cm:checkedOut'], properties: { 'cm:lockType': 'READ_ONLY_LOCK' } }
} as NodeEntry;
context.selection.file = context.selection.first;
context.selection.nodes = [context.selection.first] as NodeEntry[];
expect(app.canCheckout(context)).toBeFalse();
});
it('should return false when node is a working copy', () => {
context.selection.first = { entry: { isFile: true, aspectNames: ['cm:workingcopy'], properties: {} } } as NodeEntry;
context.selection.file = context.selection.first;
context.selection.nodes = [context.selection.first] as NodeEntry[];
expect(app.canCheckout(context)).toBeFalse();
});
it('should return true for a plain unlocked file with update permission', () => {
expect(app.canCheckout(context)).toBeTrue();
});
});
describe('canCancelCheckout', () => {
beforeEach(() => {
context.selection.isEmpty = false;
context.selection.file = {
entry: { isFile: true, aspectNames: ['cm:checkedOut'], properties: { 'cm:lockType': 'READ_ONLY_LOCK', 'cm:lockOwner': { id: 'user1' } } }
} as NodeEntry;
context.selection.first = context.selection.file;
context.selection.nodes = [context.selection.file] as NodeEntry[];
context.profile = { id: 'user1' } as unknown as ProfileState;
context.permissions = { check: () => true };
});
it('should return false when no file is selected', () => {
context.selection.file = null;
expect(app.canCancelCheckout(context)).toBeFalse();
});
it('should return false when in trashcan', () => {
context.navigation = { url: '/trashcan' };
expect(app.canCancelCheckout(context)).toBeFalse();
});
it('should return false when selected node is a link', () => {
context.selection.nodes = [{ entry: { nodeType: 'app:filelink' } }] as NodeEntry[];
expect(app.canCancelCheckout(context)).toBeFalse();
});
it('should return false when node is not checked out and not a working copy', () => {
context.selection.first = { entry: { isFile: true, aspectNames: [], properties: {} } } as NodeEntry;
context.selection.file = context.selection.first;
expect(app.canCancelCheckout(context)).toBeFalse();
});
it('should return true when node is checked-out original and user has delete permission', () => {
expect(app.canCancelCheckout(context)).toBeTrue();
});
it('should return true when node is a working copy and user has delete permission', () => {
context.selection.first = { entry: { isFile: true, aspectNames: ['cm:workingcopy'], properties: {} } } as NodeEntry;
context.selection.file = context.selection.first;
context.selection.nodes = [context.selection.first] as NodeEntry[];
expect(app.canCancelCheckout(context)).toBeTrue();
});
it('should return true when user is the lock owner even without delete permission', () => {
context.permissions = { check: () => false };
expect(app.canCancelCheckout(context)).toBeTrue();
});
it('should return false when user is not the lock owner and has no delete permission', () => {
context.profile = { id: 'other-user' } as ProfileState;
context.permissions = { check: () => false };
expect(app.canCancelCheckout(context)).toBeFalse();
});
});
describe('isNodeLink', () => {
it('should return false when selection is empty', () => {
context.selection.isEmpty = true;
+109 -12
View File
@@ -24,6 +24,7 @@
import { AppConfigService } from '@alfresco/adf-core';
import { RuleContext } from '@alfresco/adf-extensions';
import { NodeEntry, SharedLink } from '@alfresco/js-api';
import * as navigation from './navigation.rules';
import * as repository from './repository.rules';
import { isAdmin } from './user.rules';
@@ -121,9 +122,14 @@ export function canRemoveFavorite(context: RuleContext): boolean {
* JSON ref: `app.selection.file.canShare`
*/
export const canShareFile = (context: RuleContext): boolean =>
[context.selection.file, !navigation.isTrashcan(context), repository.hasQuickShareEnabled(context), !isShared(context), !isNodeLink(context)].every(
Boolean
);
[
context.selection.file,
!navigation.isTrashcan(context),
repository.hasQuickShareEnabled(context),
!isShared(context),
!isNodeLink(context),
!isLockedOrWorkingCopy(context)
].every(Boolean);
/**
* Checks if user can perform "Join" or "Cancel Join Request" on a library.
@@ -210,7 +216,7 @@ export function canCreateFolder(context: AcaRuleContext): boolean {
* JSON ref: `app.selection.canDownload`
*/
export function canDownloadSelection(context: RuleContext): boolean {
if (isNodeLink(context)) {
if (context.selection.nodes.some((node) => isLockedOrWorkingCopy(context, node)) || isNodeLink(context)) {
return false;
}
return context.selection.nodes.every((node: any) => node.entry && (node.entry.isFile || node.entry.isFolder || !!node.entry.nodeId));
@@ -320,14 +326,51 @@ export const isWriteLocked = (context: RuleContext): boolean =>
);
/**
* Checks if the selected file has **write** or **read-only** locks specified,
* and that current user is the owner of the lock.
* Checks if a node is locked or a working copy. Accepts an optional node argument
* so it can be evaluated per-row (e.g. for badges), falling back to context.selection.first.
* JSON ref: `app.selection.isLockedOrWorkingCopy`
*
* Covers:
* - `entry.isLocked` — any server-reported lock
* - `cm:lockType` property — present when locked via the Lock action
* - `cm:workingcopy` aspect — the working copy created on checkout
* - `cm:checkedOut` aspect — the original file while its working copy exists
*
* @param context Rule execution context
* @param node Optional node to evaluate; defaults to context.selection.first
*/
export function isLockedOrWorkingCopy(context: RuleContext, node?: NodeEntry): boolean {
const entry = (node ?? context?.selection?.first)?.entry;
if (!entry) {
return false;
}
if (!entry.isFile && !(entry as SharedLink).nodeId) {
return false;
}
return (
entry.isLocked === true ||
!!entry.properties?.['cm:lockType'] ||
(entry.aspectNames ?? []).includes('cm:workingcopy') ||
(entry.aspectNames ?? []).includes('cm:checkedOut')
);
}
/**
* Checks if the current user owns the lock on the selected file.
* Handles both regular write/read-only locks (`cm:lockOwner`) and
* working copies (`cm:workingCopyOwner`), which have no `cm:lockType` themselves.
* JSON ref: `app.selection.file.isLockOwner`
*/
export const isUserWriteLockOwner = (context: RuleContext): boolean =>
isWriteLocked(context) &&
context.selection.file?.entry.properties['cm:lockOwner'] &&
context.selection.file?.entry.properties['cm:lockOwner'].id === context.profile.id;
export const isUserWriteLockOwner = (context: RuleContext): boolean => {
const entry = context.selection.file?.entry;
if (!entry) {
return false;
}
if (entry.aspectNames?.includes('cm:workingcopy')) {
return entry.properties?.['cm:workingCopyOwner']?.id === context.profile.id;
}
return isWriteLocked(context) && !!entry.properties?.['cm:lockOwner'] && entry.properties['cm:lockOwner'].id === context.profile.id;
};
/**
* Checks if user can lock selected file.
@@ -371,6 +414,9 @@ export function canUploadVersion(context: RuleContext): boolean {
* @param context Rule execution context
*/
export const canPrintFile = (context: RuleContext): boolean => {
if (isLockedOrWorkingCopy(context)) {
return false;
}
const nodeEntry = context.selection.file.entry;
if (!nodeEntry?.content?.mimeType) {
return false;
@@ -395,6 +441,7 @@ export const canToggleSharedLink = (context: RuleContext): boolean => [canShareF
*/
export const canEditAspects = (context: RuleContext): boolean =>
[
!isWorkingCopy(context),
!isMultiselection(context),
canUpdateSelectedNode(context),
!isWriteLocked(context),
@@ -402,8 +449,7 @@ export const canEditAspects = (context: RuleContext): boolean =>
repository.isMajorVersionAvailable(context, '7')
].every(Boolean);
export const canToggleFileLock = (context: RuleContext): boolean =>
!isNodeLink(context) && [canLockFile(context) || canUnlockFile(context)].some(Boolean);
export const canToggleFileLock = (context: RuleContext): boolean => canCheckout(context) || canCancelCheckout(context);
/**
* @deprecated Uses workarounds for for recent files and search api issues.
@@ -451,6 +497,10 @@ export function canOpenWithOffice(context: AcaRuleContext): boolean {
return false;
}
if (isWorkingCopy(context)) {
return false;
}
if (context.navigation?.url?.startsWith('/trashcan')) {
return false;
}
@@ -600,6 +650,53 @@ export const isCheckedOut = (context: RuleContext): boolean => {
return false;
};
/**
* Checks if the selected node is a working copy (has cm:workingcopy aspect).
* JSON ref: `app.selection.isWorkingCopy`
*
* @param context Rule execution context
*/
export const isWorkingCopy = (context: RuleContext): boolean => {
if (!context.selection?.isEmpty) {
return (context.selection.first?.entry?.aspectNames ?? []).includes('cm:workingcopy');
}
return false;
};
/**
* Checks if the selected file node can be checked out.
* Returns true for cm:content (or subtype) file nodes that are not already
* checked out, not locked, not a working copy, and where the user has update permission.
* Blocks folders, node links, trashcan items, and special system nodes (no update permission).
* JSON ref: `app.selection.canCheckout`
*
* @param context Rule execution context
*/
export const canCheckout = (context: RuleContext): boolean =>
hasFileSelected(context) &&
!navigation.isTrashcan(context) &&
!isNodeLink(context) &&
canUpdateSelectedNode(context) &&
!isLockedOrWorkingCopy(context);
/**
* Checks if checkout can be cancelled for the selected node.
* Returns true when a checked-out original or working copy is selected
* and the user is the lock owner or has delete permission.
* JSON ref: `app.selection.canCancelCheckout`
*
* @param context Rule execution context
*/
export const canCancelCheckout = (context: RuleContext): boolean => {
return (
hasFileSelected(context) &&
!navigation.isTrashcan(context) &&
!isNodeLink(context) &&
isLockedOrWorkingCopy(context) &&
(context.permissions.check(context.selection.file?.entry, ['delete']) || isUserWriteLockOwner(context))
);
};
/**
* Checks if any of the selected nodes is a link node (app:filelink or app:folderlink).
* JSON ref: `app.selection.isNodeLink`
@@ -40,7 +40,7 @@ import {
ViewNodeExtras
} from '@alfresco/aca-shared/store';
import { AppExtensionService } from '../../services/app.extension.service';
import { isLibrary, isLocked } from '../../utils/node.utils';
import { isLibrary } from '../../utils/node.utils';
import { AutoDownloadService } from '../../services/auto-download.service';
import { BreakpointObserver, Breakpoints } from '@angular/cdk/layout';
import { Router } from '@angular/router';
@@ -177,15 +177,9 @@ export abstract class PageComponent implements OnInit, OnDestroy, OnChanges {
}
imageResolver(row: ShareDataRow): string | null {
if (row) {
if (isLocked(row.node)) {
return 'material-icons://lock';
}
if (isLibrary(row.node)) {
if (row && isLibrary(row.node)) {
return 'material-icons://library_books';
}
}
return null;
}
@@ -266,7 +266,7 @@ describe('Info Drawer state', () => {
expect(component.imageResolver(null)).toBe(null);
});
it('should resolve custom image for locked node', () => {
it('should not resolve custom image for locked node', () => {
const row: any = {
node: {
entry: {
@@ -275,7 +275,7 @@ describe('Info Drawer state', () => {
}
};
expect(component.imageResolver(row)).toBe('material-icons://lock');
expect(component.imageResolver(row)).toBe(null);
});
it('should resolve custom image for a library', () => {
@@ -23,20 +23,36 @@
*/
import { LockedByComponent } from './locked-by.component';
import { NodeEntry } from '@alfresco/js-api';
describe('LockedByComponent', () => {
it('should evaluate label text', () => {
it('should show lock owner for a locked file', () => {
const component = new LockedByComponent();
component.node = {
entry: {
aspectNames: [],
properties: {
'cm:lockOwner': {
displayName: 'owner-name'
'cm:lockOwner': { displayName: 'lock-owner' }
}
}
} as any
};
} as NodeEntry;
component.ngOnInit();
expect(component.text).toBe('owner-name');
expect(component.workingCopy).toBeFalse();
expect(component.text).toBe('lock-owner');
});
it('should show working copy owner for a working copy', () => {
const component = new LockedByComponent();
component.node = {
entry: {
aspectNames: ['cm:workingcopy'],
properties: {
'cm:workingCopyOwner': { displayName: 'wc-owner' }
}
}
} as NodeEntry;
component.ngOnInit();
expect(component.workingCopy).toBeTrue();
expect(component.text).toBe('wc-owner');
});
});
@@ -26,13 +26,14 @@ import { ChangeDetectionStrategy, Component, Input, OnInit, ViewEncapsulation }
import { NodeEntry } from '@alfresco/js-api';
import { TranslatePipe } from '@ngx-translate/core';
import { MatIconModule } from '@angular/material/icon';
import { isWorkingCopy } from '../../utils/node.utils';
@Component({
imports: [TranslatePipe, MatIconModule],
selector: 'aca-locked-by',
template: `
<mat-icon class="aca-locked-by--icon">lock</mat-icon>
<span class="aca-locked-by--label">{{ 'APP.LOCKED_BY' | translate }}</span>
<span class="aca-locked-by--label">{{ (workingCopy ? 'CHECKOUT.CHECKED_OUT_BY' : 'APP.LOCKED_BY') | translate }}</span>
<span class="aca-locked-by--name">{{ text }}</span>
`,
styleUrls: ['./locked-by.component.scss'],
@@ -46,9 +47,13 @@ export class LockedByComponent implements OnInit {
@Input()
node: NodeEntry;
public text: string;
workingCopy = false;
text: string;
ngOnInit(): void {
this.text = this.node?.entry?.properties?.['cm:lockOwner']?.displayName;
this.workingCopy = isWorkingCopy(this.node);
this.text = this.workingCopy
? this.node?.entry?.properties?.['cm:workingCopyOwner']?.displayName
: this.node?.entry?.properties?.['cm:lockOwner']?.displayName;
}
}
@@ -22,7 +22,7 @@
* from Hyland Software. If not, see <http://www.gnu.org/licenses/>.
*/
import { Node } from '@alfresco/js-api';
import { Node, NodeEntry } from '@alfresco/js-api';
export function isLocked(node: { entry: Node }): boolean {
if (node?.entry) {
@@ -34,6 +34,16 @@ export function isLocked(node: { entry: Node }): boolean {
}
}
export function isWorkingCopy(nodeEntry: NodeEntry): boolean {
if (nodeEntry?.entry) {
const { entry } = nodeEntry;
return entry.aspectNames?.includes('cm:workingcopy') ?? false;
} else {
return false;
}
}
export function isLibrary(node: { entry: Node | any }): boolean {
if (node?.entry) {
const { entry } = node;
@@ -22,7 +22,8 @@
* from Hyland Software. If not, see <http://www.gnu.org/licenses/>.
*/
import { isLibrary, isLocked } from './node.utils';
import { isLibrary, isLocked, isWorkingCopy } from './node.utils';
import { NodeEntry } from '@alfresco/js-api';
describe('NodeUtils', () => {
describe('isLocked', () => {
@@ -81,6 +82,53 @@ describe('NodeUtils', () => {
});
});
describe('isWorkingCopy', () => {
it('should return [false] if entry is not defined', () => {
expect(isWorkingCopy(null)).toBeFalse();
expect(isWorkingCopy({ entry: null })).toBeFalse();
});
it('should return [true] when cm:workingcopy aspect is present', () => {
expect(
isWorkingCopy({
entry: {
aspectNames: ['cm:workingcopy', 'cm:titled']
}
} as NodeEntry)
).toBeTrue();
});
it('should return [false] when cm:workingcopy aspect is absent', () => {
expect(
isWorkingCopy({
entry: {
aspectNames: ['cm:titled']
}
} as NodeEntry)
).toBeFalse();
});
it('should return [false] when aspectNames is empty', () => {
expect(
isWorkingCopy({
entry: {
aspectNames: []
}
} as NodeEntry)
).toBeFalse();
});
it('should return [false] when aspectNames is undefined', () => {
expect(
isWorkingCopy({
entry: {
aspectNames: undefined
}
} as NodeEntry)
).toBeFalse();
});
});
describe('isLibrary', () => {
it('should return [false] if entry is not defined', () => {
expect(isLibrary(null)).toBeFalse();
@@ -47,6 +47,8 @@ export enum NodeActionTypes {
ManageVersions = 'MANAGE_VERSIONS',
EditOffline = 'EDIT_OFFLINE',
UnlockForWriting = 'UNLOCK_WRITE_LOCK',
CheckoutNode = 'CHECKOUT_NODE',
CancelCheckoutNode = 'CANCEL_CHECKOUT_NODE',
AddFavorite = 'ADD_FAVORITE',
RemoveFavorite = 'REMOVE_FAVORITE',
ChangeAspects = 'ASPECT_LIST',
@@ -198,6 +200,18 @@ export class EditOfflineAction implements Action {
constructor(public payload: NodeEntry) {}
}
export class CheckoutNodeAction implements Action {
readonly type = NodeActionTypes.CheckoutNode;
constructor(public payload: NodeEntry) {}
}
export class CancelCheckoutNodeAction implements Action {
readonly type = NodeActionTypes.CancelCheckoutNode;
constructor(public payload: NodeEntry) {}
}
export class UnlockWriteAction implements Action {
readonly type = NodeActionTypes.UnlockForWriting;