Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions src/app/datasets/batch-view/batch-view.component.html
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,17 @@
<mat-icon> remove_circle_outline </mat-icon>
Empty Selection
</button>
<button
*ngIf="!editingPublishedDataDoi"
mat-button
id="exportCsvButton"
(click)="onExportCsv()"
class="button"
color="primary"
>
<mat-icon> download </mat-icon>
Export CSV
</button>
<button
*ngIf="!editingPublishedDataDoi"
mat-button
Expand Down
189 changes: 186 additions & 3 deletions src/app/datasets/batch-view/batch-view.component.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,28 +22,112 @@ import { MockStore, provideMockStore } from "@ngrx/store/testing";
import { DatasetState } from "state-management/state/datasets.store";
import { selectDatasetsInBatch } from "state-management/selectors/datasets.selectors";
import { removeFromBatchAction } from "state-management/actions/datasets.actions";
import { fetchInstrumentsAction } from "state-management/actions/instruments.actions";
import { MatFormFieldModule } from "@angular/material/form-field";
import { MatChipsModule } from "@angular/material/chips";
import { MatInputModule } from "@angular/material/input";
import { AppConfigService } from "app-config.service";
import { DatasetsService } from "@scicatproject/scicat-sdk-ts-angular";
import { selectColumnsWithHasFetchedSettings } from "state-management/selectors/user.selectors";
import { DatasetsListService } from "shared/services/datasets-list.service";
import { TableService } from "shared/modules/dynamic-material-table/table/dynamic-mat-table.service";
import { TableField } from "shared/modules/dynamic-material-table/models/table-field.model";
import { TableColumn } from "state-management/models";
import { TranslateService } from "@ngx-translate/core";

describe("BatchViewComponent", () => {
let component: BatchViewComponent;
let fixture: ComponentFixture<BatchViewComponent>;

let dispatchSpy;
let store: MockStore<DatasetState>;
let tableService: jasmine.SpyObj<TableService>;
let datasetsListService: jasmine.SpyObj<DatasetsListService>;
let translateService: jasmine.SpyObj<TranslateService>;

const configuredColumns: TableColumn[] = [
{ name: "select", order: 0, type: "standard", enabled: true },
{ name: "pid", order: 1, type: "standard", enabled: true, header: "PID" },
{
name: "datasetName",
order: 2,
type: "standard",
enabled: true,
header: "Dataset name",
},
{
name: "sourceFolder",
order: 3,
type: "standard",
enabled: false,
header: "Source Folder",
},
];

const convertedColumns: TableField<any>[] = [
{
name: "pid",
header: "PID",
display: "visible",
toExport: (row) => row.pid,
},
{
name: "datasetName",
header: "Dataset name",
display: "visible",
toExport: (row) => row.datasetName,
},
{
name: "sourceFolder",
header: "Source Folder",
display: "hidden",
toExport: (row) => row.sourceFolder,
},
];

const router = {
navigate: jasmine.createSpy("navigate"),
};

const getConfig = () => ({
archiveWorkflowEnabled: true,
shareEnabled: false,
defaultDatasetsListSettings: {
columns: configuredColumns,
},
labelsLocalization: {
dataset: {
pid: "PID",
datasetName: "Dataset Name",
creationTime: "Creation Time",
},
},
});

beforeEach(waitForAsync(() => {
tableService = jasmine.createSpyObj<TableService>("TableService", [
"exportToCsv",
]);
translateService = jasmine.createSpyObj<TranslateService>(
"TranslateService",
["instant"],
);
translateService.instant.and.callFake((key: string) => {
const translations = {
"dataset.PID": "PID",
"dataset.creationTime": "Creation Time",
};

return translations[key] || key;
});
datasetsListService = jasmine.createSpyObj<DatasetsListService>(
"DatasetsListService",
["convertSavedDatasetColumns"],
);
datasetsListService.convertSavedDatasetColumns.and.returnValue(
convertedColumns,
);

TestBed.configureTestingModule({
schemas: [NO_ERRORS_SCHEMA],
declarations: [BatchViewComponent],
Expand All @@ -59,7 +143,16 @@ describe("BatchViewComponent", () => {
],
providers: [
provideMockStore({
selectors: [{ selector: selectDatasetsInBatch, value: [] }],
selectors: [
{ selector: selectDatasetsInBatch, value: [dataset] },
{
selector: selectColumnsWithHasFetchedSettings,
value: {
columns: configuredColumns,
hasFetchedSettings: true,
},
},
],
}),
],
});
Expand All @@ -72,6 +165,9 @@ describe("BatchViewComponent", () => {
{ provide: DatasetsService, useClass: MockDatasetApi },
{ provide: AppConfigService, useValue: { getConfig } },
{ provide: ActivatedRoute, useClass: MockActivatedRoute },
{ provide: TableService, useValue: tableService },
{ provide: DatasetsListService, useValue: datasetsListService },
{ provide: TranslateService, useValue: translateService },
],
},
});
Expand All @@ -81,6 +177,7 @@ describe("BatchViewComponent", () => {
}));

beforeEach(() => {
dispatchSpy = spyOn(store, "dispatch").and.callThrough();
fixture = TestBed.createComponent(BatchViewComponent);
component = fixture.componentInstance;
fixture.detectChanges();
Expand All @@ -90,9 +187,15 @@ describe("BatchViewComponent", () => {
expect(component).toBeTruthy();
});

it("should request instruments on init for export formatting", () => {
expect(dispatchSpy).toHaveBeenCalledWith(
fetchInstrumentsAction({ limit: 1000, skip: 0 }),
);
});

describe("#clearBatch()", () => {
it("should dispatch a clearBatchAction", () => {
dispatchSpy = spyOn(store, "dispatch");
dispatchSpy.calls.reset();

component["clearBatch"]();

Expand All @@ -106,7 +209,7 @@ describe("BatchViewComponent", () => {

describe("#onRemove()", () => {
it("should dispatch a removeFromBatchAction", () => {
dispatchSpy = spyOn(store, "dispatch");
dispatchSpy.calls.reset();
component.onRemove(dataset);

expect(dispatchSpy).toHaveBeenCalledOnceWith(
Expand All @@ -127,6 +230,86 @@ describe("BatchViewComponent", () => {
});
});

describe("#onExportCsv()", () => {
it("should export csv using visible saved dataset columns", () => {
component.onExportCsv();

expect(
datasetsListService.convertSavedDatasetColumns,
).toHaveBeenCalledWith(configuredColumns);
expect(tableService.exportToCsv).toHaveBeenCalled();

const [columns, rows, selection, filename] =
tableService.exportToCsv.calls.mostRecent().args;

expect(columns.map((column) => column.name)).toEqual([
"pid",
"datasetName",
]);
expect(columns.map((column) => column.header)).toEqual([
"PID",
"Dataset name",
]);
expect(rows).toEqual([dataset]);
expect(selection.selected).toEqual([]);
expect(filename).toMatch(
/^datasets-selection-\d{4}-\d{1,2}-\d{1,2}\.csv$/,
);
});

it("should fall back to default config columns when user settings are unavailable", () => {
store.overrideSelector(selectColumnsWithHasFetchedSettings, {
columns: [],
hasFetchedSettings: false,
});
store.refreshState();

component.onExportCsv();

expect(
datasetsListService.convertSavedDatasetColumns,
).toHaveBeenCalledWith(configuredColumns);
});

it("should export translated dataset table headers when a column has no explicit header", () => {
datasetsListService.convertSavedDatasetColumns.and.returnValue([
{
name: "creationTime",
display: "visible",
toExport: () => "2026-03-25 12:00",
},
]);

component.onExportCsv();

const [columns] = tableService.exportToCsv.calls.mostRecent().args;

expect(columns[0].header).toBe("Creation Time");
expect(translateService.instant).toHaveBeenCalledWith(
"dataset.creationTime",
);
});
});

describe("template", () => {
it("should render the export button when not editing a published dataset list", () => {
const button: HTMLButtonElement | null =
fixture.nativeElement.querySelector("#exportCsvButton");

expect(button).not.toBeNull();
expect(button?.textContent).toContain("Export CSV");
});

it("should hide the export button while editing a published dataset list", () => {
component.editingPublishedDataDoi = "10.1234/example";
fixture.detectChanges();

const button = fixture.nativeElement.querySelector("#exportCsvButton");

expect(button).toBeNull();
});
});

describe("#onShare()", () => {
xit("should ...", () => {});
});
Expand Down
69 changes: 68 additions & 1 deletion src/app/datasets/batch-view/batch-view.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import {
removeFromBatchAction,
storeBatchAction,
} from "state-management/actions/datasets.actions";
import { Message, MessageType } from "state-management/models";
import { Message, MessageType, TableColumn } from "state-management/models";
import { showMessageAction } from "state-management/actions/user.actions";
import { DialogComponent } from "shared/modules/dialog/dialog.component";

Expand All @@ -23,9 +23,16 @@ import { AppConfigService } from "app-config.service";
import {
selectIsAdmin,
selectProfile,
selectColumnsWithHasFetchedSettings,
} from "state-management/selectors/user.selectors";
import { OutputDatasetObsoleteDto } from "@scicatproject/scicat-sdk-ts-angular";
import { resyncPublishedDataAction } from "state-management/actions/published-data.actions";
import { TableService } from "shared/modules/dynamic-material-table/table/dynamic-mat-table.service";
import { TableField } from "shared/modules/dynamic-material-table/models/table-field.model";
import { DatasetsListService } from "shared/services/datasets-list.service";
import { fetchInstrumentsAction } from "state-management/actions/instruments.actions";
import { TranslateService } from "@ngx-translate/core";
import { translateComponentLabel } from "shared/pipes/component-translate.pipe";

@Component({
selector: "batch-view",
Expand Down Expand Up @@ -59,6 +66,9 @@ export class BatchViewComponent implements OnInit, OnDestroy {
private archivingSrv: ArchivingService,
private router: Router,
private route: ActivatedRoute,
private tableService: TableService,
private datasetsListService: DatasetsListService,
private translateService: TranslateService,
) {}

private clearBatch() {
Expand All @@ -69,6 +79,49 @@ export class BatchViewComponent implements OnInit, OnDestroy {
this.store.dispatch(storeBatchAction({ batch: datasetUpdatedBatch }));
}

private getConfiguredDatasetColumns(): TableColumn[] {
let configuredColumns: TableColumn[] = [];

this.store
.select(selectColumnsWithHasFetchedSettings)
.pipe(first())
.subscribe(({ columns, hasFetchedSettings }) => {
if (hasFetchedSettings && columns.length) {
configuredColumns = columns;
}
});

if (configuredColumns.length) {
return configuredColumns;
}

return this.appConfig.defaultDatasetsListSettings?.columns || [];
}

private getExportColumns(): TableField<OutputDatasetObsoleteDto>[] {
return this.datasetsListService
.convertSavedDatasetColumns(this.getConfiguredDatasetColumns())
.filter((column) => column.display !== "hidden")
.map((column) => ({
...column,
header: this.translateDatasetColumnHeader(column),
toExport:
column.toExport ||
((row: OutputDatasetObsoleteDto) =>
typeof row === "object" ? row[column.name] : ""),
}));
}

private translateDatasetColumnHeader(
column: TableField<OutputDatasetObsoleteDto>,
): string {
return translateComponentLabel(
this.translateService,
column.header || column.name,
"dataset",
);
}

onEmpty() {
const msg =
"Are you sure that you want to remove all datasets from the batch?";
Expand All @@ -85,6 +138,19 @@ export class BatchViewComponent implements OnInit, OnDestroy {
this.router.navigate(["datasets", "selection", "publish"]);
}

onExportCsv() {
const columns = this.getExportColumns();

this.tableService.exportToCsv(
columns,
this.datasetList,
{
selected: [],
} as any,
`datasets-selection-${TableService.getFormattedFileNamingDate()}.csv`,
);
}

onShareClick() {
this.router.navigate([], {
queryParams: { share: "true" },
Expand Down Expand Up @@ -277,6 +343,7 @@ export class BatchViewComponent implements OnInit, OnDestroy {
this.userProfile = userProfile;
})
.unsubscribe();
this.store.dispatch(fetchInstrumentsAction({ limit: 1000, skip: 0 }));
this.store.dispatch(prefillBatchAction());
this.subscriptions.push(
this.batch$.subscribe((result) => {
Expand Down
Loading
Loading