diff --git a/README.md b/README.md index 00494b77..d59b0bb6 100644 --- a/README.md +++ b/README.md @@ -90,6 +90,9 @@ User Interface related Features: - [Model Localization](https://cap.cloud.sap/docs/guides/i18n) for [English](app/_i18n/i18n.properties) and [German](app/_i18n/i18n_de.properties) language for static texts - [Custom File Upload extension](app/admin/webapp/extension/Upload.js) which provides a button for uploading `CSV` files - A simple Swagger UI for the CatalogService API at +- UI5 [Tree Table](app/genres/webapp/manifest.json) with Value Help for [GenreHierarchy](app/admin/fiori-service.cds) +- [Custom event handlers](https://cap.cloud.sap/docs/java/provisioning-api) for Tree Table such as the [Custom business logic for GenreHierarchy](srv/src/main/java/my/bookshop/handlers/HierarchyHandler.java). + Please note, that Tree Tables must be used with HANA. Custom event handler in this case provides a limited support ment for local testing. CDS Maven Plugin Features: @@ -138,6 +141,14 @@ are defined for local development: - User: `user`, password: `user` to browse books - User: `admin`, password: `admin` to manage books and orders +### Testing in hybrid mode + +You can test the `GenreHierarchyTest` on H2 using the profile `default` as well as on HANA using the profile `hybrid` + +``` +cds bind --exec -- mvn clean install -Dspring.profiles.active=hybrid +``` + ## Using VS Code VS Code supports the project out-of-the-box, when using the [Extension Pack for Java](https://marketplace.visualstudio.com/items?itemName=vscjava.vscode-java-pack). diff --git a/app/admin/fiori-service.cds b/app/admin/fiori-service.cds index cec4f215..bee1aa19 100644 --- a/app/admin/fiori-service.cds +++ b/app/admin/fiori-service.cds @@ -59,6 +59,44 @@ annotate AdminService.Books with @(UI : { ]} }); +// Add Value Help for Tree Table +annotate AdminService.Books with { + genre @(Common: { + Label : 'Genre', + ValueList: { + CollectionPath : 'GenreHierarchy', + Parameters : [ + { + $Type : 'Common.ValueListParameterDisplayOnly', + ValueListProperty: 'name', + }, + { + $Type : 'Common.ValueListParameterInOut', + LocalDataProperty: genre_ID, + ValueListProperty: 'ID', + } + ], + PresentationVariantQualifier: 'VH', + } + }); +} + +// Hide ID because of the ValueHelp +annotate AdminService.GenreHierarchy with { + ID @UI.Hidden; +}; + +annotate AdminService.GenreHierarchy with @UI: { + PresentationVariant #VH: { + $Type : 'UI.PresentationVariantType', + Visualizations : ['@UI.LineItem'], + RecursiveHierarchyQualifier: 'GenreHierarchy' + }, + LineItem : [{ + $Type: 'UI.DataField', + Value: name, + }] +}; //////////////////////////////////////////////////////////// // diff --git a/app/appconfig/fioriSandboxConfig.json b/app/appconfig/fioriSandboxConfig.json index 1dc45ef8..48b2ef6a 100644 --- a/app/appconfig/fioriSandboxConfig.json +++ b/app/appconfig/fioriSandboxConfig.json @@ -20,6 +20,14 @@ "title": "Browse Books", "description": "Find your favorite book" } + }, { + "id": "browse-genres", + "tileType": "sap.ushell.ui.tile.StaticTile", + "properties": { + "targetURL": "#Genres-display", + "title": "Browse Genres", + "description": "Find your favorite genre" + } } ] }, @@ -112,6 +120,19 @@ "url": "/browse/webapp" } }, + "browse-genres": { + "semanticObject": "Genres", + "action": "display", + "signature": { + "parameters": {}, + "additionalParameters": "allowed" + }, + "resolutionResult": { + "applicationType": "SAPUI5", + "additionalInformation": "SAPUI5.Component=genres", + "url": "/genres/webapp" + } + }, "manage-books": { "semanticObject": "Books", "action": "manage", diff --git a/app/common.cds b/app/common.cds index a8607057..ba638052 100644 --- a/app/common.cds +++ b/app/common.cds @@ -177,10 +177,8 @@ annotate my.Genres with UI : { SelectionFields : [name], LineItem : [ - {Value : name}, - { - Value : parent.name, - Label : 'Main Genre' + {Value : name, + Label : '{i18n>Name}', }, ], } @@ -199,12 +197,7 @@ annotate my.Genres with TypeNamePlural : '{i18n>Genres}', Title : {Value : name}, Description : {Value : ID} - }, - Facets : [{ - $Type : 'UI.ReferenceFacet', - Label : '{i18n>SubGenres}', - Target : 'children/@UI.LineItem' - }, ], + } }); diff --git a/app/genres/fiori-service.cds b/app/genres/fiori-service.cds new file mode 100644 index 00000000..fd4a556a --- /dev/null +++ b/app/genres/fiori-service.cds @@ -0,0 +1,23 @@ +/* + UI annotations for the Browse GenreHierarchy App +*/ + +using AdminService from '../../srv/admin-service'; + + +annotate AdminService.GenreHierarchy with @Aggregation.RecursiveHierarchy#GenreHierarchy: { + $Type: 'Aggregation.RecursiveHierarchyType', + NodeProperty: ID, // identifies a node + ParentNavigationProperty: parent // navigates to a node's parent + }; + + annotate AdminService.GenreHierarchy with @Hierarchy.RecursiveHierarchy#GenreHierarchy: { + $Type: 'Hierarchy.RecursiveHierarchyType', + // ExternalKey : null, + LimitedDescendantCount: LimitedDescendantCount, + DistanceFromRoot: DistanceFromRoot, + DrillState: DrillState, + Matched: Matched, + MatchedDescendantCount: MatchedDescendantCount, + LimitedRank: LimitedRank +}; diff --git a/app/genres/package.json b/app/genres/package.json new file mode 100644 index 00000000..9b81674d --- /dev/null +++ b/app/genres/package.json @@ -0,0 +1,12 @@ +{ + "name": "genres", + "version": "1.0.0", + "description": "", + "main": "index.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "keywords": [], + "author": "", + "license": "ISC" +} diff --git a/app/genres/webapp/Component.js b/app/genres/webapp/Component.js new file mode 100644 index 00000000..6b352417 --- /dev/null +++ b/app/genres/webapp/Component.js @@ -0,0 +1,3 @@ +sap.ui.define(["sap/fe/core/AppComponent"], ac => ac.extend("genres.Component", { + metadata:{ manifest:'json' } +})) diff --git a/app/genres/webapp/i18n/i18n.properties b/app/genres/webapp/i18n/i18n.properties new file mode 100644 index 00000000..d2792ee9 --- /dev/null +++ b/app/genres/webapp/i18n/i18n.properties @@ -0,0 +1,2 @@ +appTitle=Browse Genres +appDescription=Genres as Tree View diff --git a/app/genres/webapp/i18n/i18n_de.properties b/app/genres/webapp/i18n/i18n_de.properties new file mode 100644 index 00000000..e8714e92 --- /dev/null +++ b/app/genres/webapp/i18n/i18n_de.properties @@ -0,0 +1,2 @@ +appTitle=Zeige Genres +appDescription=Genres als Baumansicht diff --git a/app/genres/webapp/index.html b/app/genres/webapp/index.html new file mode 100644 index 00000000..d2192773 --- /dev/null +++ b/app/genres/webapp/index.html @@ -0,0 +1,35 @@ + + + + + + + Browse Genres + + + + +
+ + diff --git a/app/genres/webapp/manifest.json b/app/genres/webapp/manifest.json new file mode 100644 index 00000000..ab4a7d46 --- /dev/null +++ b/app/genres/webapp/manifest.json @@ -0,0 +1,129 @@ +{ + "_version": "1.8.0", + "sap.app": { + "id": "genres", + "type": "application", + "title": "{{appTitle}}", + "description": "{{appDescription}}", + "applicationVersion": { + "version": "1.0.0" + }, + "dataSources": { + "AdminService": { + "uri": "/api/admin/", + "type": "OData", + "settings": { + "odataVersion": "4.0" + } + } + }, + "-sourceTemplate": { + "id": "ui5template.basicSAPUI5ApplicationProject", + "-id": "ui5template.smartTemplate", + "-version": "1.40.12" + }, + "crossNavigation": { + "inbounds": { + "Genres-show": { + "signature": { + "parameters": {}, + "additionalParameters": "allowed" + }, + "semanticObject": "GenreHierarchy", + "action": "show" + } + } + } + }, + "sap.ui5": { + "dependencies": { + "minUI5Version": "1.122.0", + "libs": { + "sap.fe.templates": {} + } + }, + "models": { + "i18n": { + "type": "sap.ui.model.resource.ResourceModel", + "uri": "i18n/i18n.properties" + }, + "": { + "dataSource": "AdminService", + "settings": { + "synchronizationMode": "None", + "operationMode": "Server", + "autoExpandSelect" : true, + "earlyRequests": true, + "groupProperties": { + "default": { + "submit": "Auto" + } + } + } + } + }, + "routing": { + "routes": [ + { + "pattern": ":?query:", + "name": "GenreHierarchyList", + "target": "GenreHierarchyList" + }, + { + "pattern": "GenreHierarchy({key}):?query:", + "name": "GenreHierarchyDetails", + "target": "GenreHierarchyDetails" + } + ], + "targets": { + "GenreHierarchyList": { + "type": "Component", + "id": "GenreHierarchyList", + "name": "sap.fe.templates.ListReport", + "options": { + "settings" : { + "entitySet" : "GenreHierarchy", + "navigation" : { + "GenreHierarchy" : { + "detail" : { + "route" : "GenreHierarchyDetails" + } + } + }, + "controlConfiguration": { + "@com.sap.vocabularies.UI.v1.LineItem": { + "tableSettings": { + "hierarchyQualifier": "GenreHierarchy", + "type": "TreeTable" + } + } + } + } + } + }, + "GenreHierarchyDetails": { + "type": "Component", + "id": "GenreHierarchyDetails", + "name": "sap.fe.templates.ObjectPage", + "options": { + "settings" : { + "entitySet": "GenreHierarchy" + } + } + } + } + }, + "contentDensities": { + "compact": true, + "cozy": true + } + }, + "sap.ui": { + "technology": "UI5", + "fullWidth": false + }, + "sap.fiori": { + "registrationIds": [], + "archeType": "transactional" + } +} diff --git a/app/index.cds b/app/index.cds index dcbf40e5..0c07c888 100644 --- a/app/index.cds +++ b/app/index.cds @@ -8,4 +8,5 @@ using from './orders/fiori-service'; using from './reviews/fiori-service'; using from './notes/fiori-service'; using from './addresses/fiori-service'; +using from './genres/fiori-service'; using from './common'; diff --git a/app/xs-app.json b/app/xs-app.json index f6adf5a4..4facc67d 100644 --- a/app/xs-app.json +++ b/app/xs-app.json @@ -2,77 +2,82 @@ "welcomeFile": "/app/fiori.html", "authenticationMethod": "route", "routes": [ - { - "source": "^/app/(.*)$", - "cacheControl": "no-cache, no-store, must-revalidate", - "target": "$1", - "localDir": "./", - "authenticationType": "xsuaa" - }, - { - "source": "^/appconfig/(.*)$", - "localDir": "./", - "authenticationType": "xsuaa" - }, - { - "source": "^/browse/webapp/(.*)$", - "localDir": "./", - "authenticationType": "xsuaa" - }, - { - "source": "^/admin/webapp/(.*)$", - "localDir": "./", - "authenticationType": "xsuaa" - }, - { - "source": "^/orders/webapp/(.*)$", - "localDir": "./", - "authenticationType": "xsuaa" - }, - { - "source": "^/reviews/webapp/(.*)$", - "localDir": "./", - "authenticationType": "xsuaa" - }, - { - "source": "^/notes/webapp/(.*)$", - "localDir": "./", - "authenticationType": "xsuaa" - }, - { - "source": "^/addresses/webapp/(.*)$", - "localDir": "./", - "authenticationType": "xsuaa" - }, - { - "source": "^/vue/(.*)$", - "localDir": "./", - "authenticationType": "xsuaa" - }, - { - "source": "^/api/admin/(.*)", - "authenticationType": "xsuaa", - "destination": "backend" - }, - { - "source": "^/api/browse/(.*)", - "authenticationType": "xsuaa", - "destination": "backend" - }, - { - "source": "^/api/review/(.*)", - "authenticationType": "xsuaa", - "destination": "backend" - }, - { - "source": "^/api/notes/(.*)", - "authenticationType": "xsuaa", - "destination": "backend" - }, - { - "source": "^/api/(.*)$", - "authenticationType": "none", - "destination": "backend" - } + { + "source": "^/app/(.*)$", + "cacheControl": "no-cache, no-store, must-revalidate", + "target": "$1", + "localDir": "./", + "authenticationType": "xsuaa" + }, + { + "source": "^/appconfig/(.*)$", + "localDir": "./", + "authenticationType": "xsuaa" + }, + { + "source": "^/browse/webapp/(.*)$", + "localDir": "./", + "authenticationType": "xsuaa" + }, + { + "source": "^/admin/webapp/(.*)$", + "localDir": "./", + "authenticationType": "xsuaa" + }, + { + "source": "^/orders/webapp/(.*)$", + "localDir": "./", + "authenticationType": "xsuaa" + }, + { + "source": "^/genres/webapp/(.*)$", + "localDir": "./", + "authenticationType": "xsuaa" + }, + { + "source": "^/reviews/webapp/(.*)$", + "localDir": "./", + "authenticationType": "xsuaa" + }, + { + "source": "^/notes/webapp/(.*)$", + "localDir": "./", + "authenticationType": "xsuaa" + }, + { + "source": "^/addresses/webapp/(.*)$", + "localDir": "./", + "authenticationType": "xsuaa" + }, + { + "source": "^/vue/(.*)$", + "localDir": "./", + "authenticationType": "xsuaa" + }, + { + "source": "^/api/admin/(.*)", + "authenticationType": "xsuaa", + "destination": "backend" + }, + { + "source": "^/api/browse/(.*)", + "authenticationType": "xsuaa", + "destination": "backend" + }, + { + "source": "^/api/review/(.*)", + "authenticationType": "xsuaa", + "destination": "backend" + }, + { + "source": "^/api/notes/(.*)", + "authenticationType": "xsuaa", + "destination": "backend" + }, + { + "source": "^/api/(.*)$", + "authenticationType": "none", + "destination": "backend" + } ] } diff --git a/db/books.cds b/db/books.cds index fe2e5e0a..1fd06ae9 100644 --- a/db/books.cds +++ b/db/books.cds @@ -2,7 +2,6 @@ namespace my.bookshop; using { Currency, - sap, managed, cuid } from '@sap/cds/common'; @@ -25,7 +24,7 @@ entity Books : cuid, managed { } entity Authors : cuid, managed { - @assert.format : '^\p{Lu}.*' // assert that name starts with a capital letter + @assert.format: '^\p{Lu}.*' // assert that name starts with a capital letter name : String(111); dateOfBirth : Date; dateOfDeath : Date; @@ -37,17 +36,21 @@ entity Authors : cuid, managed { // annotations for Data Privacy annotate Authors with -@PersonalData : { DataSubjectRole : 'Author', EntitySemantics : 'DataSubject' } -{ - ID @PersonalData.FieldSemantics : 'DataSubjectID'; - name @PersonalData.IsPotentiallySensitive; +@PersonalData: { + DataSubjectRole: 'Author', + EntitySemantics: 'DataSubject' +} { + ID @PersonalData.FieldSemantics: 'DataSubjectID'; + name @PersonalData.IsPotentiallySensitive; } /** * Hierarchically organized Code List for Genres */ -entity Genres : sap.common.CodeList { +entity Genres { key ID : Integer; + name : localized String(255); + descr : localized String(1000); parent : Association to Genres; children : Composition of many Genres on children.parent = $self; diff --git a/db/data/my.bookshop-Books.csv b/db/data/my.bookshop-Books.csv index dd4baa1a..e5453379 100644 --- a/db/data/my.bookshop-Books.csv +++ b/db/data/my.bookshop-Books.csv @@ -1,6 +1,6 @@ ID;TITLE;DESCR;AUTHOR_ID;STOCK;PRICE;CURRENCY_CODE;GENRE_ID;RATING;ISBN -f846b0b9-01d4-4f6d-82a4-d79204f62278;Wuthering Heights;"Wuthering Heights, Emily Brontë's only novel, was published in 1847 under the pseudonym ""Ellis Bell"". It was written between October 1845 and June 1846. Wuthering Heights and Anne Brontë's Agnes Grey were accepted by publisher Thomas Newby before the success of their sister Charlotte's novel Jane Eyre. After Emily's death, Charlotte edited the manuscript of Wuthering Heights and arranged for the edited version to be published as a posthumous second edition in 1850.";335c7bcd-b826-4f14-a788-e0bf6738617a;12;11.11;GBP;11;4.5;979-8698267973 -9b084139-0b1e-43b6-b12a-7b3669d75f02;Jane Eyre;"Jane Eyre /ɛər/ (originally published as Jane Eyre: An Autobiography) is a novel by English writer Charlotte Brontë, published under the pen name ""Currer Bell"", on 16 October 1847, by Smith, Elder & Co. of London. The first American edition was published the following year by Harper & Brothers of New York. Primarily a bildungsroman, Jane Eyre follows the experiences of its eponymous heroine, including her growth to adulthood and her love for Mr. Rochester, the brooding master of Thornfield Hall. The novel revolutionised prose fiction in that the focus on Jane's moral and spiritual development is told through an intimate, first-person narrative, where actions and events are coloured by a psychological intensity. The book contains elements of social criticism, with a strong sense of Christian morality at its core and is considered by many to be ahead of its time because of Jane's individualistic character and how the novel approaches the topics of class, sexuality, religion and feminism.";e3da2c2e-72ee-45d5-8def-52964c7b252a;11;12.34;GBP;11;3.0;979-8598716472 -51061ce3-ddde-4d70-a2dc-6314afbcc73e;The Raven;"“The Raven"" is a narrative poem by American writer Edgar Allan Poe. First published in January 1845, the poem is often noted for its musicality, stylized language, and supernatural atmosphere. It tells of a talking raven's mysterious visit to a distraught lover, tracing the man's slow fall into madness. The lover, often identified as being a student, is lamenting the loss of his love, Lenore. Sitting on a bust of Pallas, the raven seems to further distress the protagonist with its constant repetition of the word ""Nevermore"". The poem makes use of folk, mythological, religious, and classical references.";e7643aae-2d2f-4656-bb2d-1328ad3c8045;333;13.13;USD;16;2.5;978-1092909747 -aebdfc8a-0dfa-4468-bd36-48aabd65e663;Eleonora;"""Eleonora"" is a short story by Edgar Allan Poe, first published in 1842 in Philadelphia in the literary annual The Gift. It is often regarded as somewhat autobiographical and has a relatively ""happy"" ending.";e7643aae-2d2f-4656-bb2d-1328ad3c8045;555;14;USD;16;1.0;979-8669820985 -4a519e61-3c3a-4bd9-ab12-d7e0c5329933;Catweazle;Catweazle is a British fantasy television series, starring Geoffrey Bayldon in the title role, and created by Richard Carpenter for London Weekend Television. The first series, produced and directed by Quentin Lawrence, was screened in the UK on ITV in 1970. The second series, directed by David Reid and David Lane, was shown in 1971. Each series had thirteen episodes, most but not all written by Carpenter, who also published two books based on the scripts.;3c081d9d-abda-4da9-8b6a-4f4555bb26bc;22;15;EUR;13;4.0;978-3473523023 +f846b0b9-01d4-4f6d-82a4-d79204f62278;Wuthering Heights;"Wuthering Heights, Emily Brontë's only novel, was published in 1847 under the pseudonym ""Ellis Bell"". It was written between October 1845 and June 1846. Wuthering Heights and Anne Brontë's Agnes Grey were accepted by publisher Thomas Newby before the success of their sister Charlotte's novel Jane Eyre. After Emily's death, Charlotte edited the manuscript of Wuthering Heights and arranged for the edited version to be published as a posthumous second edition in 1850.";335c7bcd-b826-4f14-a788-e0bf6738617a;12;11.11;GBP;103;4.5;979-8698267973 +9b084139-0b1e-43b6-b12a-7b3669d75f02;Jane Eyre;"Jane Eyre /ɛər/ (originally published as Jane Eyre: An Autobiography) is a novel by English writer Charlotte Brontë, published under the pen name ""Currer Bell"", on 16 October 1847, by Smith, Elder & Co. of London. The first American edition was published the following year by Harper & Brothers of New York. Primarily a bildungsroman, Jane Eyre follows the experiences of its eponymous heroine, including her growth to adulthood and her love for Mr. Rochester, the brooding master of Thornfield Hall. The novel revolutionised prose fiction in that the focus on Jane's moral and spiritual development is told through an intimate, first-person narrative, where actions and events are coloured by a psychological intensity. The book contains elements of social criticism, with a strong sense of Christian morality at its core and is considered by many to be ahead of its time because of Jane's individualistic character and how the novel approaches the topics of class, sexuality, religion and feminism.";e3da2c2e-72ee-45d5-8def-52964c7b252a;11;12.34;GBP;103;3.0;979-8598716472 +51061ce3-ddde-4d70-a2dc-6314afbcc73e;The Raven;"“The Raven"" is a narrative poem by American writer Edgar Allan Poe. First published in January 1845, the poem is often noted for its musicality, stylized language, and supernatural atmosphere. It tells of a talking raven's mysterious visit to a distraught lover, tracing the man's slow fall into madness. The lover, often identified as being a student, is lamenting the loss of his love, Lenore. Sitting on a bust of Pallas, the raven seems to further distress the protagonist with its constant repetition of the word ""Nevermore"". The poem makes use of folk, mythological, religious, and classical references.";e7643aae-2d2f-4656-bb2d-1328ad3c8045;333;13.13;USD;117;2.5;978-1092909747 +aebdfc8a-0dfa-4468-bd36-48aabd65e663;Eleonora;"""Eleonora"" is a short story by Edgar Allan Poe, first published in 1842 in Philadelphia in the literary annual The Gift. It is often regarded as somewhat autobiographical and has a relatively ""happy"" ending.";e7643aae-2d2f-4656-bb2d-1328ad3c8045;555;14;USD;117;1.0;979-8669820985 +4a519e61-3c3a-4bd9-ab12-d7e0c5329933;Catweazle;Catweazle is a British fantasy television series, starring Geoffrey Bayldon in the title role, and created by Richard Carpenter for London Weekend Television. The first series, produced and directed by Quentin Lawrence, was screened in the UK on ITV in 1970. The second series, directed by David Reid and David Lane, was shown in 1971. Each series had thirteen episodes, most but not all written by Carpenter, who also published two books based on the scripts.;3c081d9d-abda-4da9-8b6a-4f4555bb26bc;22;15;EUR;110;4.0;978-3473523023 diff --git a/db/data/my.bookshop-Genres.csv b/db/data/my.bookshop-Genres.csv index 88e73bdd..84bb85b0 100644 --- a/db/data/my.bookshop-Genres.csv +++ b/db/data/my.bookshop-Genres.csv @@ -1,16 +1,31 @@ ID;parent_ID;name -10;;Fiction -11;10;Drama -12;10;Poetry -13;10;Fantasy -14;10;Science Fiction -15;10;Romance -16;10;Mystery -17;10;Thriller -18;10;Dystopia -19;10;Fairy Tale -20;;Non-Fiction -21;20;Biography -22;21;Autobiography -23;20;Essay -24;20;Speech \ No newline at end of file +100;;Fiction +101;100;Action +102;100;Adventure +103;100;Drama +105;100;Poetry +106;100;Science Fiction +107;106;Utopian and Dystopian +108;107;Dystopia +109;108;Cyberpunk +110;109;Steampunk +104;100;Fantasy +111;104;Epic fantasy +112;104;High fantasy +113;100;Graphic Novel +115;100;Short Story +116;100;Romance +117;100;Mystery +123;117;Thriller +124;117;Suspense +118;100;Horror +119;100;Historical Fiction +120;100;Contemporary Fiction +121;100;Magical Realism +122;100;Literary Fiction +128;100;Fairy Tale +200;;Non-Fiction +201;200;Biography +202;201;Autobiography +203;200;Essay +204;200;Speech diff --git a/db/reviews.cds b/db/reviews.cds index 7015fbf6..318844f7 100644 --- a/db/reviews.cds +++ b/db/reviews.cds @@ -9,17 +9,17 @@ using my.bookshop.Books from './books'; entity Reviews : cuid, managed { @cds.odata.ValueList - book : Association to Books; - rating : Rating; - title : String(111); - text : String(1111); + book : Association to Books; + rating : Rating; + title : String(111); + text : String(1111); } // input validation annotate Reviews with { title @mandatory; rating @assert.range; - book @mandatory @assert.target; + book @mandatory @assert.target; } type Rating : Integer enum { diff --git a/srv/admin-service.cds b/srv/admin-service.cds index 79d3ce34..4d3b93f3 100644 --- a/srv/admin-service.cds +++ b/srv/admin-service.cds @@ -1,34 +1,43 @@ using {sap.common.Languages as CommonLanguages} from '@sap/cds/common'; using {my.bookshop as my} from '../db/index'; using {sap.changelog as changelog} from 'com.sap.cds/change-tracking'; -using {sap.attachments.Attachments} from `com.sap.cds/cds-feature-attachments`; +using {my.common.Hierarchy as Hierarchy} from './hierarchy'; +using {sap.attachments.Attachments} from 'com.sap.cds/cds-feature-attachments'; extend my.Orders with changelog.changeTracked; -@path : 'admin' -service AdminService @(requires : 'admin') { - entity Books as projection on my.Books excluding { reviews } actions { - action addToOrder(order_ID : UUID, quantity : Integer) returns Orders; - } +@path: 'admin' +@odata.apply.transformations +service AdminService @(requires: 'admin') { + entity Books as + projection on my.Books + excluding { + reviews + } + actions { + action addToOrder(order_ID : UUID, quantity : Integer) returns Orders; + } - entity Authors as projection on my.Authors; - entity Orders as select from my.Orders; + entity Authors as projection on my.Authors; + entity Orders as select from my.Orders; + extend my.Genres with Hierarchy; + entity GenreHierarchy as projection on my.Genres; @cds.persistence.skip entity Upload @odata.singleton { - csv : LargeBinary @Core.MediaType : 'text/csv'; + csv : LargeBinary @Core.MediaType: 'text/csv'; } } // Deep Search Items -annotate AdminService.Orders with @cds.search : { +annotate AdminService.Orders with @cds.search: { OrderNo, Items }; -annotate AdminService.OrderItems with @cds.search : {book}; +annotate AdminService.OrderItems with @cds.search: {book}; -annotate AdminService.Books with @cds.search : { +annotate AdminService.Books with @cds.search: { descr, title }; @@ -60,12 +69,13 @@ annotate AdminService.OrderItems { // Assign identifiers to the tracked entities annotate AdminService.Orders with @changelog: [OrderNo]; + annotate AdminService.OrderItems with @changelog: [ - parent.OrderNo, - book.title, - ]; + parent.OrderNo, + book.title, +]; // Extends the Books entity with the Attachments composition extend my.Books with { - covers : Composition of many Attachments; + covers : Composition of many Attachments; }; diff --git a/srv/cat-service.cds b/srv/cat-service.cds index e887271f..c83eb432 100644 --- a/srv/cat-service.cds +++ b/srv/cat-service.cds @@ -13,6 +13,9 @@ service CatalogService @(requires: 'any') { @readonly entity Authors as projection on my.Authors; + @readonly + entity Genres as projection on my.Genres; + @readonly entity Reviews as projection on my.Reviews; diff --git a/srv/hierarchy.cds b/srv/hierarchy.cds new file mode 100644 index 00000000..f6619d98 --- /dev/null +++ b/srv/hierarchy.cds @@ -0,0 +1,29 @@ +namespace my.common; + +aspect Hierarchy { + virtual LimitedDescendantCount : Integer64; + virtual DistanceFromRoot : Integer64; + virtual DrillState : String; + virtual Matched : Boolean; + virtual MatchedDescendantCount : Integer64; + virtual LimitedRank : Integer64; +} + + +annotate Hierarchy with @Capabilities.FilterRestrictions.NonFilterableProperties: [ + 'LimitedDescendantCount', + 'DistanceFromRoot', + 'DrillState', + 'Matched', + 'MatchedDescendantCount', + 'LimitedRank' +]; + +annotate Hierarchy with @Capabilities.SortRestrictions.NonSortableProperties: [ + 'LimitedDescendantCount', + 'DistanceFromRoot', + 'DrillState', + 'Matched', + 'MatchedDescendantCount', + 'LimitedRank' +]; diff --git a/srv/review-service.cds b/srv/review-service.cds index d87950f9..0afa2e92 100644 --- a/srv/review-service.cds +++ b/srv/review-service.cds @@ -1,28 +1,33 @@ using {my.bookshop as my} from '../db/index'; -@path : 'review' +@path: 'review' service ReviewService { entity Reviews as projection on my.Reviews; @readonly - entity Books as projection on my.Books excluding { - createdBy, - modifiedBy - } + entity Books as + projection on my.Books + excluding { + createdBy, + modifiedBy + } @readonly entity Authors as projection on my.Authors; + @readonly + entity Genres as projection on my.Genres; + // access control restrictions - annotate Reviews with @restrict : [ + annotate Reviews with @restrict: [ { - grant : '*', - to : 'authenticated-user', - where : (createdBy=$user) + grant: '*', + to: 'authenticated-user', + where: (createdBy = $user) }, { - grant : '*', - to : 'admin', + grant: '*', + to: 'admin', } ]; } diff --git a/srv/src/main/java/my/bookshop/handlers/HierarchyHandler.java b/srv/src/main/java/my/bookshop/handlers/HierarchyHandler.java new file mode 100644 index 00000000..bdd875a0 --- /dev/null +++ b/srv/src/main/java/my/bookshop/handlers/HierarchyHandler.java @@ -0,0 +1,313 @@ +package my.bookshop.handlers; + +import java.util.ArrayDeque; +import java.util.Comparator; +import java.util.Deque; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +import org.springframework.context.annotation.Profile; +import org.springframework.stereotype.Component; + +import com.sap.cds.Row; +import com.sap.cds.ql.CQL; +import com.sap.cds.ql.Select; +import com.sap.cds.ql.cqn.CqnElementRef; +import com.sap.cds.ql.cqn.CqnPredicate; +import com.sap.cds.ql.cqn.CqnSelect; +import com.sap.cds.ql.cqn.CqnValue; +import com.sap.cds.ql.cqn.Modifier; +import com.sap.cds.ql.cqn.transformation.CqnTopLevelsTransformation; +import com.sap.cds.ql.cqn.transformation.CqnAncestorsTransformation; +import com.sap.cds.ql.cqn.transformation.CqnDescendantsTransformation; +import com.sap.cds.ql.cqn.transformation.CqnFilterTransformation; +import com.sap.cds.ql.cqn.transformation.CqnSearchTransformation; +import com.sap.cds.ql.cqn.transformation.CqnOrderByTransformation; +import com.sap.cds.ql.cqn.transformation.CqnTransformation; +import com.sap.cds.services.cds.CdsReadEventContext; +import com.sap.cds.services.cds.CqnService; +import com.sap.cds.services.handler.EventHandler; +import com.sap.cds.services.handler.annotations.Before; +import com.sap.cds.services.handler.annotations.ServiceName; +import com.sap.cds.services.persistence.PersistenceService; + +import cds.gen.adminservice.AdminService_; +import cds.gen.adminservice.GenreHierarchy; +import cds.gen.adminservice.GenreHierarchy_; + +import static cds.gen.adminservice.AdminService_.GENRE_HIERARCHY; + +@Component +@Profile("default") // non-HANA +@ServiceName(AdminService_.CDS_NAME) +/** + * On HANA, requests for GenreHierarchy are handled generically. + * + * This handler is only in effect when running with the `default` profile on + * H2. It is a stand-in for non-HANA until the CAP Java runtime can also handle + * requests for hierarchies on non-HANA databases. + * + * The handler is neither functionally complete nor correct for all requests. It + * is not intended as a blue-print for custom code. + */ +public class HierarchyHandler implements EventHandler { + + private final PersistenceService db; + + HierarchyHandler(PersistenceService db) { + this.db = db; + } + + @Before(event = CqnService.EVENT_READ, entity = GenreHierarchy_.CDS_NAME) + public void readGenreHierarchy(CdsReadEventContext event) { + List trafos = event.getCqn().transformations(); + List result = null; + + if (trafos.size() < 1) { + return; + } + + if (getTopLevels(trafos) instanceof CqnTopLevelsTransformation topLevels) { + result = topLevels(topLevels, CQL.TRUE); + } else if (trafos.get(0) instanceof CqnDescendantsTransformation descendants) { + result = handleDescendants(descendants); + } else if (trafos.get(0) instanceof CqnAncestorsTransformation ancestors) { + if (trafos.size() == 2 && trafos.get(1) instanceof CqnTopLevelsTransformation topLevels) { + result = handleAncestors(ancestors, topLevels); + } else if (trafos.size() == 3 && trafos.get(2) instanceof CqnTopLevelsTransformation topLevels) { + result = handleAncestors(ancestors, topLevels); + } + } + + setResult(event, result); + } + + private CqnTopLevelsTransformation getTopLevels(List trafos) { + if (trafos.get(0) instanceof CqnTopLevelsTransformation topLevels) { + return topLevels; + } else if (trafos.size() == 2 && trafos.get(0) instanceof CqnOrderByTransformation + && trafos.get(1) instanceof CqnTopLevelsTransformation topLevels) { + return topLevels; + } + return null; + } + + private void setResult(CdsReadEventContext event, List result) { + if (!result.isEmpty()) { + addDrillState(result); + } + + event.setResult(result); + } + + private void addDrillState(List ghs) { + List ids = ghs.stream().map(gh -> gh.getId()).toList(); + Set parents = ghs.stream().map(gh -> gh.getParentId()).filter(p -> p != null) + .collect(Collectors.toSet()); + CqnSelect q = Select.from(GENRE_HIERARCHY).columns(gh -> gh.parent_ID().as("id")) + .where(gh -> gh.parent_ID().in(ids)); + Set nonLeafs = db + .run(q) + .stream().map(r -> r.get("id")).collect(Collectors.toSet()); + + for (GenreHierarchy gh : ghs) { + Integer id = gh.getId(); + if (nonLeafs.contains(id)) { + if (parents.contains(id)) { + gh.setDrillState("expanded"); + } else { + gh.setDrillState("collapsed"); + } + } else { + gh.setDrillState("leaf"); + } + } + } + + private CqnPredicate descendantsFilter(CqnDescendantsTransformation descendants) { + CqnTransformation trafo = descendants.transformations().get(0); + CqnPredicate start = ((CqnFilterTransformation) trafo).filter(); + CqnPredicate result = CQL.FALSE; + if (descendants.keepStart()) { + result = CQL.or(result, start); + } + CqnPredicate children = CQL.copy(start, new Modifier() { + @Override + public CqnValue ref(CqnElementRef ref) { + return CQL.get(GenreHierarchy.PARENT_ID); + } + }); + result = CQL.or(result, children); + + return result; + } + + private CqnPredicate ancestorsFilter(CqnAncestorsTransformation ancestors) { + CqnTransformation trafo = ancestors.transformations().get(0); + Select inner = Select.from(GENRE_HIERARCHY).columns(gh -> gh.ID()); + if (trafo instanceof CqnFilterTransformation filter) { + inner.where(filter.filter()); + } else if (trafo instanceof CqnSearchTransformation search) { + inner.search(search.search()); + } + + Select outer = Select.from(GENRE_HIERARCHY) + .columns(gh -> gh.ID().as("i0"), + gh -> gh.parent().ID().as("i1"), + gh -> gh.parent().parent().ID().as("i2"), + gh -> gh.parent().parent().parent().ID().as("i3"), + gh -> gh.parent().parent().parent().parent().ID().as("i4")) + .where(gh -> gh.ID().in(inner)); + + Set ancestorIds = new HashSet<>(); + db.run(outer).stream().forEach(r -> { + addIfNotNull(ancestorIds, r, "i0"); + addIfNotNull(ancestorIds, r, "i1"); + addIfNotNull(ancestorIds, r, "i2"); + addIfNotNull(ancestorIds, r, "i3"); + addIfNotNull(ancestorIds, r, "i4"); + }); + + return CQL.get(GenreHierarchy_.ID).in(ancestorIds.stream().toList()); + } + + private List handleDescendants(CqnDescendantsTransformation descendants) { + CqnPredicate filter = descendantsFilter(descendants); + CqnSelect childrenCQN = Select.from(GENRE_HIERARCHY).where(filter); + List nodes = db.run(childrenCQN).listOf(GenreHierarchy.class); + + connect(nodes); + + return nodes.stream().sorted(new Sorter()).toList(); + } + + private static void connect(List nodes) { + Map lookup = new HashMap<>(); + nodes.forEach(gh -> lookup.put(gh.getId(), gh)); + nodes.forEach(gh -> gh.setParent(lookup.get(gh.getParentId()))); + nodes.forEach(gh -> gh.setDistanceFromRoot(distanceFromRoot(gh))); + } + + private List handleAncestors(CqnAncestorsTransformation ancestors, + CqnTopLevelsTransformation topLevels) { + CqnPredicate filter = ancestorsFilter(ancestors); + + return topLevels(topLevels, filter); + } + + private void addIfNotNull(Set ancestorIds, Row r, String key) { + Integer id = (Integer) r.get(key); + if (id != null) { + ancestorIds.add(id); + } + } + + private List topLevels(CqnTopLevelsTransformation topLevels, CqnPredicate filter) { + return topLevels.levels() < 0 ? topLevelsAll(filter) : topLevelsLimit(topLevels, filter); + } + + private List topLevelsLimit(CqnTopLevelsTransformation topLevels, CqnPredicate filter) { + long limit = topLevels.levels(); + Map lookup = new HashMap<>(); + Map expandLevels = topLevels.expandLevels(); + + CqnSelect getRoots = Select.from(GENRE_HIERARCHY).where(gh -> gh.parent_ID().isNull().and(filter)); + List roots = db.run(getRoots).listOf(GenreHierarchy.class); + roots.forEach(root -> { + root.setDistanceFromRoot(0l); + lookup.put(root.getId(), root); + List parents = List.of(root.getId()); + for (long i = 1; i < limit; i++) { + List ps = parents; + CqnSelect getChildren = Select.from(GENRE_HIERARCHY) + .where(gh -> gh.parent_ID().in(ps).and(filter)); + List children = db.run(getChildren).listOf(GenreHierarchy.class); + if (children.isEmpty()) { + break; + } + long dfr = i; + parents = children.stream().peek(gh -> { + gh.setParent(lookup.get(gh.getParentId())); + gh.setDistanceFromRoot(dfr); + lookup.put(gh.getId(), gh); + }).map(GenreHierarchy::getId).toList(); + } + }); + + if (!expandLevels.isEmpty()) { + List expandedIds = expandLevels.keySet().stream().map(key -> (Integer) key).toList(); + CqnSelect expandedCQN = Select.from(AdminService_.GENRE_HIERARCHY).where(gh -> CQL.and(filter, + CQL.or(gh.ID().in(expandedIds), gh.parent_ID().in(expandedIds)))); + + List expanded = db.run(expandedCQN).listOf(GenreHierarchy.class); + expanded.forEach(gh -> { + if (!lookup.keySet().contains(gh.getId())) { + gh.setParent(lookup.get(gh.getParentId())); + gh.setDistanceFromRoot(distanceFromRoot(gh)); + lookup.put(gh.getId(), gh); + } + }); + + } + + return lookup.values().stream().sorted(new Sorter()).toList(); + } + + private List topLevelsAll(CqnPredicate filter) { + CqnSelect allCqn = Select.from(GENRE_HIERARCHY).where(filter); + var all = db.run(allCqn).listOf(GenreHierarchy.class); + + connect(all); + + return all.stream().sorted(new Sorter()).toList(); + } + + private static long distanceFromRoot(GenreHierarchy gh) { + long dfr = 0; + while (gh.getParent() != null) { + dfr++; + gh = gh.getParent(); + } + + return dfr; + } + + static class Sorter implements Comparator { + + @Override + public int compare(GenreHierarchy gh1, GenreHierarchy gh2) { + Deque path1 = getPath(gh1); + Deque path2 = getPath(gh2); + int res = 0; + + while (true) { + if (path1.isEmpty()) { + return path2.isEmpty() ? 0 : -1; + } + if (path2.isEmpty()) { + return +1; + } + String last1 = path1.pop(); + String last2 = path2.pop(); + res = last1.compareTo(last2); + if (res != 0) { + return res; + } + } + } + + Deque getPath(GenreHierarchy gh) { + Deque path = new ArrayDeque<>(); + do { + path.push(gh.getName()); + gh = gh.getParent(); + } while (gh != null); + + return path; + } + } +} diff --git a/srv/src/test/java/my/bookshop/GenreHierarchyTest.java b/srv/src/test/java/my/bookshop/GenreHierarchyTest.java new file mode 100644 index 00000000..e519a2b4 --- /dev/null +++ b/srv/src/test/java/my/bookshop/GenreHierarchyTest.java @@ -0,0 +1,239 @@ +package my.bookshop; + +import static org.assertj.core.api.Assumptions.assumeThat; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import java.net.URI; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.core.env.Environment; +import org.springframework.core.env.Profiles; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.ResultActions; +import org.springframework.web.util.UriComponentsBuilder; + +@SpringBootTest +@AutoConfigureMockMvc +public class GenreHierarchyTest { + + @Autowired + private MockMvc client; + + @Autowired + Environment env; + + private static final String genresURI = "/api/admin/GenreHierarchy"; + + @Test + @WithMockUser(username = "admin") + void testGetAll() throws Exception { + client.perform(get(genresURI)).andExpect(status().isOk()); + } + + @Test + @WithMockUser(username = "admin") + void testCountAll() throws Exception { + client.perform(get(genresURI + "/$count")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$").value(30)); + } + + @Test + @WithMockUser(username = "admin") + void testStartOneLevel() throws Exception { + client.perform(get(genresURI + + "?$select=DrillState,ID,name,DistanceFromRoot" + + "&$apply=orderby(name)/" + + "com.sap.vocabularies.Hierarchy.v1.TopLevels(HierarchyNodes=$root/GenreHierarchy,HierarchyQualifier='GenreHierarchy',NodeProperty='ID',Levels=1)" + + "&$count=true")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.value[0].ID").value(100)) + .andExpect(jsonPath("$.value[0].name").value("Fiction")) + .andExpect(jsonPath("$.value[0].DistanceFromRoot").value(0)) + .andExpect(jsonPath("$.value[0].DrillState").value("collapsed")) + .andExpect(jsonPath("$.value[1].ID").value(200)) + .andExpect(jsonPath("$.value[1].name").value("Non-Fiction")) + .andExpect(jsonPath("$.value[1].DistanceFromRoot").value(0)) + .andExpect(jsonPath("$.value[1].DrillState").value("collapsed")) + .andExpect(jsonPath("$.value[2]").doesNotExist()); + } + + @Test + @WithMockUser(username = "admin") + void testStartTwoLevels() throws Exception { + client.perform(get(genresURI + + "?$select=DrillState,ID,name,DistanceFromRoot" + + "&$apply=orderby(name)/" + + "com.sap.vocabularies.Hierarchy.v1.TopLevels(HierarchyNodes=$root/GenreHierarchy,HierarchyQualifier='GenreHierarchy',NodeProperty='ID',Levels=2)" + + "&$count=true")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.value[0].ID").value(100)) + .andExpect(jsonPath("$.value[0].name").value("Fiction")) + .andExpect(jsonPath("$.value[0].DrillState").value("expanded")) + .andExpect(jsonPath("$.value[0].DistanceFromRoot").value(0)) + .andExpect(jsonPath("$.value[1].ID").value(101)) + .andExpect(jsonPath("$.value[1].name").value("Action")) + .andExpect(jsonPath("$.value[1].DrillState").value("leaf")) + .andExpect(jsonPath("$.value[1].DistanceFromRoot").value(1)) + .andExpect(jsonPath("$.value[20].ID").value(204)) + .andExpect(jsonPath("$.value[20].name").value("Speech")) + .andExpect(jsonPath("$.value[20].DrillState").value("leaf")) + .andExpect(jsonPath("$.value[20].DistanceFromRoot").value(1)) + .andExpect(jsonPath("$.value[21]").doesNotExist()); + } + + @Test + @WithMockUser(username = "admin") + void testExpandNonFiction() throws Exception { + client.perform(get(genresURI + + "?$select=DrillState,ID,name" + + "&$apply=descendants($root/GenreHierarchy,GenreHierarchy,ID,filter(ID eq 200),1)" + + "/orderby(ID)")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.value[0].ID").value(201)) + .andExpect(jsonPath("$.value[0].name").value("Biography")) + .andExpect(jsonPath("$.value[0].DrillState").value("collapsed")) + .andExpect(jsonPath("$.value[1].ID").value(203)) + .andExpect(jsonPath("$.value[1].name").value("Essay")) + .andExpect(jsonPath("$.value[1].DrillState").value("leaf")) + .andExpect(jsonPath("$.value[2].ID").value(204)) + .andExpect(jsonPath("$.value[2].name").value("Speech")) + .andExpect(jsonPath("$.value[2].DrillState").value("leaf")) + .andExpect(jsonPath("$.value[3]").doesNotExist()); + } + + @Test + @WithMockUser(username = "admin") + void testCollapseAll() throws Exception { + client.perform(get(genresURI + + "?$select=DrillState,ID,name" + + "&$apply=com.sap.vocabularies.Hierarchy.v1.TopLevels(HierarchyNodes=$root/GenreHierarchy,HierarchyQualifier='GenreHierarchy',NodeProperty='ID',Levels=1)" + + "&$count=true&$skip=0&$top=238")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.value[0].name").value("Fiction")) + .andExpect(jsonPath("$.value[0].DrillState").value("collapsed")) + .andExpect(jsonPath("$.value[1].name").value("Non-Fiction")) + .andExpect(jsonPath("$.value[1].DrillState").value("collapsed")) + .andExpect(jsonPath("$.value[2]").doesNotExist()); + } + + @Test + @WithMockUser(username = "admin") + void testExpandAll() throws Exception { + String url = genresURI + + "?$select=DistanceFromRoot,DrillState,ID,LimitedDescendantCount,name" + + "&$apply=com.sap.vocabularies.Hierarchy.v1.TopLevels(HierarchyNodes=$root/GenreHierarchy,HierarchyQualifier='GenreHierarchy',NodeProperty='ID')" + + "&$count=true&$skip=0&$top=238"; + + ResultActions expectations = client.perform(get(url)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.value[0].ID").value(100)) + .andExpect(jsonPath("$.value[0].name").value("Fiction")) + .andExpect(jsonPath("$.value[0].DrillState").value("expanded")) + .andExpect(jsonPath("$.value[0].DistanceFromRoot").value(0)) + .andExpect(jsonPath("$.value[29].name").value("Speech")) + .andExpect(jsonPath("$.value[29].DrillState").value("leaf")) + .andExpect(jsonPath("$.value[30]").doesNotExist()); + if (isOnHana()) { + expectations.andExpect(jsonPath("$.value[0].LimitedDescendantCount").value(24)); + } + } + + @Test + @WithMockUser(username = "admin") + void testSearch() throws Exception { + ResultActions expectations = client.perform(get(genresURI + + "?$select=DistanceFromRoot,DrillState,ID,LimitedDescendantCount,name" + + "&$apply=ancestors($root/GenreHierarchy,GenreHierarchy,ID,search(\"ry\"),keep start)" + + "/orderby(name)" + + "/com.sap.vocabularies.Hierarchy.v1.TopLevels(HierarchyNodes=$root/GenreHierarchy,HierarchyQualifier='GenreHierarchy',NodeProperty='ID')" + + "&$count=true")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.value[0].ID").value(100)) + .andExpect(jsonPath("$.value[0].name").value("Fiction")) + .andExpect(jsonPath("$.value[0].DrillState").value("expanded")) + .andExpect(jsonPath("$.value[0].DistanceFromRoot").value(0)) + .andExpect(jsonPath("$.value[1].ID").value(120)) + .andExpect(jsonPath("$.value[1].name").value("Contemporary Fiction")) + .andExpect(jsonPath("$.value[1].DrillState").value("leaf")) + .andExpect(jsonPath("$.value[1].DistanceFromRoot").value(1)) + .andExpect(jsonPath("$.value[2].ID").value(128)) + .andExpect(jsonPath("$.value[2].name").value("Fairy Tale")) + .andExpect(jsonPath("$.value[2].DrillState").value("leaf")) + .andExpect(jsonPath("$.value[2].DistanceFromRoot").value(1)) + .andExpect(jsonPath("$.value[3].ID").value(122)) + .andExpect(jsonPath("$.value[6].name").value("Short Story")) + .andExpect(jsonPath("$.value[6].DrillState").value("leaf")) + .andExpect(jsonPath("$.value[6].DistanceFromRoot").value(1)) + .andExpect(jsonPath("$.value[7]").doesNotExist()) + ; + if (isOnHana()) { + expectations.andExpect(jsonPath("$.value[0].LimitedDescendantCount").value(6)) + .andExpect(jsonPath("$.value[1].LimitedDescendantCount").value(0)) + .andExpect(jsonPath("$.value[2].LimitedDescendantCount").value(0)) + .andExpect(jsonPath("$.value[6].LimitedDescendantCount").value(0)); + } + } + + @Test + @WithMockUser(username = "admin") + void testFilterNotExpanded() throws Exception { + client.perform(get(genresURI + + "?$select=DrillState,ID,name,DistanceFromRoot" + + "&$apply=ancestors($root/GenreHierarchy,GenreHierarchy,ID,filter(name eq 'Autobiography'),keep start)/orderby(name)" + + "/com.sap.vocabularies.Hierarchy.v1.TopLevels(HierarchyNodes=$root/GenreHierarchy,HierarchyQualifier='GenreHierarchy',NodeProperty='ID',Levels=1)")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.value[0].ID").value(200)) + .andExpect(jsonPath("$.value[0].name").value("Non-Fiction")) + .andExpect(jsonPath("$.value[0].DrillState").value("collapsed")) + .andExpect(jsonPath("$.value[0].DistanceFromRoot").value(0)) + .andExpect(jsonPath("$.value[1]").doesNotExist()); + } + + @Test + @WithMockUser(username = "admin") + void testFilterExpandLevels() throws Exception { + String expandLevelsJson = """ + [{"NodeID":100,"Levels":1},{"NodeID":200,"Levels":1}]\ + """; + String unencoded = genresURI + "?$select=DistanceFromRoot,DrillState,ID,LimitedDescendantCount,name" + + "&$apply=ancestors($root/GenreHierarchy,GenreHierarchy,ID,filter(name eq 'Autobiography'),keep start)/orderby(name)" + + "/com.sap.vocabularies.Hierarchy.v1.TopLevels(HierarchyNodes=$root/GenreHierarchy,HierarchyQualifier='GenreHierarchy',NodeProperty='ID',Levels=1,ExpandLevels=" + + expandLevelsJson + ")&$count=true"; + String uriString = UriComponentsBuilder.fromUriString(unencoded).toUriString(); + URI uri = URI.create(uriString); + client.perform(get(uri)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.value[0].ID").value(200)) + .andExpect(jsonPath("$.value[0].name").value("Non-Fiction")) + .andExpect(jsonPath("$.value[0].DrillState").value("expanded")) + .andExpect(jsonPath("$.value[0].DistanceFromRoot").value(0)) + .andExpect(jsonPath("$.value[2]").doesNotExist()); + } + + @Test + @WithMockUser(username = "admin") + void testStartTwoLevelsOrderByDescHANA() throws Exception { + assumeThat(env.getActiveProfiles()).contains("hybrid"); + client.perform(get(genresURI + + "?$select=DrillState,ID,name,DistanceFromRoot" + + "&$apply=orderby(name desc)/" + + "com.sap.vocabularies.Hierarchy.v1.TopLevels(HierarchyNodes=$root/GenreHierarchy,HierarchyQualifier='GenreHierarchy',NodeProperty='ID',Levels=2)" + + "&$count=true")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.value[0].ID").value(200)) + .andExpect(jsonPath("$.value[1].ID").value(204)) + .andExpect(jsonPath("$.value[20].ID").value(101)) + .andExpect(jsonPath("$.value[21]").doesNotExist()); + } + + private boolean isOnHana() { + return env.acceptsProfiles(Profiles.of("hybrid")); + } +} \ No newline at end of file diff --git a/srv/src/test/java/my/bookshop/handlers/HierarchyHandlerSorterTest.java b/srv/src/test/java/my/bookshop/handlers/HierarchyHandlerSorterTest.java new file mode 100644 index 00000000..46bc78c2 --- /dev/null +++ b/srv/src/test/java/my/bookshop/handlers/HierarchyHandlerSorterTest.java @@ -0,0 +1,70 @@ +package my.bookshop.handlers; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import java.util.List; +import org.junit.jupiter.api.Test; + +import cds.gen.adminservice.GenreHierarchy; +import my.bookshop.handlers.HierarchyHandler.Sorter; + +public class HierarchyHandlerSorterTest { + + @Test + public void testSortRoots() { + GenreHierarchy r1 = genre("Philosophical fiction"); + GenreHierarchy r2 = genre("Epic"); + List sorted = sorted(r1, r2); + + assertEquals("Epic", sorted.get(0).getName()); + assertEquals("Philosophical fiction", sorted.get(1).getName()); + } + + @Test + public void testSortSiblings() { + GenreHierarchy root = genre("Folklore"); + GenreHierarchy g1 = genre("Urban legend", root); + GenreHierarchy g2 = genre("Fairy tale", root); + List sorted = sorted(g1, g2); + + assertEquals("Fairy tale", sorted.get(0).getName()); + assertEquals("Urban legend", sorted.get(1).getName()); + } + + @Test + public void testSortChildrenWithDifRoot() { + GenreHierarchy r1 = genre("Thriller"); + GenreHierarchy r2 = genre("Folklore"); + GenreHierarchy g2 = genre("Urban legend", r2); + List sorted = sorted(r1, g2); + + assertEquals("Urban legend", sorted.get(0).getName()); + assertEquals("Thriller", sorted.get(1).getName()); + } + + @Test + public void testSortChildrenSameRoot() { + GenreHierarchy r1 = genre("Folklore"); + GenreHierarchy g1 = genre("Urban legend", r1); + List sorted = sorted(g1, r1); + + assertEquals("Folklore", sorted.get(0).getName()); + assertEquals("Urban legend", sorted.get(1).getName()); + } + + private static GenreHierarchy genre(String name, GenreHierarchy parent) { + GenreHierarchy genre = GenreHierarchy.create(); + genre.setName(name); + if (parent != null) { + genre.setParent(parent); + } + return genre; + } + + private static GenreHierarchy genre(String name) { + return genre(name, null); + } + + private static List sorted(GenreHierarchy... h) { + return List.of(h).stream().sorted(new Sorter()).toList(); + } +}