Skip to content

Commit

Permalink
feat(editor): new route to duplicate local record
Browse files Browse the repository at this point in the history
  • Loading branch information
LHBruneton-C2C committed Jul 12, 2024
1 parent cec60ff commit 88666cc
Show file tree
Hide file tree
Showing 7 changed files with 216 additions and 0 deletions.
6 changes: 6 additions & 0 deletions apps/metadata-editor/src/app/app.routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { SearchRecordsComponent } from './records/search-records/search-records-
import { MyOrgUsersComponent } from './my-org-users/my-org-users.component'
import { MyOrgRecordsComponent } from './records/my-org-records/my-org-records.component'
import { NewRecordResolver } from './new-record.resolver'
import { DuplicateRecordResolver } from './duplicate-record.resolver'

export const appRoutes: Route[] = [
{ path: '', redirectTo: 'catalog/search', pathMatch: 'prefix' },
Expand Down Expand Up @@ -101,6 +102,11 @@ export const appRoutes: Route[] = [
component: EditPageComponent,
resolve: { record: NewRecordResolver },
},
{
path: 'duplicate/:uuid',
component: EditPageComponent,
resolve: { record: DuplicateRecordResolver },
},
{
path: 'edit/:uuid',
component: EditPageComponent,
Expand Down
84 changes: 84 additions & 0 deletions apps/metadata-editor/src/app/duplicate-record.resolver.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
import { TestBed } from '@angular/core/testing'
import { DuplicateRecordResolver } from './duplicate-record.resolver'
import { HttpClientTestingModule } from '@angular/common/http/testing'
import { NotificationsService } from '@geonetwork-ui/feature/notifications'
import { of, throwError } from 'rxjs'
import { DATASET_RECORDS } from '@geonetwork-ui/common/fixtures'
import { ActivatedRouteSnapshot, convertToParamMap } from '@angular/router'
import { CatalogRecord } from '@geonetwork-ui/common/domain/model/record'
import { TranslateModule } from '@ngx-translate/core'
import { RecordsRepositoryInterface } from '@geonetwork-ui/common/domain/repository/records-repository.interface'

class NotificationsServiceMock {
showNotification = jest.fn()
}
class RecordsRepositoryMock {
openRecordForDuplication = jest.fn(() =>
of([DATASET_RECORDS[0], '<xml>blabla</xml>', false])
)
}

const activatedRoute = {
paramMap: convertToParamMap({ id: DATASET_RECORDS[0].uniqueIdentifier }),
} as ActivatedRouteSnapshot

describe('DuplicateRecordResolver', () => {
let resolver: DuplicateRecordResolver
let recordsRepository: RecordsRepositoryInterface
let notificationsService: NotificationsService
let resolvedData: [CatalogRecord, string, boolean]

beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule, TranslateModule.forRoot()],
providers: [
{ provide: NotificationsService, useClass: NotificationsServiceMock },
{
provide: RecordsRepositoryInterface,
useClass: RecordsRepositoryMock,
},
],
})
resolver = TestBed.inject(DuplicateRecordResolver)
recordsRepository = TestBed.inject(RecordsRepositoryInterface)
notificationsService = TestBed.inject(NotificationsService)
})

it('should be created', () => {
expect(resolver).toBeTruthy()
})

describe('load record success', () => {
beforeEach(() => {
resolvedData = undefined
resolver.resolve(activatedRoute).subscribe((r) => (resolvedData = r))
})
it('should load record by uuid', () => {
expect(resolvedData).toEqual([
DATASET_RECORDS[0],
'<xml>blabla</xml>',
false,
])
})
})

describe('load record failure', () => {
beforeEach(() => {
recordsRepository.openRecordForDuplication = () =>
throwError(() => new Error('oopsie'))
resolvedData = undefined
resolver.resolve(activatedRoute).subscribe((r) => (resolvedData = r))
})
it('should not emit anything', () => {
expect(resolvedData).toBeUndefined()
})
it('should show error notification', () => {
expect(notificationsService.showNotification).toHaveBeenCalledWith({
type: 'error',
title: 'editor.record.loadError.title',
text: 'editor.record.loadError.body oopsie',
closeMessage: 'editor.record.loadError.closeMessage',
})
})
})
})
42 changes: 42 additions & 0 deletions apps/metadata-editor/src/app/duplicate-record.resolver.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { Injectable } from '@angular/core'
import { ActivatedRouteSnapshot } from '@angular/router'
import { catchError, EMPTY, Observable } from 'rxjs'
import { CatalogRecord } from '@geonetwork-ui/common/domain/model/record'
import { NotificationsService } from '@geonetwork-ui/feature/notifications'
import { TranslateService } from '@ngx-translate/core'
import { RecordsRepositoryInterface } from '@geonetwork-ui/common/domain/repository/records-repository.interface'

@Injectable({
providedIn: 'root',
})
export class DuplicateRecordResolver {
constructor(
private recordsRepository: RecordsRepositoryInterface,
private notificationsService: NotificationsService,
private translateService: TranslateService
) {}

resolve(
route: ActivatedRouteSnapshot
): Observable<[CatalogRecord, string, boolean]> {
return this.recordsRepository
.openRecordForDuplication(route.paramMap.get('uuid'))
.pipe(
catchError((error) => {
this.notificationsService.showNotification({
type: 'error',
title: this.translateService.instant(
'editor.record.loadError.title'
),
text: `${this.translateService.instant(
'editor.record.loadError.body'
)} ${error.message}`,
closeMessage: this.translateService.instant(
'editor.record.loadError.closeMessage'
),
})
return EMPTY
})
)
}
}
1 change: 1 addition & 0 deletions libs/api/metadata-converter/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export * from './lib/base.converter'
export * from './lib/iso19139'
export * from './lib/iso19115-3'
export * from './lib/find-converter'
Expand Down
48 changes: 48 additions & 0 deletions libs/api/repository/src/lib/gn4/gn4-repository.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -323,6 +323,54 @@ describe('Gn4Repository', () => {
})
})
})
describe('openRecordForDuplication', () => {
let record: CatalogRecord
let recordSource: string
let savedOnce: boolean

const date = new Date('2024-07-11')
jest.useFakeTimers().setSystemTime(date)

beforeEach(async () => {
;(gn4RecordsApi.getRecordAs as jest.Mock).mockReturnValueOnce(
of(DATASET_RECORD_SIMPLE_AS_XML).pipe(map((xml) => ({ body: xml })))
)
;[record, recordSource, savedOnce] = await lastValueFrom(
repository.openRecordForDuplication('1234-5678')
)
})
it('calls the API to get the record as XML', () => {
expect(gn4RecordsApi.getRecordAs).toHaveBeenCalledWith(
'1234-5678',
undefined,
expect.anything(),
undefined,
undefined,
undefined,
expect.anything(),
expect.anything(),
undefined,
expect.anything()
)
})
it('parses the XML record into a native object, and updates the id and title', () => {
expect(record).toMatchObject({
uniqueIdentifier: `TEMP-ID-1720656000000`,
title:
'A very interesting dataset (un jeu de données très intéressant) (Copy)',
})
})
it('saves the duplicated record as draft', () => {
const hasDraft = repository.recordHasDraft(`TEMP-ID-1720656000000`)
expect(hasDraft).toBe(true)
})
it('tells the record it has not been saved yet', () => {
expect(savedOnce).toBe(false)
})
it('returns the record as serialized', () => {
expect(recordSource).toMatch(/<mdb:MD_Metadata/)
})
})
// note: we're using a simple record here otherwise there might be loss of information when converting
describe('saveRecord', () => {
let recordSource: string
Expand Down
23 changes: 23 additions & 0 deletions libs/api/repository/src/lib/gn4/gn4-repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import {
} from '@geonetwork-ui/common/domain/model/search'
import { catchError, map, tap } from 'rxjs/operators'
import {
BaseConverter,
findConverterForDocument,
Gn4Converter,
Gn4SearchResults,
Expand Down Expand Up @@ -230,6 +231,28 @@ export class Gn4Repository implements RecordsRepositoryInterface {
)
}

openRecordForDuplication(
uniqueIdentifier: string
): Observable<[CatalogRecord, string, false] | null> {
return this.loadRecordAsXml(uniqueIdentifier).pipe(
switchMap(async (xml) => {
const converter = findConverterForDocument(xml)
const record = await converter.readRecord(xml)
return [record, converter] as [CatalogRecord, BaseConverter<string>]
}),
switchMap(async ([record, converter]) => {
record.uniqueIdentifier = `TEMP-ID-${Date.now()}`
record.title = `${record.title} (Copy)`
const xml = await converter.writeRecord(record)
window.localStorage.setItem(
this.getLocalStorageKeyForRecord(record.uniqueIdentifier),
xml
)
return [record, xml, false] as [CatalogRecord, string, false]
})
)
}

private serializeRecordToXml(
record: CatalogRecord,
referenceRecordSource?: string
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,18 @@ export abstract class RecordsRepositoryInterface {
uniqueIdentifier: string
): Observable<[CatalogRecord, string, boolean] | null>

/**
* This emits once:
* - record object with a new unique identifier and suffixed title
* - serialized representation of the record as text
* - false, as the duplicated record is always a draft
* @param uniqueIdentifier
* @returns Observable<[CatalogRecord, string, false] | null>
*/
abstract openRecordForDuplication(
uniqueIdentifier: string
): Observable<[CatalogRecord, string, false] | null>

/**
* @param record
* @param referenceRecordSource
Expand Down

0 comments on commit 88666cc

Please sign in to comment.