diff --git a/.cdsprettier.json b/.cdsprettier.json new file mode 100644 index 0000000..d2d4809 --- /dev/null +++ b/.cdsprettier.json @@ -0,0 +1,8 @@ +{ + "maxDocCommentLine": 80, + "formatDocComments": true, + "tabSize": 2, + "alignPostAnnotations": false, + "alignColonsInAnnotations": false, + "alignValuesInAnnotations": false +} \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..08ae9e3 --- /dev/null +++ b/.gitignore @@ -0,0 +1,35 @@ +**/gen/ +**/edmx/ +*.db +*.sqlite +*.sqlite-wal +*.sqlite-shm +schema*.sql +default-env.json + +**/bin/ +**/target/ +.flattened-pom.xml +.classpath +.project +.settings + +**/node/ +**/node_modules/ +**/package-lock.json +**/.mta/ +*.mtar + +*.log* +gc_history* +hs_err* +*.tgz +*.iml + +.vscode +.idea +.reloadtrigger + +**/.DS_Store + +.cdsrc-private.json diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..b08a07c --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,15 @@ +# Change Log + +- All notable changes to this project are documented in this file. +- The format is based on [Keep a Changelog](https://keepachangelog.com/). +- This project adheres to [Semantic Versioning](https://semver.org/). + +## Version 1.0.0 - TBD + +### Added + +### Changed + +### Fixed + +### Removed \ No newline at end of file diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..017fbe5 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,38 @@ +# Contributing + +## Code of Conduct + +All members of the project community must abide by the [SAP Open Source Code of Conduct](https://github.com/SAP/.github/blob/main/CODE_OF_CONDUCT.md). +Only by respecting each other we can develop a productive, collaborative community. +Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting [a project maintainer](.reuse/dep5). + +## Engaging in Our Project + +We use GitHub to manage reviews of pull requests. + +- If you are a new contributor, see: [Steps to Contribute](#steps-to-contribute) + +- Before implementing your change, create an issue that describes the problem you would like to solve or the code that should be enhanced. Please note that you are willing to work on that issue. + +- The team will review the issue and decide whether it should be implemented as a pull request. In that case, they will assign the issue to you. If the team decides against picking up the issue, the team will post a comment with an explanation. + +## Steps to Contribute + +Should you wish to work on an issue, please claim it first by commenting on the GitHub issue that you want to work on. This is to prevent duplicated efforts from other contributors on the same issue. + +If you have questions about one of the issues, please comment on them, and one of the maintainers will clarify. + +## Contributing Code or Documentation + +You are welcome to contribute code in order to fix a bug or to implement a new feature that is logged as an issue. + +The following rule governs code contributions: + +- Contributions must be licensed under the [Apache 2.0 License](./LICENSE) +- Due to legal reasons, contributors will be asked to accept a Developer Certificate of Origin (DCO) when they create the first pull request to this project. This happens in an automated fashion during the submission process. SAP uses [the standard DCO text of the Linux Foundation](https://developercertificate.org/). + +## Issues and Planning + +- We use GitHub issues to track bugs and enhancement requests. + +- Please provide as much context as possible when you open an issue. The information you provide must be comprehensive enough to reproduce that issue for the assignee. \ No newline at end of file diff --git a/LICENSES/Apache-2.0.txt b/LICENSES/Apache-2.0.txt new file mode 100644 index 0000000..137069b --- /dev/null +++ b/LICENSES/Apache-2.0.txt @@ -0,0 +1,73 @@ +Apache License +Version 2.0, January 2004 +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. + +"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: + + (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. + + You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + +To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/README.md b/README.md index e69de29..97e8420 100644 --- a/README.md +++ b/README.md @@ -0,0 +1,153 @@ +# SAP Cloud Application Programming Model, AI plugin for Java + +This is the Java version of the [SAP CAP AI plugin for Node.js](https://github.com/cap-js/ai). + +## About this project + +The SAP Cloud Application Programming Model, AI plugin for Java provides AI-powered UI recommendations for CAP Java applications, leveraging SAP AI Core and the SAP-RPT-1 model. + +> [!IMPORTANT] +> In multi-tenancy scenarios with a sidecar, the plugin must be included in the sidecar for SAP AI Core handling. + +### 1. Use case: Recommendations + +Recommendations are implemented leveraging SAP-RPT-1 and AI Core. This plugin generically hooks into any entity which has properties with a value help (detected via `@Common.ValueList` on the property or `@cds.odata.valuelist` on the association target). + +```cds +entity Books { + key ID : Integer; + title : String(111); + descr : String(1111); + genre : Association to one Genres; + status : Association to one Status; +} +annotate Genres with @cds.odata.valuelist; +annotate Books with { + status @Common.ValueList : { + CollectionPath : 'Status', + Parameters: [ + { + $Type: 'Common.ValueListParameterInOut' + ValueListProperty : 'code', + LocalDataProperty : status_code + } + ] + } +} +``` + +The annotated fields automatically receive AI-powered recommendations in Fiori draft edit mode. The handler fetches existing rows from the database as training context, calls the RPT-1 model, and writes the predictions into the `SAP_Recommendations` property on the result. + +If you do not want recommendations for a specific field, annotate it with `@UI.RecommendationState: 0`. + +```cds +annotate Books with { + genre @UI.RecommendationState : 0; +} +``` + +### 2. Use case: Simplified AI Core usage + +The plugin introduces an `AICore` CAP service that automatically performs some administrative tasks and offers simplified access to AI Core. + +#### Automatic operations + +- The plugin automatically creates a new SAP AI Core resource group per tenant during tenant onboarding and deletes it during offboarding. +- The plugin automatically creates an RPT-1 deployment per resource group for the recommendations feature. + +## Requirements and Setup + +### Prerequisites + +- Java 17+ +- Maven 3.6.3+ +- Node.js 20+ (for CDS build tooling) +- `@sap/cds-dk` 9+ (CDS build tooling) +- An [SAP AI Core](https://help.sap.com/docs/sap-ai-core) service binding (for production) + +### Dependencies to add + +pom.xml: +```xml + + com.sap.cds + cds-feature-ai + ${revision} + +``` + +package.json: +```json +"dependencies": { + "@cap-js/ai": "1.0.0" +} +``` + +### AI Core service binding + +To use the plugin in production scenarios you need an [SAP AI Core](https://help.sap.com/docs/sap-ai-core) service binding. +The plugin will automatically create resource groups per tenant labeled with `ext.ai.sap.com/CDS_TENANT_ID` in multi-tenancy scenarios and create an RPT-1 deployment in each for the recommendations feature. For multitenancy, set `cds.multitenancy.enabled=true` (or the environment variable `CDS_MULTITENANCY_ENABLED=true`). + +In single-tenant setups the plugin uses the 'default' resource group and creates an RPT-1 deployment as well if none exists. + +For single-tenant deployments you can change the resource group as follow in the `application.yaml`: + +```yaml +# application.yaml +cds: + requires: + AICore: + resourceGroup: CUSTOM_RESOURCE_GROUP +``` + +For Cloud Foundry apps an example config could look like in [samples/bookshop/mta.yaml](samples/bookshop/mta.yaml). + +For local development without an AI Core binding, the plugin falls back to a `MockAIClient` that returns random predictions from the existing context rows. + + +## Test the plugin locally + +In `samples/bookshop` you can find a complete CAP Java bookshop that demonstrates the plugin: + +```bash +mvn clean install +cd samples/bookshop +mvn spring-boot:run +``` + +### Local Testing +To execute local tests, simply run: + +```bash +mvn test +``` + +or for a full build including tests: + +```bash +mvn clean install +``` + +To run the integration test [AICoreSetupHandlerTest](https://github.com/cap-java/cds-feature-ai/blob/main/srv/src/test/java/com/sap/cds/feature/ai/client/setup/AICoreSetupHandlerTest.java), you need a [SAP AI Core](https://help.sap.com/docs/sap-ai-core) service binding. +Then, first run `cds bind -to ` in order to make the service binding available locally. This command will use your currently targeted Cloud Foundry space, for more info consult the cds bind documentation at https://cap.cloud.sap/docs/tools/cds-bind. + +Then execute the test with `cds bind --exec mvn test`. + +If there is no binding, the integration test is skipped automatically. + +## Support, Feedback, Contributing + +This project is open to feature requests/suggestions, bug reports etc. via [GitHub issues](https://github.com/cap-java/cds-feature-ai/issues). Contribution and feedback are encouraged and always welcome. For more information about how to contribute, the project structure, as well as additional contribution information, see our [Contribution Guidelines](CONTRIBUTING.md). + +## Security / Disclosure + +If you find any bug that may be a security problem, please follow our instructions at [in our security policy](https://github.com/cap-java/cds-feature-ai/security/policy) on how to report it. Please do not create GitHub issues for security-related doubts or problems. + +## Code of Conduct + +We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone. By participating in this project, you agree to abide by its [Code of Conduct](https://github.com/cap-java/.github/blob/main/CODE_OF_CONDUCT.md) at all times. + +## Licensing + +Copyright 2026 SAP SE or an SAP affiliate company and cds-feature-ai contributors. Please see our [LICENSE](LICENSE) for copyright and license information. Detailed information including third-party components and their licensing/copyright information is available via the REUSE tool. + diff --git a/REUSE.toml b/REUSE.toml new file mode 100644 index 0000000..576b23e --- /dev/null +++ b/REUSE.toml @@ -0,0 +1,11 @@ +version = 1 +SPDX-PackageName = "cds-feature-ai" +SPDX-PackageSupplier = "ospo@sap.com" +SPDX-PackageDownloadLocation = "https://github.com/cap-java/cds-feature-ai" +SPDX-PackageComment = "The code in this project may include calls to APIs (\"API Calls\") of\n SAP or third-party products or services developed outside of this project\n (\"External Products\").\n \"APIs\" means application programming interfaces, as well as their respective\n specifications and implementing code that allows software to communicate with\n other software.\n API Calls to External Products are not licensed under the open source license\n that governs this project. The use of such API Calls and related External\n Products are subject to applicable additional agreements with the relevant\n provider of the External Products. In no event shall the open source license\n that governs this project grant any rights in or to any External Products,or\n alter, expand or supersede any terms of the applicable additional agreements.\n If you have a valid license agreement with SAP for the use of a particular SAP\n External Product, then you may make use of any API Calls included in this\n project's code for that SAP External Product, subject to the terms of such\n license agreement. If you do not have a valid license agreement for the use of\n a particular SAP External Product, then you may only make use of any API Calls\n in this project for that SAP External Product for your internal, non-productive\n and non-commercial test and evaluation of such API Calls. Nothing herein grants\n you any rights to use or access any SAP External Product, or provide any third\n parties the right to use of access any SAP External Product, through API Calls." + +[[annotations]] +path = "**" +precedence = "aggregate" +SPDX-FileCopyrightText = "2026 SAP SE or an SAP affiliate company and @cap-java/cds-feature-ai contributors" +SPDX-License-Identifier = "Apache-2.0" diff --git a/gh_ruleset.json b/gh_ruleset.json new file mode 100644 index 0000000..6f88065 --- /dev/null +++ b/gh_ruleset.json @@ -0,0 +1,59 @@ +{ + "name": "main", + "target": "branch", + "source_type": "Repository", + "source": "Repository", + "enforcement": "active", + "conditions": { + "ref_name": { + "exclude": [], + "include": ["~DEFAULT_BRANCH"] + } + }, + "rules": [ + { + "type": "deletion" + }, + { + "type": "non_fast_forward" + }, + { + "type": "required_status_checks", + "parameters": { + "strict_required_status_checks_policy": false, + "do_not_enforce_on_create": false, + "required_status_checks": [ + { + "context": "build / build-and-run", + "integration_id": 15368 + }, + { + "context": "lint", + "integration_id": 15368 + }, + { + "context": "test (20.x)", + "integration_id": 15368 + }, + { + "context": "test (22.x)", + "integration_id": 15368 + } + ] + } + }, + { + "type": "pull_request", + "parameters": { + "required_approving_review_count": 2, + "dismiss_stale_reviews_on_push": false, + "require_code_owner_review": false, + "require_last_push_approval": false, + "required_review_thread_resolution": true, + "automatic_copilot_code_review_enabled": false, + "allowed_merge_methods": ["squash"] + } + } + ], + "bypass_actors": [] +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..0dac673 --- /dev/null +++ b/package.json @@ -0,0 +1,16 @@ +{ + "name": "cds-feature-ai", + "version": "1.0.0-SNAPSHOT", + "description": "CAP Java AI Features Plugin", + "license": "Apache-2.0", + "type": "module", + "scripts": { + "lint": "cds lint", + "prettier:check": "cds format --check" + }, + "devDependencies": { + "@sap/cds-dk": "^9.3.2", + "@sap/eslint-plugin-cds": "^4", + "eslint": "^10" + } +} diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..ca0e387 --- /dev/null +++ b/pom.xml @@ -0,0 +1,372 @@ + + + 4.0.0 + + com.sap.cds + cds-feature-ai-root + ${revision} + pom + + CDS Feature for AI - Root + This artifact is a CAP Java plugin that provides smart recommendations using the SAP RPT-1 model. + + + SAP SE + https://www.sap.com + + + + + The Apache Software License, Version 2.0 + https://www.apache.org/licenses/LICENSE-2.0.txt + repo + + + + + + SAP SE + https://www.sap.com + + + + + srv + + + + + central + MavenCentral + https://central.sonatype.com + + + artifactory + Artifactory_DMZ-snapshots + https://common.repositories.cloud.sap/artifactory/cap-java + + + + + + 1.0.0-SNAPSHOT + + + 17 + 4.6.1 + 3.5.6 + 1.18.0 + 0.8.14 + 6.0.3 + 5.23.0 + 3.5.0 + 3.15.0 + 3.4.1 + 3.1.4 + 3.12.0 + 3.5.5 + 3.5.5 + 3.28.0 + 3.6.2 + 1.7.3 + 5.28.0 + 4.9.8.3 + 1.23.0 + + + true + + + + + + com.sap.cds + cds-services-bom + ${cds.services.version} + pom + import + + + + com.sap.cloud.sdk + sdk-bom + ${sap.cloud.sdk.version} + pom + import + + + + org.junit + junit-bom + ${junit.version} + pom + import + + + + org.mockito + mockito-bom + ${mockito.version} + pom + import + + + + com.sap.cds + cds-feature-ai + ${revision} + + + + + + + com.sap.cds + cds-services-api + + + + org.junit.jupiter + junit-jupiter + test + + + + org.assertj + assertj-core + 3.27.7 + test + + + + org.mockito + mockito-core + test + + + + org.mockito + mockito-junit-jupiter + test + + + + + + + + com.sap.cds + cds-maven-plugin + ${cds.services.version} + + + org.jacoco + jacoco-maven-plugin + ${jacoco.version} + + + maven-clean-plugin + ${maven.clean.plugin.version} + + + maven-compiler-plugin + ${maven.compiler.plugin.version} + + ${java.version} + UTF-8 + + + + maven-source-plugin + ${maven.source.plugin.version} + + + maven-deploy-plugin + ${maven.deploy.plugin.version} + + + maven-javadoc-plugin + ${maven.javadoc.plugin.version} + + + maven-surefire-plugin + ${maven.surefire.plugin.version} + + + maven-failsafe-plugin + ${maven.failsafe.plugin.version} + + + maven-pmd-plugin + ${maven.pmd.plugin.version} + + + maven-enforcer-plugin + ${maven.enforcer.plugin.version} + + + org.codehaus.mojo + flatten-maven-plugin + ${maven.flatten.plugin.version} + + + org.pitest + pitest-maven + ${pitest.maven.plugin.version} + + + com.github.spotbugs + spotbugs-maven-plugin + ${spotbugs.maven.plugin.version} + + + + + + + + org.codehaus.mojo + flatten-maven-plugin + + true + resolveCiFriendliesOnly + + + + flatten + + flatten + + process-resources + + + flatten.clean + + clean + + clean + + + + + + com.github.spotbugs + spotbugs-maven-plugin + + Max + true + /src/main/resources/spotbugs-exclusion-filter.xml + ${project.build.directory} + true + + + + spotbugs-error + + check + + process-test-classes + + + + + + maven-pmd-plugin + + ${java.version} + 5 + ${project.build.directory} + true + true + false + false + + + /rulesets/java/maven-pmd-plugin-default.xml + + + ${project.basedir}/src/gen/java + + + **/*Test** + + + + + + com.sap.cloud.sdk.quality + pmd-rules + 3.78.0 + + + + + pmd-error + + check + cpd-check + + process-test-classes + + + + + + maven-enforcer-plugin + + + no-duplicate-declared-dependencies + + enforce + + + + + + 3.6.3 + + + ${java.version} + + + + + + + + + + com.diffplug.spotless + spotless-maven-plugin + 3.4.0 + + + + + + + /* + * © $YEAR SAP SE or an SAP affiliate company and cds-feature-ai contributors. + */ + + + + + pom.xml + + + + + + + + check + + process-sources + + + + + + + diff --git a/samples/bookshop/.cdsrc.json b/samples/bookshop/.cdsrc.json new file mode 100644 index 0000000..1cb5db6 --- /dev/null +++ b/samples/bookshop/.cdsrc.json @@ -0,0 +1,8 @@ +{ + "requires": { + "db": "hana", + "[production]": { + "auth": "xsuaa" + } + } +} diff --git a/samples/bookshop/.gitignore b/samples/bookshop/.gitignore new file mode 100644 index 0000000..2ecc68d --- /dev/null +++ b/samples/bookshop/.gitignore @@ -0,0 +1,34 @@ +**/gen/ +**/edmx/ +*.db +*.sqlite +*.sqlite-wal +*.sqlite-shm +schema*.sql +default-env.json + +**/bin/ +**/target/ +.flattened-pom.xml +.classpath +.project +.settings + +**/node/ +**/node_modules/ + +**/.mta/ +*.mtar + +*.log* +gc_history* +hs_err* +*.tgz +*.iml + +.vscode +.idea +.reloadtrigger + +# added by cds +.cdsrc-private.json diff --git a/samples/bookshop/app/_i18n/i18n.properties b/samples/bookshop/app/_i18n/i18n.properties new file mode 100644 index 0000000..7326bbb --- /dev/null +++ b/samples/bookshop/app/_i18n/i18n.properties @@ -0,0 +1,15 @@ +Books = Books +Book = Book +ID = ID +Title = Title +Author = Author +Authors = Authors +AuthorID = Author ID +AuthorName = Author Name +Name = Name +Age = Age +Stock = Stock +Order = Order +Orders = Orders +Price = Price +Genre = Genre \ No newline at end of file diff --git a/samples/bookshop/app/_i18n/i18n_de.properties b/samples/bookshop/app/_i18n/i18n_de.properties new file mode 100644 index 0000000..cb712c1 --- /dev/null +++ b/samples/bookshop/app/_i18n/i18n_de.properties @@ -0,0 +1,15 @@ +Books = Bücher +Book = Buch +ID = ID +Title = Titel +Author = Autor +Authors = Autoren +AuthorID = ID des Autors +AuthorName = Name des Autors +Name = Name +Age = Alter +Stock = Bestand +Order = Bestellung +Orders = Bestellungen +Price = Preis +Genre = Genre \ No newline at end of file diff --git a/samples/bookshop/app/admin-books/fiori-service.cds b/samples/bookshop/app/admin-books/fiori-service.cds new file mode 100644 index 0000000..34ffe51 --- /dev/null +++ b/samples/bookshop/app/admin-books/fiori-service.cds @@ -0,0 +1,79 @@ +using {AdminService} from '../../srv/admin-service.cds'; + +//////////////////////////////////////////////////////////////////////////// +// +// Books Object Page +// +annotate AdminService.Books with @(UI: { + HeaderInfo : { + TypeName : '{i18n>Book}', + TypeNamePlural: '{i18n>Books}', + Title : {Value: title}, + Description : {Value: author.name} + }, + Facets : [ + { + $Type : 'UI.ReferenceFacet', + Label : '{i18n>General}', + Target: '@UI.FieldGroup#General' + }, + { + $Type : 'UI.ReferenceFacet', + Label : '{i18n>Details}', + Target: '@UI.FieldGroup#Details' + }, + { + $Type : 'UI.ReferenceFacet', + Label : '{i18n>Admin}', + Target: '@UI.FieldGroup#Admin' + } + ], + FieldGroup #General: {Data: [ + {Value: title}, + {Value: author_ID}, + {Value: genre_ID}, + {Value: descr} + ]}, + FieldGroup #Details: {Data: [ + {Value: stock}, + {Value: price}, + {Value: currency_code} + ]}, + FieldGroup #Admin : {Data: [ + {Value: createdBy}, + {Value: createdAt}, + {Value: modifiedBy}, + {Value: modifiedAt} + ]} +}); + + +//////////////////////////////////////////////////////////// +// +// Draft for Localized Data +// +annotate sap.capire.bookshop.Books with @fiori.draft.enabled; +annotate AdminService.Books with @odata.draft.enabled; + +// In addition we need to expose Languages through AdminService as a target for ValueList +using {sap} from '@sap/cds/common'; + +extend service AdminService { + @readonly + entity Languages as projection on sap.common.Languages; +} + +// Workaround for Fiori popup for asking user to enter a new UUID on Create +annotate AdminService.Books with { + ID @Core.Computed; +} + +// Show Genre as drop down, not a dialog +annotate AdminService.Books with { + genre @Common.ValueListWithFixedValues; +} + +// Show currency also as drop down, not a dialog +annotate AdminService.Books with { + currency @Common.ValueListWithFixedValues; +} diff --git a/samples/bookshop/app/admin-books/webapp/Component.js b/samples/bookshop/app/admin-books/webapp/Component.js new file mode 100644 index 0000000..e98677e --- /dev/null +++ b/samples/bookshop/app/admin-books/webapp/Component.js @@ -0,0 +1,8 @@ +sap.ui.define(["sap/fe/core/AppComponent"], function (AppComponent) { + "use strict"; + return AppComponent.extend("books.Component", { + metadata: { manifest: "json" } + }); +}); + +/* eslint no-undef:0 */ diff --git a/samples/bookshop/app/admin-books/webapp/i18n/i18n.properties b/samples/bookshop/app/admin-books/webapp/i18n/i18n.properties new file mode 100644 index 0000000..9a23ee4 --- /dev/null +++ b/samples/bookshop/app/admin-books/webapp/i18n/i18n.properties @@ -0,0 +1,3 @@ +appTitle=Manage Books +appSubTitle=Manage bookshop inventory +appDescription=Manage your bookshop inventory with ease. diff --git a/samples/bookshop/app/admin-books/webapp/i18n/i18n_de.properties b/samples/bookshop/app/admin-books/webapp/i18n/i18n_de.properties new file mode 100644 index 0000000..01d56a2 --- /dev/null +++ b/samples/bookshop/app/admin-books/webapp/i18n/i18n_de.properties @@ -0,0 +1,3 @@ +appTitle=Bücher verwalten +appSubTitle=Verwalten Sie den Bestand der Buchhandlungen +appDescription=Verwalten Sie den Bestand Ihrer Buchhandlung ganz einfach. diff --git a/samples/bookshop/app/admin-books/webapp/manifest.json b/samples/bookshop/app/admin-books/webapp/manifest.json new file mode 100644 index 0000000..4bcc54c --- /dev/null +++ b/samples/bookshop/app/admin-books/webapp/manifest.json @@ -0,0 +1,145 @@ +{ + "_version": "1.49.0", + "sap.app": { + "applicationVersion": { + "version": "1.0.0" + }, + "id": "bookshop.admin-books", + "type": "application", + "title": "{{appTitle}}", + "description": "{{appDescription}}", + "i18n": "i18n/i18n.properties", + "dataSources": { + "AdminService": { + "uri": "/odata/v4/AdminService/", + "type": "OData", + "settings": { + "odataVersion": "4.0" + } + } + }, + "crossNavigation": { + "inbounds": { + "intent-Books-manage": { + "signature": { + "parameters": {}, + "additionalParameters": "allowed" + }, + "semanticObject": "Books", + "action": "manage" + } + } + } + }, + "sap.ui": { + "technology": "UI5", + "fullWidth": false, + "deviceTypes": { + "desktop": true, + "tablet": true, + "phone": true + } + }, + "sap.ui5": { + "dependencies": { + "minUI5Version": "1.115.1", + "libs": { + "sap.fe.templates": {} + } + }, + "models": { + "i18n": { + "type": "sap.ui.model.resource.ResourceModel", + "uri": "i18n/i18n.properties" + }, + "": { + "dataSource": "AdminService", + "settings": { + "operationMode": "Server", + "autoExpandSelect": true, + "earlyRequests": true, + "groupProperties": { + "default": { + "submit": "Auto" + } + } + } + } + }, + "routing": { + "routes": [ + { + "pattern": ":?query:", + "name": "BooksList", + "target": "BooksList" + }, + { + "pattern": "Books({key}):?query:", + "name": "BooksDetails", + "target": "BooksDetails" + }, + { + "pattern": "Books({key}/author({key2}):?query:", + "name": "AuthorsDetails", + "target": "AuthorsDetails" + } + ], + "targets": { + "BooksList": { + "type": "Component", + "id": "BooksList", + "name": "sap.fe.templates.ListReport", + "options": { + "settings": { + "contextPath": "/Books", + "initialLoad": true, + "navigation": { + "Books": { + "detail": { + "route": "BooksDetails" + } + } + } + } + } + }, + "BooksDetails": { + "type": "Component", + "id": "BooksDetailsList", + "name": "sap.fe.templates.ObjectPage", + "options": { + "settings": { + "contextPath": "/Books", + "editableHeaderContent": false, + "navigation": { + "Authors": { + "detail": { + "route": "AuthorsDetails" + } + } + } + } + } + }, + "AuthorsDetails": { + "type": "Component", + "id": "AuthorsDetailsList", + "name": "sap.fe.templates.ObjectPage", + "options": { + "settings": { + "contextPath": "/Authors" + } + } + } + } + }, + "contentDensities": { + "compact": true, + "cozy": true + } + }, + "sap.fiori": { + "registrationIds": [], + "archeType": "transactional" + } +} diff --git a/samples/bookshop/app/appconfig/fioriSandboxConfig.json b/samples/bookshop/app/appconfig/fioriSandboxConfig.json new file mode 100644 index 0000000..ff2ac49 --- /dev/null +++ b/samples/bookshop/app/appconfig/fioriSandboxConfig.json @@ -0,0 +1,95 @@ +{ + "services": { + "LaunchPage": { + "adapter": { + "config": { + "catalogs": [], + "groups": [ + { + "id": "Bookshop", + "title": "Bookshop", + "isPreset": true, + "isVisible": true, + "isGroupLocked": false, + "tiles": [ + { + "id": "BrowseBooks", + "tileType": "sap.ushell.ui.tile.StaticTile", + "properties": { + "title": "Browse Books", + "targetURL": "#Books-display" + } + } + ] + }, + { + "id": "Administration", + "title": "Administration", + "isPreset": true, + "isVisible": true, + "isGroupLocked": false, + "tiles": [ + { + "id": "ManageBooks", + "tileType": "sap.ushell.ui.tile.StaticTile", + "properties": { + "title": "Manage Books", + "targetURL": "#Books-manage" + } + } + ] + } + ] + } + } + }, + "NavTargetResolution": { + "config": { + "enableClientSideTargetResolution": true + } + }, + "ClientSideTargetResolution": { + "adapter": { + "config": { + "inbounds": { + "BrowseBooks": { + "semanticObject": "Books", + "action": "display", + "title": "Browse Books", + "signature": { + "parameters": { + "Books.ID": { + "renameTo": "ID" + }, + "Authors.books.ID": { + "renameTo": "ID" + } + }, + "additionalParameters": "ignored" + }, + "resolutionResult": { + "applicationType": "SAPUI5", + "additionalInformation": "SAPUI5.Component=bookshop", + "url": "browse/webapp" + } + }, + "ManageBooks": { + "semanticObject": "Books", + "action": "manage", + "title": "Manage Books", + "signature": { + "parameters": {}, + "additionalParameters": "allowed" + }, + "resolutionResult": { + "applicationType": "SAPUI5", + "additionalInformation": "SAPUI5.Component=books", + "url": "admin-books/webapp" + } + } + } + } + } + } + } +} diff --git a/samples/bookshop/app/browse/fiori-service.cds b/samples/bookshop/app/browse/fiori-service.cds new file mode 100644 index 0000000..666781d --- /dev/null +++ b/samples/bookshop/app/browse/fiori-service.cds @@ -0,0 +1,58 @@ +using {CatalogService} from '../../srv/cat-service.cds'; + +//////////////////////////////////////////////////////////////////////////// +// +// Books Object Page +// +annotate CatalogService.Books with @(UI: { + HeaderInfo : { + TypeName : '{i18n>Book}', + TypeNamePlural: '{i18n>Books}', + Title : {Value: title}, + Description : {Value: author} + }, + Facets : [{ + $Type : 'UI.CollectionFacet', + Label : '{i18n>Details}', + Facets: [ + { + $Type : 'UI.ReferenceFacet', + Target: '@UI.FieldGroup#Descr' + }, + { + $Type : 'UI.ReferenceFacet', + Target: '@UI.FieldGroup#Price' + } + ] + }], + FieldGroup #Descr : {Data: [{Value: descr, ![@UI.MultiLineText]: true}]}, + FieldGroup #Price: {Data: [ + {Value: price}, + {Value: currency_code} + ]} +}); + +//////////////////////////////////////////////////////////////////////////// +// +// Books List Page +// +annotate CatalogService.Books with @(UI: { + SelectionFields: [ + ID, + price, + currency_code + ], + LineItem : [ + { + Value: ID, + Label: '{i18n>Title}' + }, + { + Value: author, + Label: '{i18n>Author}' + }, + {Value: genre.name}, + {Value: price}, + {Value: currency_code} + ] +}); diff --git a/samples/bookshop/app/browse/webapp/Component.js b/samples/bookshop/app/browse/webapp/Component.js new file mode 100644 index 0000000..4020679 --- /dev/null +++ b/samples/bookshop/app/browse/webapp/Component.js @@ -0,0 +1,7 @@ +sap.ui.define(["sap/fe/core/AppComponent"], function(AppComponent) { + "use strict"; + return AppComponent.extend("bookshop.Component", { + metadata: { manifest: "json" } + }); +}); +/* eslint no-undef:0 */ diff --git a/samples/bookshop/app/browse/webapp/i18n/i18n.properties b/samples/bookshop/app/browse/webapp/i18n/i18n.properties new file mode 100644 index 0000000..21436e8 --- /dev/null +++ b/samples/bookshop/app/browse/webapp/i18n/i18n.properties @@ -0,0 +1,3 @@ +appTitle=Browse Books +appSubTitle=Find all your favorite books +appDescription=This application lets you find the next books you want to read. diff --git a/samples/bookshop/app/browse/webapp/i18n/i18n_de.properties b/samples/bookshop/app/browse/webapp/i18n/i18n_de.properties new file mode 100644 index 0000000..ea86c3f --- /dev/null +++ b/samples/bookshop/app/browse/webapp/i18n/i18n_de.properties @@ -0,0 +1,3 @@ +appTitle=Bücher anschauen +appSubTitle=Finden sie ihre nächste Lektüre +appDescription=Finden Sie die nachsten Bücher, die Sie lesen möchten. diff --git a/samples/bookshop/app/browse/webapp/manifest.json b/samples/bookshop/app/browse/webapp/manifest.json new file mode 100644 index 0000000..cd4b1c3 --- /dev/null +++ b/samples/bookshop/app/browse/webapp/manifest.json @@ -0,0 +1,137 @@ +{ + "_version": "1.49.0", + "sap.app": { + "id": "bookshop.browse", + "applicationVersion": { + "version": "1.0.0" + }, + "type": "application", + "title": "{{appTitle}}", + "description": "{{appDescription}}", + "i18n": "i18n/i18n.properties", + "dataSources": { + "CatalogService": { + "uri": "/odata/v4/CatalogService/", + "type": "OData", + "settings": { + "odataVersion": "4.0" + } + } + }, + "crossNavigation": { + "inbounds": { + "intent1": { + "signature": { + "parameters": { + "Books.ID": { + "renameTo": "ID" + }, + "Authors.books.ID": { + "renameTo": "ID" + } + }, + "additionalParameters": "ignored" + }, + "semanticObject": "Books", + "action": "display", + "title": "{{appTitle}}", + "subTitle": "{{appSubTitle}}", + "icon": "sap-icon://course-book", + "indicatorDataSource": { + "dataSource": "CatalogService", + "path": "Books/$count", + "refresh": 1800 + } + } + } + } + }, + "sap.ui": { + "technology": "UI5", + "fullWidth": false, + "deviceTypes": { + "desktop": true, + "tablet": true, + "phone": true + } + }, + "sap.ui5": { + "dependencies": { + "minUI5Version": "1.115.1", + "libs": { + "sap.fe.templates": {} + } + }, + "models": { + "i18n": { + "type": "sap.ui.model.resource.ResourceModel", + "uri": "i18n/i18n.properties" + }, + "": { + "dataSource": "CatalogService", + "settings": { + "operationMode": "Server", + "autoExpandSelect": true, + "earlyRequests": true, + "groupProperties": { + "default": { + "submit": "Auto" + } + } + } + } + }, + "routing": { + "routes": [ + { + "pattern": ":?query:", + "name": "BooksList", + "target": "BooksList" + }, + { + "pattern": "Books({key}):?query:", + "name": "BooksDetails", + "target": "BooksDetails" + } + ], + "targets": { + "BooksList": { + "type": "Component", + "id": "BooksList", + "name": "sap.fe.templates.ListReport", + "options": { + "settings": { + "contextPath": "/Books", + "initialLoad": true, + "navigation": { + "Books": { + "detail": { + "route": "BooksDetails" + } + } + } + } + } + }, + "BooksDetails": { + "type": "Component", + "id": "BooksDetailsList", + "name": "sap.fe.templates.ObjectPage", + "options": { + "settings": { + "contextPath": "/Books" + } + } + } + } + }, + "contentDensities": { + "compact": true, + "cozy": true + } + }, + "sap.fiori": { + "registrationIds": [], + "archeType": "transactional" + } +} diff --git a/samples/bookshop/app/common.cds b/samples/bookshop/app/common.cds new file mode 100644 index 0000000..2afc6e0 --- /dev/null +++ b/samples/bookshop/app/common.cds @@ -0,0 +1,263 @@ +/* + Common Annotations shared by all apps +*/ + +using {sap.capire.bookshop as my} from '../db/schema'; +using { + sap.common, + sap.common.Currencies +} from '@sap/cds/common'; + +//////////////////////////////////////////////////////////////////////////// +// +// Books Lists +// +annotate my.Books with @( + Common.SemanticKey: [ID], + UI : { + Identification : [{Value: title}], + SelectionFields: [ + ID, + author_ID, + price, + currency_code + ], + LineItem : [ + { + Value: ID, + Label: '{i18n>Title}' + }, + { + Value: author.ID, + Label: '{i18n>Author}' + }, + {Value: genre.name}, + {Value: stock}, + {Value: price} + ] + } +) { + ID @Common : { + SemanticObject : 'Books', + Text : title, + TextArrangement: #TextOnly + }; + author @ValueList.entity: 'Authors'; +}; + +annotate Currencies with { + symbol @Common.Label: '{i18n>Currency}'; +} + +//////////////////////////////////////////////////////////////////////////// +// +// Books Elements +// +annotate my.Books with { + ID @title: '{i18n>ID}'; + title @title: '{i18n>Title}'; + genre @title: '{i18n>Genre}' @Common : { + Text : genre.name, + TextArrangement: #TextOnly + }; + author @title: '{i18n>Author}' @Common : { + Text : author.name, + TextArrangement: #TextOnly + }; + price @title: '{i18n>Price}'; + currency @title: '{i18n>Currency}'; + stock @title: '{i18n>Stock}'; + descr @title: '{i18n>Description}' @UI.MultiLineText; +} + +//////////////////////////////////////////////////////////////////////////// +// +// Genres List +// +annotate my.Genres with @( + Common.SemanticKey: [name], + UI : { + SelectionFields: [name], + LineItem : [ + {Value: name}, + { + Value: parent.name, + Label: 'Main Genre' + } + ] + } +); + +annotate my.Genres with { + ID @Common.Text: name @Common.TextArrangement: #TextOnly; +} + +//////////////////////////////////////////////////////////////////////////// +// +// Genre Details +// +annotate my.Genres with @(UI: { + Identification: [{Value: name}], + HeaderInfo : { + TypeName : '{i18n>Genre}', + TypeNamePlural: '{i18n>Genres}', + Title : {Value: name}, + Description : {Value: ID} + }, + Facets : [{ + $Type : 'UI.ReferenceFacet', + Label : '{i18n>SubGenres}', + Target: 'children/@UI.LineItem' + }] +}); + +//////////////////////////////////////////////////////////////////////////// +// +// Genres Elements +// +annotate my.Genres with { + ID @title: '{i18n>ID}'; + name @title: '{i18n>Genre}'; +} + +//////////////////////////////////////////////////////////////////////////// +// +// Authors List +// +annotate my.Authors with @( + Common.SemanticKey: [ID], + UI : { + Identification : [{Value: name}], + SelectionFields: [name], + LineItem : [ + {Value: ID}, + {Value: dateOfBirth}, + {Value: dateOfDeath}, + {Value: placeOfBirth}, + {Value: placeOfDeath} + ] + } +) { + ID @Common: { + SemanticObject : 'Authors', + Text : name, + TextArrangement: #TextOnly + }; +}; + +//////////////////////////////////////////////////////////////////////////// +// +// Author Details +// +annotate my.Authors with @(UI: { + HeaderInfo: { + TypeName : '{i18n>Author}', + TypeNamePlural: '{i18n>Authors}', + Title : {Value: name}, + Description : {Value: dateOfBirth} + }, + Facets : [{ + $Type : 'UI.ReferenceFacet', + Target: 'books/@UI.LineItem' + }] +}); + + +//////////////////////////////////////////////////////////////////////////// +// +// Authors Elements +// +annotate my.Authors with { + ID @title: '{i18n>ID}'; + name @title: '{i18n>Name}'; + dateOfBirth @title: '{i18n>DateOfBirth}'; + dateOfDeath @title: '{i18n>DateOfDeath}'; + placeOfBirth @title: '{i18n>PlaceOfBirth}'; + placeOfDeath @title: '{i18n>PlaceOfDeath}'; +} + +//////////////////////////////////////////////////////////////////////////// +// +// Languages List +// +annotate common.Languages with @( + Common.SemanticKey: [code], + Identification : [{Value: code}], + UI : { + SelectionFields: [ + name, + descr + ], + LineItem : [ + {Value: code}, + {Value: name} + ] + } +); + +//////////////////////////////////////////////////////////////////////////// +// +// Language Details +// +annotate common.Languages with @(UI: { + HeaderInfo : { + TypeName : '{i18n>Language}', + TypeNamePlural: '{i18n>Languages}', + Title : {Value: name}, + Description : {Value: descr} + }, + Facets : [{ + $Type : 'UI.ReferenceFacet', + Label : '{i18n>Details}', + Target: '@UI.FieldGroup#Details' + }], + FieldGroup #Details: {Data: [ + {Value: code}, + {Value: name}, + {Value: descr} + ]} +}); + +//////////////////////////////////////////////////////////////////////////// +// +// Currencies List +// +annotate common.Currencies with @( + Common.SemanticKey: [code], + Identification : [{Value: code}], + UI : { + SelectionFields: [ + name, + descr + ], + LineItem : [ + {Value: descr}, + {Value: symbol}, + {Value: code} + ] + } +); + +//////////////////////////////////////////////////////////////////////////// +// +// Currency Details +// +annotate common.Currencies with @(UI: { + HeaderInfo : { + TypeName : '{i18n>Currency}', + TypeNamePlural: '{i18n>Currencies}', + Title : {Value: descr}, + Description : {Value: code} + }, + Facets : [{ + $Type : 'UI.ReferenceFacet', + Label : '{i18n>Details}', + Target: '@UI.FieldGroup#Details' + }], + FieldGroup #Details: {Data: [ + {Value: name}, + {Value: symbol}, + {Value: code}, + {Value: descr} + ]} +}); diff --git a/samples/bookshop/app/index.html b/samples/bookshop/app/index.html new file mode 100644 index 0000000..70f6315 --- /dev/null +++ b/samples/bookshop/app/index.html @@ -0,0 +1,32 @@ + + + + + + + + Bookshop + + + + + + + + + + diff --git a/samples/bookshop/app/package.json b/samples/bookshop/app/package.json new file mode 100644 index 0000000..73938f8 --- /dev/null +++ b/samples/bookshop/app/package.json @@ -0,0 +1,11 @@ +{ + "name": "bookshop-app", + "version": "1.0.0", + "description": "Bookshop Approuter", + "scripts": { + "start": "node node_modules/@sap/approuter/approuter.js" + }, + "dependencies": { + "@sap/approuter": "^16.0.0" + } +} diff --git a/samples/bookshop/app/services.cds b/samples/bookshop/app/services.cds new file mode 100644 index 0000000..87e7b31 --- /dev/null +++ b/samples/bookshop/app/services.cds @@ -0,0 +1,6 @@ +/* + This model controls what gets served to Fiori frontends... +*/ +using from './common'; +using from './browse/fiori-service'; +using from './admin-books/fiori-service'; diff --git a/samples/bookshop/app/xs-app.json b/samples/bookshop/app/xs-app.json new file mode 100644 index 0000000..5509e99 --- /dev/null +++ b/samples/bookshop/app/xs-app.json @@ -0,0 +1,19 @@ +{ + "welcomeFile": "/index.html", + "authenticationMethod": "route", + "routes": [ + { + "source": "^/odata/(.*)$", + "target": "/odata/$1", + "destination": "srv-api", + "authenticationType": "xsuaa", + "csrfProtection": false + }, + { + "source": "^/(.*)$", + "target": "$1", + "localDir": ".", + "authenticationType": "xsuaa" + } + ] +} diff --git a/samples/bookshop/db/data/sap-common-Currencies.csv b/samples/bookshop/db/data/sap-common-Currencies.csv new file mode 100644 index 0000000..71ec0af --- /dev/null +++ b/samples/bookshop/db/data/sap-common-Currencies.csv @@ -0,0 +1,204 @@ +code,name,descr,minorUnit +"ADP","Peseta","Andorran Peseta --> (Old --> EUR)",0 +"AED","Dirham","United Arab Emirates Dirham",2 +"AFA","Afghani","Afghani (Old)",0 +"AFN","Afghani","Afghani",2 +"ALL","Lek","Albanian Lek",2 +"AMD","Dram","Armenian Dram",2 +"ANG","W.Ind.Guilder","West Indian Guilder",2 +"AOA","Kwansa","Angolanische Kwanza",2 +"AON","New Kwanza","Angolan New Kwanza (Old)",0 +"AOR","Kwanza Reajust.","Angolan Kwanza Reajustado (Old)",0 +"ARS","Arg. Peso","Argentine Peso",2 +"ATS","Shilling","Austrian Schilling (Old --> EUR)",2 +"AUD","Austr. Dollar","Australian Dollar",2 +"AWG","Aruban Florin","Aruban Florin",2 +"AZM","Manat","Azerbaijani Manat (Old)",2 +"AZN","Manat","Azerbaijani Manat",2 +"BAM","Convert. Mark","Bosnia and Herzegovina Convertible Mark",2 +"BBD","Dollar","Barbados Dollar",2 +"BDT","Taka","Bangladesh Taka",2 +"BEF","Belgian Franc","Belgian Franc (Old --> EUR)",0 +"BGN","Lev","Bulgarian Lev",2 +"BHD","Dinar","Bahraini Dinar",3 +"BIF","Burundi Franc","Burundi Franc",0 +"BMD","Bermudan Dollar","Bermudan Dollar",2 +"BND","Dollar","Brunei Dollar",2 +"BOB","Boliviano","Boliviano",2 +"BRL","Real","Brazilian Real",2 +"BSD","Dollar","Bahaman Dollar",2 +"BTN","Ngultrum","Bhutan Ngultrum",2 +"BWP","Pula","Botswana Pula",2 +"BYB","Belarus. Ruble","Belarusian Ruble (Old)",0 +"BYN","Bela. Ruble N.","Belarusian Ruble (New)",2 +"BYR","Ruble","Belarusian Ruble",2 +"BZD","Dollar","Belize Dollar",2 +"CAD","Canadian Dollar","Canadian Dollar",2 +"CDF","Congolese Franc","Congolese Franc",2 +"CHF","Swiss Franc","Swiss Franc",2 +"CLP","Peso","Chilean Peso",0 +"CNY","Renminbi","Chinese Renminbi",2 +"COP","Peso","Colombian Peso",2 +"CRC","Cost.Rica Colon","Costa Rica Colon",2 +"CSD","Serbian Dinar","Serbian Dinar (Old)",2 +"CUC","Peso Convertib.","Peso Convertible",2 +"CVE","Escudo","Cape Verde Escudo",2 +"CYP","Cyprus Pound","Cyprus Pound (Old --> EUR)",2 +"CZK","Krona","Czech Krona",2 +"DEM","German Mark","German Mark (Old --> EUR)",2 +"DJF","Djibouti Franc","Djibouti Franc",0 +"DKK","Danish Krone","Danish Krone",2 +"DOP","Dominican Peso","Dominican Peso",2 +"DZD","Dinar","Algerian Dinar",2 +"ECS","Sucre","Ecuadorian Sucre (Old --> USD)",0 +"EEK","Krona","Estonian Krone (Old --> EUR)",2 +"EGP","Pound","Egyptian Pound",2 +"ERN","Nakfa","Eritrean Nafka",2 +"ESP","Peseta","Spanish Peseta (Old --> EUR)",0 +"ETB","Birr","Ethiopian Birr",2 +"EUR","Euro","European Euro",2 +"FIM","Finnish markka","Finnish Markka (Old --> EUR)",2 +"FJD","Dollar","Fiji Dollar",2 +"FKP","Falkland Pound","Falkland Pound",2 +"FRF","French Franc","French Franc (Old --> EUR)",2 +"GBP","Pound","British Pound",2 +"GEL","Lari","Georgian Lari",2 +"GHC","Cedi","Ghanaian Cedi (Old)",2 +"GHS","Cedi","Ghanian Cedi",2 +"GIP","Gibraltar Pound","Gibraltar Pound",2 +"GMD","Dalasi","Gambian Dalasi",2 +"GNF","Franc","Guinean Franc",0 +"GRD","Drachma","Greek Drachma (Old --> EUR)",0 +"GTQ","Quetzal","Guatemalan Quetzal",2 +"GWP","Guinea Peso","Guinea Peso (Old --> SHP)",2 +"GYD","Guyana Dollar","Guyana Dollar",2 +"HKD","H.K.Dollar","Hong Kong Dollar",2 +"HNL","Lempira","Honduran Lempira",2 +"HRK","Kuna","Croatian Kuna (Old --> EUR)",2 +"HTG","Gourde","Haitian Gourde",2 +"HUF","Forint","Hungarian Forint",2 +"IDR","Rupiah","Indonesian Rupiah",2 +"IEP","Irish Punt","Irish Punt (Old --> EUR)",2 +"ILS","Scheckel","Israeli Scheckel",2 +"INR","Rupee","Indian Rupee",2 +"IQD","Dinar","Iraqui Dinar",2 +"ISK","Krona","Iceland Krona",0 +"ITL","Lire","Italian Lira (Old --> EUR)",0 +"JMD","Jamaican Dollar","Jamaican Dollar",2 +"JOD","Jordanian Dinar","Jordanian Dinar",3 +"JPY","Yen","Japanese Yen",0 +"KES","Shilling","Kenyan Shilling",2 +"KGS","Som","Kyrgyzstan Som",2 +"KHR","Riel","Cambodian Riel",2 +"KMF","Comoros Franc","Comoros Franc",0 +"KRW","S.Korean Won","South Korean Won",0 +"KWD","Dinar","Kuwaiti Dinar",3 +"KYD","Cayman Dollar","Cayman Dollar",2 +"KZT","Tenge","Kazakstanian Tenge",2 +"LAK","Kip","Laotian Kip",2 +"LBP","Lebanese Pound","Lebanese Pound",2 +"LKR","Sri Lanka Rupee","Sri Lankan Rupee",2 +"LRD","Liberian Dollar","Liberian Dollar",2 +"LSL","Loti","Lesotho Loti",2 +"LTL","Lita","Lithuanian Lita",2 +"LUF","Lux. Franc","Luxembourg Franc (Old --> EUR)",0 +"LVL","Lat","Latvian Lat",2 +"LYD","Libyan Dinar","Libyan Dinar",3 +"MAD","Dirham","Moroccan Dirham",2 +"MDL","Leu","Moldavian Leu",2 +"MGA","Madagasc.Ariary","Madagascan Ariary",2 +"MGF","Madagascan Fr.","Madagascan Franc (Old",0 +"MKD","Maced. Denar","Macedonian Denar",2 +"MMK","Kyat","Myanmar Kyat",2 +"MNT","Tugrik","Mongolian Tugrik",2 +"MOP","Pataca","Macao Pataca",2 +"MRO","Ouguiya","Mauritanian Ouguiya",2 +"MRU","Ouguiya","Mauritanian Ouguiya",2 +"MTL","Lira","Maltese Lira (Old --> EUR)",2 +"MUR","Rupee","Mauritian Rupee",2 +"MVR","Rufiyaa","Maldive Rufiyaa",2 +"MWK","Malawi Kwacha","Malawi Kwacha",2 +"MXN","Peso","Mexican Pesos",2 +"MYR","Ringgit","Malaysian Ringgit",2 +"MZM","Metical","Mozambique Metical (Old)",0 +"MZN","Metical","Mozambique Metical",2 +"NAD","Namibian Dollar","Namibian Dollar",2 +"NGN","Naira","Nigerian Naira",2 +"NIO","Cordoba Oro","Nicaraguan Cordoba Oro",2 +"NLG","Guilder","Dutch Guilder (Old --> EUR)",2 +"NOK","Norwegian Krone","Norwegian Krone",2 +"NPR","Rupee","Nepalese Rupee",2 +"NZD","N.Zeal.Dollars","New Zealand Dollars",2 +"OMR","Omani Rial","Omani Rial",3 +"PAB","Balboa","Panamanian Balboa",2 +"PEN","New Sol","Peruvian New Sol",2 +"PGK","Kina","Papua New Guinea Kina",2 +"PHP","Peso","Philippine Peso",2 +"PKR","Rupee","Pakistani Rupee",2 +"PLN","Zloty","Polish Zloty (new)",2 +"PTE","Escudo","Portuguese Escudo (Old --> EUR)",0 +"PYG","Guarani","Paraguayan Guarani",0 +"QAR","Rial","Qatar Rial",2 +"ROL","Leu (Old)","Romanian Leu (Old)",0 +"RON","Leu","Romanian Leu",2 +"RSD","Serbian Dinar","Serbian Dinar",2 +"RUB","Ruble","Russian Ruble",2 +"RWF","Franc","Rwandan Franc",0 +"SAR","Rial","Saudi Riyal",2 +"SBD","Sol.Isl.Dollar","Solomon Islands Dollar",2 +"SCR","Rupee","Seychelles Rupee",2 +"SDD","Dinar","Sudanese Dinar (Old)",2 +"SDG","Pound","Sudanese Pound",2 +"SDP","Pound","Sudanese Pound (until 1992)",2 +"SEK","Swedish Krona","Swedish Krona",2 +"SGD","Sing.Dollar","Singapore Dollar",2 +"SHP","St.Helena Pound","St.Helena Pound",2 +"SIT","Tolar","Slovenian Tolar (Old --> EUR)",2 +"SKK","Krona","Slovakian Krona (Old --> EUR)",2 +"SLL","Leone","Sierra Leone Leone",2 +"SOS","Shilling","Somalian Shilling",2 +"SRD","Surinam Doillar","Surinam Dollar",2 +"SRG","Surinam Guilder","Surinam Guilder (Old)",2 +"SSP","Pound","South Sudanese Pound",2 +"STD","Dobra","Sao Tome / Principe Dobra",2 +"SVC","Colon","El Salvador Colon",2 +"SZL","Lilangeni","Swaziland Lilangeni",2 +"THB","Baht","Thailand Baht",2 +"TJR","Ruble","Tajikistani Ruble (Old)",0 +"TJS","Somoni","Tajikistani Somoni",2 +"TMM","Manat (Old)","Turkmenistani Manat (Old)",0 +"TMT","Manat","Turkmenistani Manat",2 +"TND","Dinar","Tunisian Dinar",3 +"TOP","Pa'anga","Tongan Pa'anga",2 +"TPE","Timor Escudo","Timor Escudo --> USD",2 +"TRL","Lira (Old)","Turkish Lira (Old)",0 +"TRY","Lira","Turkish Lira",2 +"TTD","T.+ T. Dollar","Trinidad and Tobago Dollar",2 +"TWD","Dollar","New Taiwan Dollar",2 +"TZS","Shilling","Tanzanian Shilling",2 +"UAH","Hryvnia","Ukraine Hryvnia",2 +"UGX","Shilling","Ugandan Shilling",0 +"USD","US Dollar","United States Dollar",2 +"UYU","Peso","Uruguayan Peso",2 +"UZS","Total","Uzbekistan Som",2 +"VEB","Bolivar (Old)","Venezuelan Bolivar (Old)",2 +"VEF","Bolivar","Venezuelan Bolivar",2 +"VES","Bolivar","Venezuelan Bolivar",2 +"VND","Dong","Vietnamese Dong",0 +"VUV","Vatu","Vanuatu Vatu",2 +"WST","Tala","Samoan Tala",2 +"XAF","CFA Franc BEAC","Gabon CFA Franc BEAC",0 +"XCD","Dollar","East Carribean Dollar",2 +"XEU","E.C.U.","European Currency Unit (E.C.U.)",2 +"XOF","CFA Franc BCEAO","Benin CFA Franc BCEAO",0 +"XPF","Fr. Franc (Pac)","French Franc (Pacific Islands)",0 +"YER","Yemeni Ryal","Yemeni Ryal",2 +"YUM","New Dinar","New Yugoslavian Dinar (Old)",2 +"ZAR","Rand","South African Rand",2 +"ZMK","Kwacha","Zambian Kwacha (Old)",2 +"ZMW","Kwacha","Zambian Kwacha (New)",2 +"ZRN","Zaire","Zaire (Old)",2 +"ZWD","Zimbabwe Dollar","Zimbabwean Dollar (Old)",2 +"ZWL","Zimbabwe Dollar","Zimbabwean Dollar (New)",2 +"ZWN","Zimbabwe Dollar","Zimbabwean Dollar (Old)",2 +"ZWR","Zimbabwe Dollar","Zimbabwean Dollar (Old)",2 \ No newline at end of file diff --git a/samples/bookshop/db/data/sap.capire.bookshop-Authors.csv b/samples/bookshop/db/data/sap.capire.bookshop-Authors.csv new file mode 100644 index 0000000..5272ee1 --- /dev/null +++ b/samples/bookshop/db/data/sap.capire.bookshop-Authors.csv @@ -0,0 +1,5 @@ +ID;name;dateOfBirth;placeOfBirth;dateOfDeath;placeOfDeath +10fef92e-975f-4c41-8045-c58e5c27a040;Emily Brontë;1818-07-30;Thornton, Yorkshire;1848-12-19;Haworth, Yorkshire +d4585e0e-ab3b-4424-b2ac-f2bfa785f068;Charlotte Brontë;1818-04-21;Thornton, Yorkshire;1855-03-31;Haworth, Yorkshire +4cf60975-300d-4dbe-8598-57b02e62bae2;Edgar Allen Poe;1809-01-19;Boston, Massachusetts;1849-10-07;Baltimore, Maryland +df9fb9fa-f121-45b5-8be5-8ff7ad5219a2;Richard Carpenter;1929-08-14;King’s Lynn, Norfolk;2012-02-26;Hertfordshire, England diff --git a/samples/bookshop/db/data/sap.capire.bookshop-Books.csv b/samples/bookshop/db/data/sap.capire.bookshop-Books.csv new file mode 100644 index 0000000..5de367b --- /dev/null +++ b/samples/bookshop/db/data/sap.capire.bookshop-Books.csv @@ -0,0 +1,10 @@ +ID;title;descr;author_ID;stock;price;currency_code;genre_ID +b0056977-4cf5-46a2-ab14-6409ee2e0df1;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.";d4585e0e-ab3b-4424-b2ac-f2bfa785f068;11;12.34;GBP;11 +c7641340-a9be-4673-8dad-785a2505f46e;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.";4cf60975-300d-4dbe-8598-57b02e62bae2;333;13.13;USD;16 +7756b725-cefc-43a2-a3c8-0c9104a349b8;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.";4cf60975-300d-4dbe-8598-57b02e62bae2;555;14;USD;16 +a009c640-434a-4542-ac68-51b400c880ea;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.;df9fb9fa-f121-45b5-8be5-8ff7ad5219a2;22;150;JPY;10 +b0056977-4cf5-46a2-ab14-6409ee2e0df2;Jane Eyre II;"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.";d4585e0e-ab3b-4424-b2ac-f2bfa785f068;11;12.34;GBP; +c7641340-a9be-4673-8dad-785a2505f46f;The Raven II;"""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.";4cf60975-300d-4dbe-8598-57b02e62bae2;333;13.13;USD; +7756b725-cefc-43a2-a3c8-0c9104a349b9;Eleonora II;"""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.";4cf60975-300d-4dbe-8598-57b02e62bae2;555;14;USD; +a009c640-434a-4542-ac68-51b400c880eb;Catweazle II;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.;df9fb9fa-f121-45b5-8be5-8ff7ad5219a2;22;150;JPY; +a009c640-434a-4542-ac68-51b400c880ec;Catweazle III;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.;df9fb9fa-f121-45b5-8be5-8ff7ad5219a2;22;150;; diff --git a/samples/bookshop/db/data/sap.capire.bookshop-Genres.csv b/samples/bookshop/db/data/sap.capire.bookshop-Genres.csv new file mode 100644 index 0000000..ebeb7ce --- /dev/null +++ b/samples/bookshop/db/data/sap.capire.bookshop-Genres.csv @@ -0,0 +1,17 @@ +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 + diff --git a/samples/bookshop/db/package.json b/samples/bookshop/db/package.json new file mode 100644 index 0000000..65912cd --- /dev/null +++ b/samples/bookshop/db/package.json @@ -0,0 +1,14 @@ +{ + "name": "deploy", + "dependencies": { + "hdb": "^0", + "@sap/hdi-deploy": "^5" + }, + "engines": { + "node": "^22.0.0" + }, + "scripts": { + "start": "node node_modules/@sap/hdi-deploy/deploy.js --use-hdb --parameter com.sap.hana.di.table/try_fast_table_migration=true", + "build": "npm i && npx cds build .. --for hana --production" + } +} diff --git a/samples/bookshop/db/schema.cds b/samples/bookshop/db/schema.cds new file mode 100644 index 0000000..9358397 --- /dev/null +++ b/samples/bookshop/db/schema.cds @@ -0,0 +1,39 @@ +using { + managed, + cuid, + sap.common.CodeList +} from '@sap/cds/common'; +using { Currency } from '@sap/cds-common-content'; + +namespace sap.capire.bookshop; + +@cds.search: { title , title_embedding } +entity Books : managed, cuid { + @Search.fuzzinessThreshold: 0.5 + @mandatory title : String(111); + descr : String(1111); + author : Association to Authors; + genre : Association to Genres; + stock : Integer; + price : Decimal; + currency : Currency; +} + +entity Authors : managed, cuid { + @mandatory name : String(111); + dateOfBirth : Date; + dateOfDeath : Date; + placeOfBirth : String; + placeOfDeath : String; + books : Association to many Books + on books.author = $self; +} + +/** Hierarchically organized Code List for Genres */ +@cds.odata.valuelist +entity Genres : CodeList { + key ID : Integer; + parent : Association to Genres; + children : Composition of many Genres + on children.parent = $self; +} diff --git a/samples/bookshop/db/src/.hdiconfig b/samples/bookshop/db/src/.hdiconfig new file mode 100644 index 0000000..03673f2 --- /dev/null +++ b/samples/bookshop/db/src/.hdiconfig @@ -0,0 +1,139 @@ +{ + "file_suffixes": { + "csv": { + "plugin_name": "com.sap.hana.di.tabledata.source" + }, + "hdbafllangprocedure": { + "plugin_name": "com.sap.hana.di.afllangprocedure" + }, + "hdbanalyticprivilege": { + "plugin_name": "com.sap.hana.di.analyticprivilege" + }, + "hdbcalculationview": { + "plugin_name": "com.sap.hana.di.calculationview" + }, + "hdbcollection": { + "plugin_name": "com.sap.hana.di.collection" + }, + "hdbconstraint": { + "plugin_name": "com.sap.hana.di.constraint" + }, + "hdbdropcreatetable": { + "plugin_name": "com.sap.hana.di.dropcreatetable" + }, + "hdbflowgraph": { + "plugin_name": "com.sap.hana.di.flowgraph" + }, + "hdbfunction": { + "plugin_name": "com.sap.hana.di.function" + }, + "hdbgraphworkspace": { + "plugin_name": "com.sap.hana.di.graphworkspace" + }, + "hdbhadoopmrjob": { + "plugin_name": "com.sap.hana.di.virtualfunctionpackage.hadoop" + }, + "hdbindex": { + "plugin_name": "com.sap.hana.di.index" + }, + "hdblibrary": { + "plugin_name": "com.sap.hana.di.library" + }, + "hdbmigrationtable": { + "plugin_name": "com.sap.hana.di.table.migration" + }, + "hdbprocedure": { + "plugin_name": "com.sap.hana.di.procedure" + }, + "hdbprojectionview": { + "plugin_name": "com.sap.hana.di.projectionview" + }, + "hdbprojectionviewconfig": { + "plugin_name": "com.sap.hana.di.projectionview.config" + }, + "hdbreptask": { + "plugin_name": "com.sap.hana.di.reptask" + }, + "hdbresultcache": { + "plugin_name": "com.sap.hana.di.resultcache" + }, + "hdbrole": { + "plugin_name": "com.sap.hana.di.role" + }, + "hdbroleconfig": { + "plugin_name": "com.sap.hana.di.role.config" + }, + "hdbsearchruleset": { + "plugin_name": "com.sap.hana.di.searchruleset" + }, + "hdbsequence": { + "plugin_name": "com.sap.hana.di.sequence" + }, + "hdbstatistics": { + "plugin_name": "com.sap.hana.di.statistics" + }, + "hdbstructuredprivilege": { + "plugin_name": "com.sap.hana.di.structuredprivilege" + }, + "hdbsynonym": { + "plugin_name": "com.sap.hana.di.synonym" + }, + "hdbsynonymconfig": { + "plugin_name": "com.sap.hana.di.synonym.config" + }, + "hdbsystemversioning": { + "plugin_name": "com.sap.hana.di.systemversioning" + }, + "hdbtable": { + "plugin_name": "com.sap.hana.di.table" + }, + "hdbtabledata": { + "plugin_name": "com.sap.hana.di.tabledata" + }, + "hdbtabletype": { + "plugin_name": "com.sap.hana.di.tabletype" + }, + "hdbtrigger": { + "plugin_name": "com.sap.hana.di.trigger" + }, + "hdbview": { + "plugin_name": "com.sap.hana.di.view" + }, + "hdbvirtualfunction": { + "plugin_name": "com.sap.hana.di.virtualfunction" + }, + "hdbvirtualfunctionconfig": { + "plugin_name": "com.sap.hana.di.virtualfunction.config" + }, + "hdbvirtualpackagehadoop": { + "plugin_name": "com.sap.hana.di.virtualpackage.hadoop" + }, + "hdbvirtualpackagesparksql": { + "plugin_name": "com.sap.hana.di.virtualpackage.sparksql" + }, + "hdbvirtualprocedure": { + "plugin_name": "com.sap.hana.di.virtualprocedure" + }, + "hdbvirtualprocedureconfig": { + "plugin_name": "com.sap.hana.di.virtualprocedure.config" + }, + "hdbvirtualtable": { + "plugin_name": "com.sap.hana.di.virtualtable" + }, + "hdbvirtualtableconfig": { + "plugin_name": "com.sap.hana.di.virtualtable.config" + }, + "properties": { + "plugin_name": "com.sap.hana.di.tabledata.properties" + }, + "tags": { + "plugin_name": "com.sap.hana.di.tabledata.properties" + }, + "txt": { + "plugin_name": "com.sap.hana.di.copyonly" + }, + "hdbeshconfig": { + "plugin_name": "com.sap.hana.di.eshconfig" + } + } +} diff --git a/samples/bookshop/db/undeploy.json b/samples/bookshop/db/undeploy.json new file mode 100644 index 0000000..aa14b9f --- /dev/null +++ b/samples/bookshop/db/undeploy.json @@ -0,0 +1,7 @@ +[ + "src/gen/**/*.hdbview", + "src/gen/**/*.hdbindex", + "src/gen/**/*.hdbconstraint", + "src/gen/**/*_drafts.hdbtable", + "src/gen/**/*.hdbcalculationview" +] diff --git a/samples/bookshop/mta.yaml b/samples/bookshop/mta.yaml new file mode 100644 index 0000000..1a7a3a8 --- /dev/null +++ b/samples/bookshop/mta.yaml @@ -0,0 +1,87 @@ +_schema-version: 3.3.0 +ID: ai-bookshop +version: 1.0.0-SNAPSHOT +description: "A simple CAP project." +parameters: + enable-parallel-deployments: true +modules: + - name: ai-bookshop + type: approuter.nodejs + path: app/ + parameters: + keep-existing-routes: true + requires: + - name: srv-api + group: destinations + properties: + name: srv-api + url: ~{srv-url} + forwardAuthToken: true + - name: ai-bookshop-auth + provides: + - name: app-api + properties: + app-protocol: ${protocol} + app-uri: ${default-uri} + url: ${default-url} + - name: ai-bookshop-srv + type: java + path: srv + parameters: + instances: 1 + buildpack: sap_java_buildpack_jakarta + properties: + SPRING_PROFILES_ACTIVE: cloud,sandbox + JBP_CONFIG_COMPONENTS: "jres: ['com.sap.xs.java.buildpack.jre.SAPMachineJRE']" + JBP_CONFIG_SAP_MACHINE_JRE: '{ version: 17.+ }' + build-parameters: + builder: custom + commands: + - mvn clean package -DskipTests=true --batch-mode + build-result: target/*-exec.jar + provides: + - name: srv-api # required by consumers of CAP services (e.g. approuter) + properties: + srv-url: ${default-url} + requires: + - name: ai-bookshop-auth + - name: ai-bookshop-db + - name: joule-cap-proxy + + - name: ai-bookshop-db-deployer + type: hdb + path: db + parameters: + buildpack: nodejs_buildpack + build-parameters: + builder: custom + commands: + - npm run build + requires: + - name: ai-bookshop-db + +resources: + - name: ai-bookshop-auth + type: org.cloudfoundry.managed-service + parameters: + service: xsuaa + service-plan: application + path: ./xs-security.json + config: + xsappname: ai-bookshop-${org}-${space} + tenant-mode: dedicated + oauth2-configuration: + redirect-uris: + - https://*~{app-api/app-uri}/** + requires: + - name: app-api + - name: ai-bookshop-db + type: com.sap.xs.hdi-container + parameters: + service: hana + service-plan: hdi-shared + - name: joule-cap-proxy + type: org.cloudfoundry.existing-service + parameters: + service: aicore + service-plan: sap-internal diff --git a/samples/bookshop/package.json b/samples/bookshop/package.json new file mode 100644 index 0000000..be60784 --- /dev/null +++ b/samples/bookshop/package.json @@ -0,0 +1,14 @@ +{ + "name": "bookshop-cds", + "version": "1.0.0", + "description": "Generated by cds-services-archetype", + "license": "ISC", + "repository": "", + "devDependencies": { + "@sap/cds-dk": "^9.3.2" + }, + "dependencies": { + "@cap-js/ai": "*", + "@sap/cds-common-content": "^1.4.0" + } +} diff --git a/samples/bookshop/pom.xml b/samples/bookshop/pom.xml new file mode 100644 index 0000000..0e5e0ea --- /dev/null +++ b/samples/bookshop/pom.xml @@ -0,0 +1,150 @@ + + + 4.0.0 + + customer + bookshop-parent + ${revision} + pom + + bookshop parent + + + + 1.0.0-SNAPSHOT + + + 17 + 4.4.0 + 3.5.6 + + + + + srv + + + + + + + com.sap.cds + cds-services-bom + ${cds.services.version} + pom + import + + + + + org.springframework.boot + spring-boot-dependencies + ${spring.boot.version} + pom + import + + + + com.sap.cds + cds-feature-ai + 1.0.0-SNAPSHOT + + + + + + + + + + com.sap.cds + cds-maven-plugin + ${cds.services.version} + + + + + + + + maven-compiler-plugin + 3.14.1 + + ${java.version} + UTF-8 + + + + + + org.springframework.boot + spring-boot-maven-plugin + ${spring.boot.version} + + true + + + + + + maven-surefire-plugin + 3.5.4 + + + + + org.codehaus.mojo + flatten-maven-plugin + 1.7.3 + + true + resolveCiFriendliesOnly + + + + flatten + process-resources + + flatten + + + + flatten.clean + clean + + clean + + + + + + + + maven-enforcer-plugin + 3.6.2 + + + Project Structure Checks + + enforce + + + + + 3.6.3 + + + ${java.version} + + + + true + + + + + + + diff --git a/samples/bookshop/srv/admin-service.cds b/samples/bookshop/srv/admin-service.cds new file mode 100644 index 0000000..a9f5e36 --- /dev/null +++ b/samples/bookshop/srv/admin-service.cds @@ -0,0 +1,5 @@ +using {sap.capire.bookshop as my} from '../db/schema'; +service AdminService @(requires: 'any') { + entity Books as projection on my.Books; + entity Authors as projection on my.Authors; +} diff --git a/samples/bookshop/srv/cat-service.cds b/samples/bookshop/srv/cat-service.cds new file mode 100644 index 0000000..dee7817 --- /dev/null +++ b/samples/bookshop/srv/cat-service.cds @@ -0,0 +1,34 @@ +using {sap.capire.bookshop as my} from '../db/schema'; + +service CatalogService @(requires: 'any'){ + + /** For displaying lists of Books */ + @readonly + entity ListOfBooks as + projection on Books + excluding { + descr + }; + + /** For display in details pages */ + @readonly + entity Books as + projection on my.Books { + *, + author.name as author + } + excluding { + createdBy, + modifiedBy + }; + + action submitOrder(book : Books:ID, quantity : Integer) returns { + stock : Integer + }; + + event OrderedBook : { + book : Books:ID; + quantity : Integer; + buyer : String + }; +} diff --git a/samples/bookshop/srv/pom.xml b/samples/bookshop/srv/pom.xml new file mode 100644 index 0000000..6415be7 --- /dev/null +++ b/samples/bookshop/srv/pom.xml @@ -0,0 +1,167 @@ + + 4.0.0 + + + bookshop-parent + customer + ${revision} + + + bookshop + jar + + bookshop + + + + + + com.sap.cds + cds-starter-spring-boot + + + + org.springframework.boot + spring-boot-devtools + true + + + + org.springframework.boot + spring-boot-starter-test + test + + + + com.sap.cds + cds-adapter-odata-v4 + runtime + + + + com.h2database + h2 + runtime + + + + org.springframework.boot + spring-boot-starter-security + + + + com.sap.cds + cds-feature-ai + + + + org.springframework.security + spring-security-test + test + + + + com.sap.cds + cds-starter-cloudfoundry + runtime + + + + org.springframework.boot + spring-boot-starter-actuator + + + + + ${project.artifactId} + + + + org.springframework.boot + spring-boot-maven-plugin + ${spring.boot.version} + + false + + + + repackage + + repackage + + + exec + + + + + + + + com.sap.cds + cds-maven-plugin + + + cds.clean + + clean + + + + + cds.install-node + + install-node + + + + + cds.npm-ci + + npm + + + ci + + + + + cds.resolve + + resolve + + + + + cds.build + + cds + + + + build --for java + deploy --to h2 --with-mocks --dry --out + "${project.basedir}/src/main/resources/schema-h2.sql" + + + + + + cds.generate + + generate + + + cds.gen + true + true + true + true + + + + + + + + \ No newline at end of file diff --git a/samples/bookshop/srv/src/main/java/customer/bookshop/Application.java b/samples/bookshop/srv/src/main/java/customer/bookshop/Application.java new file mode 100644 index 0000000..f395d21 --- /dev/null +++ b/samples/bookshop/srv/src/main/java/customer/bookshop/Application.java @@ -0,0 +1,13 @@ +package customer.bookshop; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + +} diff --git a/samples/bookshop/srv/src/main/java/customer/bookshop/handlers/CatalogServiceHandler.java b/samples/bookshop/srv/src/main/java/customer/bookshop/handlers/CatalogServiceHandler.java new file mode 100644 index 0000000..72f17a6 --- /dev/null +++ b/samples/bookshop/srv/src/main/java/customer/bookshop/handlers/CatalogServiceHandler.java @@ -0,0 +1,63 @@ +package customer.bookshop.handlers; + +import java.util.stream.Stream; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import com.sap.cds.ql.Select; +import com.sap.cds.ql.Update; +import com.sap.cds.services.cds.CqnService; +import com.sap.cds.services.handler.EventHandler; +import com.sap.cds.services.handler.annotations.After; +import com.sap.cds.services.handler.annotations.On; +import com.sap.cds.services.handler.annotations.ServiceName; +import com.sap.cds.services.persistence.PersistenceService; + +import cds.gen.catalogservice.Books; +import cds.gen.catalogservice.Books_; +import cds.gen.catalogservice.CatalogService_; +import cds.gen.catalogservice.OrderedBook; +import cds.gen.catalogservice.OrderedBookContext; +import cds.gen.catalogservice.SubmitOrderContext; +import cds.gen.catalogservice.SubmitOrderContext.ReturnType; + +@Component +@ServiceName(CatalogService_.CDS_NAME) +public class CatalogServiceHandler implements EventHandler { + + @Autowired + private PersistenceService db; + + @On + public void submitOrder(SubmitOrderContext context) { + // decrease and update stock in database + db.run(Update.entity(Books_.class).byId(context.getBook()).set(b -> b.stock(), s -> s.minus(context.getQuantity()))); + + // read new stock from database + Books book = db.run(Select.from(Books_.class).where(b -> b.ID().eq(context.getBook()))).single(Books.class); + + // return new stock to client + ReturnType result = SubmitOrderContext.ReturnType.create(); + result.setStock(book.getStock()); + + OrderedBook orderedBook = OrderedBook.create(); + orderedBook.setBook(book.getId()); + orderedBook.setQuantity(context.getQuantity()); + orderedBook.setBuyer(context.getUserInfo().getName()); + + OrderedBookContext orderedBookEvent = OrderedBookContext.create(); + orderedBookEvent.setData(orderedBook); + context.getService().emit(orderedBookEvent); + + context.setResult(result); + } + + @After(event = CqnService.EVENT_READ) + public void discountBooks(Stream books) { + books.filter(b -> b.getTitle() != null && b.getStock() != null) + .filter(b -> b.getStock() > 200) + .forEach(b -> b.setTitle(b.getTitle() + " (discounted)")); + } + +} diff --git a/samples/bookshop/srv/src/main/resources/application.yaml b/samples/bookshop/srv/src/main/resources/application.yaml new file mode 100644 index 0000000..3d5bacd --- /dev/null +++ b/samples/bookshop/srv/src/main/resources/application.yaml @@ -0,0 +1,49 @@ + +logging: + level: + root: INFO + com.sap.cds: DEBUG +--- +spring: + datasource: + url: "jdbc:h2:mem:testdb" + config: + activate: + on-profile: default + sql: + init: + platform: h2 +cds: + requires: + AICore: + resourceGroup: custom-resource-group + security: + mock: + users: + admin: + password: admin + roles: + - admin + user: + password: user + data-source: + auto-config: + enabled: false +--- +management: + endpoint: + health: + show-components: always + probes: + enabled: true + endpoints: + web: + exposure: + include: health + health: + defaults: + enabled: false + ping: + enabled: true + db: + enabled: true diff --git a/samples/bookshop/srv/src/test/java/customer/bookshop/ApplicationTest.java b/samples/bookshop/srv/src/test/java/customer/bookshop/ApplicationTest.java new file mode 100644 index 0000000..152543a --- /dev/null +++ b/samples/bookshop/srv/src/test/java/customer/bookshop/ApplicationTest.java @@ -0,0 +1,21 @@ +package customer.bookshop; + +import static org.assertj.core.api.Assertions.assertThat; + +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.context.ApplicationContext; + +@SpringBootTest +@AutoConfigureMockMvc +class ApplicationTest { + + @Autowired private ApplicationContext context; + + @Test + void checkApplicationContextCanBeLoaded() { + assertThat(context).isNotNull(); + } +} \ No newline at end of file diff --git a/samples/bookshop/srv/src/test/java/customer/bookshop/handlers/CatalogServiceHandlerTest.java b/samples/bookshop/srv/src/test/java/customer/bookshop/handlers/CatalogServiceHandlerTest.java new file mode 100644 index 0000000..6c510cd --- /dev/null +++ b/samples/bookshop/srv/src/test/java/customer/bookshop/handlers/CatalogServiceHandlerTest.java @@ -0,0 +1,42 @@ +package customer.bookshop.handlers; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.stream.Stream; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import cds.gen.catalogservice.Books; + +class CatalogServiceHandlerTest { + + private CatalogServiceHandler handler = new CatalogServiceHandler(); + private Books book = Books.create(); + + @BeforeEach + public void prepareBook() { + book.setTitle("title"); + } + + @Test + void testDiscount() { + book.setStock(500); + handler.discountBooks(Stream.of(book)); + assertEquals("title (discounted)", book.getTitle()); + } + + @Test + void testNoDiscount() { + book.setStock(100); + handler.discountBooks(Stream.of(book)); + assertEquals("title", book.getTitle()); + } + + @Test + void testNoStockAvailable() { + handler.discountBooks(Stream.of(book)); + assertEquals("title", book.getTitle()); + } + +} diff --git a/samples/bookshop/xs-security.json b/samples/bookshop/xs-security.json new file mode 100644 index 0000000..9d8a299 --- /dev/null +++ b/samples/bookshop/xs-security.json @@ -0,0 +1,10 @@ +{ + "scopes": [], + "attributes": [], + "role-templates": [], + "oauth2-configuration": { + "redirect-uris": [ + "https://*.cfapps.eu12.hana.ondemand.com/**" + ] + } +} diff --git a/srv/pom.xml b/srv/pom.xml new file mode 100644 index 0000000..0fddd54 --- /dev/null +++ b/srv/pom.xml @@ -0,0 +1,218 @@ + + + 4.0.0 + + + com.sap.cds + cds-feature-ai-root + ${revision} + + + cds-feature-ai + jar + + CDS Feature for AI + + + + com.sap.cds + cds-starter-spring-boot + + + + com.sap.cds + cds-services-utils + + + com.sap.cds + cds-adapter-api + + + com.sap.cds + cds4j-core + + + com.sap.cloud.mt + tools + + + + + + com.sap.ai.sdk + core + ${ai-sdk.version} + + + + com.sap.ai.sdk.foundationmodels + sap-rpt + ${ai-sdk.version} + + + + + + + + + ${project.artifactId} + + + org.pitest + pitest-maven + + + com.sap.cds.feature.ai.* + + + CONSTRUCTOR_CALLS + VOID_METHOD_CALLS + NON_VOID_METHOD_CALLS + CONDITIONALS_BOUNDARY + EMPTY_RETURNS + NEGATE_CONDITIONALS + REMOVE_CONDITIONALS_EQUAL_IF + REMOVE_CONDITIONALS_EQUAL_ELSE + REMOVE_CONDITIONALS_ORDER_IF + REMOVE_CONDITIONALS_ORDER_ELSE + + 95 + 90 + + + + + org.pitest + pitest-junit5-plugin + ${pitest.maven.plugin.version} + + + + + + + maven-clean-plugin + + + + ./ + + .flattened-pom.xml + + + + + + + auto-clean + + clean + + clean + + + + + + + com.sap.cds + cds-maven-plugin + + + cds.clean + + clean + + + + + cds.install-node + + install-node + + + + + cds.npm-ci + + npm + + + ci + + + + + cds.resolve + + resolve + + + + + cds.build + + cds + + + + build --for java + deploy --to h2 --with-mocks --dry --out + "${project.basedir}/src/main/resources/schema-h2.sql" + + + + + + cds.generate + + generate + + + cds.gen + true + true + true + true + + + + + + + org.jacoco + jacoco-maven-plugin + + + ${excluded.generation.package}**/* + + + + + jacoco-initialize + + prepare-agent + + + + jacoco-site-report-all-tests + + report + + verify + + + jacoco-site-report-only-unit-tests + + report + + test + + + + + + + + diff --git a/srv/src/main/java/com/sap/cds/feature/ai/AIRuntimeConfiguration.java b/srv/src/main/java/com/sap/cds/feature/ai/AIRuntimeConfiguration.java new file mode 100644 index 0000000..2482669 --- /dev/null +++ b/srv/src/main/java/com/sap/cds/feature/ai/AIRuntimeConfiguration.java @@ -0,0 +1,51 @@ +/* + * © 2026 SAP SE or an SAP affiliate company and cds-feature-ai contributors. + */ +package com.sap.cds.feature.ai; + +import com.sap.cds.feature.ai.client.setup.AICoreSetupHandler; +import com.sap.cds.services.ServiceCatalog; +import com.sap.cds.services.persistence.PersistenceService; +import com.sap.cds.services.runtime.CdsRuntime; +import com.sap.cds.services.runtime.CdsRuntimeConfiguration; +import com.sap.cds.services.runtime.CdsRuntimeConfigurer; +import com.sap.cloud.environment.servicebinding.api.ServiceBinding; +import java.util.Optional; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class AIRuntimeConfiguration implements CdsRuntimeConfiguration { + + private static final Logger logger = LoggerFactory.getLogger(AIRuntimeConfiguration.class); + + @Override + public void eventHandlers(CdsRuntimeConfigurer configurer) { + + CdsRuntime runtime = configurer.getCdsRuntime(); + ServiceCatalog serviceCatalog = runtime.getServiceCatalog(); + + PersistenceService persistenceService = + serviceCatalog.getService(PersistenceService.class, PersistenceService.DEFAULT_NAME); + + Optional binding = + runtime + .getEnvironment() + .getServiceBindings() + .filter(b -> b.getServiceName().map(name -> name.equals("aicore")).orElse(false)) + .findFirst(); + // If the AI Core service binding is present, create the AICoreSetup event handler to manage + // resource groups for tenants. + // The binding itself does *not* need to be passed to the AICoreSetup; the AICoreSetup uses + // the com.sap.ai.sdk.core library which reads the binding directly from the environment + // variable AICORE_SERVICE_KEY. + Optional setup = + binding.map(b -> new AICoreSetupHandler(runtime.getEnvironment())); + setup.ifPresent( + s -> { + configurer.eventHandler(s); + logger.info("Registered AICoreSetup as event handler for MTX subscribe/unsubscribe."); + }); + configurer.eventHandler(new FioriRecommendationHandler(setup, persistenceService)); + logger.info("Registered FioriRecommendationHandler for recommendations."); + } +} diff --git a/srv/src/main/java/com/sap/cds/feature/ai/FioriRecommendationHandler.java b/srv/src/main/java/com/sap/cds/feature/ai/FioriRecommendationHandler.java new file mode 100644 index 0000000..cf06052 --- /dev/null +++ b/srv/src/main/java/com/sap/cds/feature/ai/FioriRecommendationHandler.java @@ -0,0 +1,332 @@ +/* + * © 2026 SAP SE or an SAP affiliate company and cds-feature-ai contributors. + */ +package com.sap.cds.feature.ai; + +import com.sap.cds.feature.ai.client.AIClient; +import com.sap.cds.feature.ai.client.AICoreClient; +import com.sap.cds.feature.ai.client.MockAIClient; +import com.sap.cds.feature.ai.client.setup.AICoreSetupHandler; +import com.sap.cds.ql.Select; +import com.sap.cds.ql.cqn.CqnSelect; +import com.sap.cds.services.cds.ApplicationService; +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.After; +import com.sap.cds.services.handler.annotations.ServiceName; +import com.sap.cds.services.persistence.PersistenceService; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Handler that provides Fiori AI recommendations for entities with value help. This implementation + * adds SAP_Recommendations to draft-enabled entities. + */ +@ServiceName(value = "*", type = ApplicationService.class) +public class FioriRecommendationHandler implements EventHandler { + + private final AIClient aiClient; + private final PersistenceService db; + private static final Logger logger = LoggerFactory.getLogger(FioriRecommendationHandler.class); + private static final String VALUE_LIST_ANNOTATION = "@Common.ValueList"; + private static final String VALUE_LIST_WITH_FIXED_VALUES_ANNOTATION = + "@Common.ValueListWithFixedValues"; + private static final String ASSOCIATION = "cds.Association"; + private static final String LARGE_BINARY = "cds.LargeBinary"; + private static final String VECTOR = "cds.Vector"; + private static final Set DRAFT_FIELDS = + Set.of( + "HasActiveEntity", + "HasDraftEntity", + "IsActiveEntity", + "DraftAdministrativeData_DraftUUID"); + + public FioriRecommendationHandler(Optional setupOpt, PersistenceService db) { + this.db = db; + if (setupOpt.isPresent()) { + logger.info("Registered AI Service Handler with AI Core setup."); + this.aiClient = new AICoreClient(setupOpt.get()); + } else { + logger.warn( + "No service binding to AI Service found, using mock implementation for Fiori recommendations!"); + this.aiClient = new MockAIClient(); + } + } + + /* + * After read event handler for Fiori AI recommendations: + * - Checks it's a draft read (IsActiveEntity = false), otherwise it's a read-only view and no + * recommendations are needed. + * - Finds all elements with value help annotations, these are the columns we want to predict + * - Fetches up to 2018 existing rows from DB as training context + * - Appends the current row with [PREDICT] as a placeholder + * - Sends the whole batch to the AI client → gets back predictions per row per column + * - Resolves human-readable descriptions for predicted IDs (e.g. genre.name for a predicted genre_ID) + * - Writes predictions into row.put("SAP_Recommendations", {...}) on the live result object, + */ + @After(event = CqnService.EVENT_READ, entity = "*") + public void afterRead(CdsReadEventContext context) { + List rows = context.getResult().listOf(Map.class); + + if (rows.isEmpty()) { + logger.debug("No result found, skipping predictions."); + return; + } + + if (rows.size() > 1) { + logger.debug( + "Multiple entites requested, recommendations are only available for single entity drafts."); + return; + } + + Map row = rows.get(0); + + // Only fetch predictions when editing a draft (IsActiveEntity = false) + Object isActiveEntity = row.get("IsActiveEntity"); + if (!Boolean.FALSE.equals(isActiveEntity)) { + logger.debug( + "Not editing a draft (IsActiveEntity={}), skipping predictions.", isActiveEntity); + return; + } + + // Get all fields that have value help annotations, if there are none, then there are no + // predictions to fetch + // Also Filter out association elements as they are navigation properties and not actual + // columns. + // When @Common.ValueListWithFixedValues is set on an association, CDS + // propagates the annotation to both the association element and its generated scalar + // foreign-key + // field. We only want the scalar fields for prediction, + // as those map to real DB columns and carry the actual values the AI model predicts. + List predictionColumns = + context + .getTarget() + .elements() + .filter( + e -> { + return e.findAnnotation(VALUE_LIST_ANNOTATION).isPresent() + || e.findAnnotation(VALUE_LIST_WITH_FIXED_VALUES_ANNOTATION).isPresent(); + }) + .filter(e -> !e.getType().getQualifiedName().equals(ASSOCIATION)) + .map(e -> e.getName()) + .collect(Collectors.toList()); + if (predictionColumns.isEmpty()) { + logger.debug("No prediction columns found, skipping predictions."); + return; + } + + logger.info( + "Will fetch predictions for entity: " + + context.getTarget().getName() + + " and columns: " + + String.join(", ", predictionColumns)); + + // Columns to include in the context SELECT: exclude BLOBs, Vectors, and draft-only fields + // (mirrors the Node.js filter: type !== 'cds.LargeBinary' && type !== 'cds.Vector') + List contextColumns = + context + .getTarget() + .elements() + .filter(e -> !e.getType().getQualifiedName().equals(LARGE_BINARY)) + .filter(e -> !e.getType().getQualifiedName().equals(VECTOR)) + .filter(e -> !DRAFT_FIELDS.contains(e.getName())) + .filter(e -> !e.getType().getQualifiedName().equals(ASSOCIATION)) + .map(e -> e.getName()) + .collect(Collectors.toList()); + + // Now fetch up to 2018 context rows where all prediction fields are not null + CqnSelect contextQuery = + Select.from(context.getTarget().getQualifiedName()) + .columns(contextColumns.toArray(String[]::new)) + .where( + entity -> { + com.sap.cds.ql.Predicate condition = null; + // Iterate over all prediction columns, add condition that they must be not null + // and concatenate with AND + for (String col : predictionColumns) { + com.sap.cds.ql.Predicate notNull = entity.get(col).isNotNull(); + // concatenate: all columns we want predictions for must not be null + condition = condition == null ? notNull : condition.and(notNull); + } + return condition; + }) + .limit(2018); + List contextRows = new ArrayList<>(db.run(contextQuery).listOf(Map.class)); + if (contextRows.size() < 2) { + logger.info( + "Not enough context rows found with non-null values for prediction columns (minimum is 2), skipping predictions."); + return; + } + + // Add current row with [PREDICT] placeholders; strip draft-only fields first + // (mirrors Node.js: delete predictionRow.DraftAdministrativeData_DraftUUID etc.) + Map predictRow = new HashMap<>(row); + DRAFT_FIELDS.forEach(predictRow::remove); + for (String col : predictionColumns) { + predictRow.putIfAbsent(col, "[PREDICT]"); + } + if (!predictRow.values().contains("[PREDICT]")) { + logger.info( + "Current row already has values for all prediction columns, skipping predictions."); + return; + } + contextRows.add(predictRow); + + // Tenant ID is only needed for multi-tenant applications with AI Core, for single-tenant apps + // it is null, + // yet we need to get it here from the context to pass it to the AI client. + String tenantId = context.getUserInfo().getTenant(); + List> predictions = + aiClient.fetchPredictions(contextRows, predictionColumns, tenantId); + + // For now, we have requested predictions for exactly one row with [PREDICT] placeholders, + // which is why we expect a list of size 1 back from the aiClient. + // In the future, we could also support multiple rows with [PREDICT] placeholders. + if (predictions.isEmpty()) { + logger.warn("No predictions returned from AI client."); + return; + } + if (predictions.size() > 1) { + logger.warn("Multiple predictions returned from AI client, but only one was expected."); + return; + } + Map prediction = predictions.get(0); + + // With the call "fetchPredictions", we get the raw prediction of the format + // { ID : entity_ID, columnName: { prediction: predictionValue }, columnName2: { prediction: + // predictionValue } }. + // + // Left to do: bring the prediction into the below format and put that into the + // "SAP_Recommendations" + // map for the row, which Fiori expects. + // SAP_Recommendations: { + // columnName: { + // RecommendedFieldValue : predictionValue; + // RecommendedFieldIsSuggestion: true; + // RecommendedFieldDescription : "human readable description for the predicted value"; + // RecommendedFieldScoreValue : 0.5; // This number here to rank several predictions per + // column does not matter, since we only have one prediction. + // }, + // columnName2: { ... } + // } + + // To get a human readable recommendation for values where the ID is stored in the main table, + // we build a map for this, i.e. genre_ID -> genre.name, country_code -> country.name, etc. + // The text path is retrieved by stripping off the "_ID" suffix (if there is one) + // and looking for a @Common.Text annotation on the association element (e.g. genre) + // that points to the text field (e.g. genre.name). + Map textPaths = new HashMap<>(); + for (String col : predictionColumns) { + Optional path; + if (col.endsWith("_ID")) { + path = getTextPath(context, col.substring(0, col.length() - 3)); + if (path.isEmpty()) { + path = + getTextPath( + context, + col); // fallback: maybe the ID field itself has the @Common.Text annotation + } + } else { + path = getTextPath(context, col); + } + path.ifPresent(p -> textPaths.put(col, p)); + } + + Map recommendations = new HashMap<>(); + for (String col : predictionColumns) { + Map values = new HashMap<>(); + // Get the recommended value + Object obj = prediction.get(col); + if (obj instanceof List list && !list.isEmpty() && list.get(0) instanceof Map map) { + Object recommendedValue = map.get("prediction"); + // AI always returns strings; try to parse as number + if (recommendedValue instanceof String s) { + try { + recommendedValue = Integer.valueOf(s); + } catch (NumberFormatException ex) { + try { + recommendedValue = Double.valueOf(s); + } catch (NumberFormatException ex2) { + recommendedValue = s; // keep as string + } + } + } + final Object finalValue = recommendedValue; + values.put("RecommendedFieldValue", finalValue); + // Possibly also get the human readable description for that RecommendedFieldValue + values.put( + "RecommendedFieldDescription", + ""); // default to empty string if we cannot find a description + if (textPaths.containsKey( + col)) { // col might be e.g. genre_ID, then textPaths.get(col) could be "genre.name" + String[] parts = textPaths.get(col).split("\\."); // "genre.name" -> ["genre", "name"] + if (parts.length + != 2) { // The expected format for @Common.Text is "association.textField", if it's + // not in this format, we do not resolve the description. + logger.warn( + "Text path {} for column {} is not in expected format 'association.textField', skipping description resolution.", + textPaths.get(col), + col); + continue; + } + CqnSelect descQuery = + Select.from(context.getTarget().getQualifiedName()) + .columns(b -> b.get(col), b -> b.to(parts[0]).get(parts[1])) + .where(b -> b.get(col).eq(finalValue)); + db.run(descQuery) + .forEach( + descRow -> { // this would then return a row with genre_ID and name + Object text = descRow.get(parts[1]); + if (text != null) values.put("RecommendedFieldDescription", text.toString()); + }); + } + values.put( + "RecommendedFieldScoreValue", + 0.5); // If we had multiple predicions, we could use this field to rank them, since we + // only have one prediction, it does not matter what is put here. + values.put( + "RecommendedFieldIsSuggestion", + true); // If we had multiple predicions, we could use this field to select one + // suggestion, since we only have one prediction, it does not matter what is put + // here. + recommendations.put(col, List.of(values)); + } + } + row.put("SAP_Recommendations", recommendations); + } + + private Optional getTextPath(CdsReadEventContext context, String columnName) { + // Get all elements of entity we are looking at + var elements = context.getTarget().elements(); + return elements + .filter(e -> e.getName().equals(columnName)) // Find the element matching the column name + .findFirst() // .flatMap will only unpack the Optional, if we find an element with + // the given column name + .flatMap( + e -> + e.findAnnotation( + "@Common.Text")) // Check if that element has an annotation @Common.Text and get + // its value, e.g. "=": "genre.name" + .flatMap( + a -> { // .flatMap will only unpack the Optional, if we find an annotation + // @Common.Text + Object val = a.getValue(); + // Path annotations can be strings, i.e., "genre.name" or Maps, i.e., {"=": + // "genre.name"} + if (val instanceof String s) return Optional.of(s); + if (val instanceof Map m) { + Object eq = m.get("="); + return eq != null ? Optional.of(eq.toString()) : Optional.empty(); + } + return Optional.empty(); + }); + } +} diff --git a/srv/src/main/java/com/sap/cds/feature/ai/client/AIClient.java b/srv/src/main/java/com/sap/cds/feature/ai/client/AIClient.java new file mode 100644 index 0000000..cc07d67 --- /dev/null +++ b/srv/src/main/java/com/sap/cds/feature/ai/client/AIClient.java @@ -0,0 +1,20 @@ +/* + * © 2026 SAP SE or an SAP affiliate company and cds-feature-ai contributors. + */ +package com.sap.cds.feature.ai.client; + +import java.util.List; +import java.util.Map; + +public interface AIClient { + /** + * Fetch predictions for the given rows. + * + * @param rows context rows + rows with [PREDICT] placeholders + * @param predictionColumns fields to predict + * @param tenantId the current tenant ID; null in single-tenant mode + * @return predicted values per row + */ + List> fetchPredictions( + List rows, List predictionColumns, String tenantId); +} diff --git a/srv/src/main/java/com/sap/cds/feature/ai/client/AICoreClient.java b/srv/src/main/java/com/sap/cds/feature/ai/client/AICoreClient.java new file mode 100644 index 0000000..695c9ed --- /dev/null +++ b/srv/src/main/java/com/sap/cds/feature/ai/client/AICoreClient.java @@ -0,0 +1,179 @@ +/* + * © 2026 SAP SE or an SAP affiliate company and cds-feature-ai contributors. + */ +package com.sap.cds.feature.ai.client; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.sap.ai.sdk.core.AiCoreService; +import com.sap.ai.sdk.core.JacksonConfiguration; +import com.sap.ai.sdk.foundationmodels.rpt.RptModel; +import com.sap.ai.sdk.foundationmodels.rpt.generated.client.DefaultApi; +import com.sap.ai.sdk.foundationmodels.rpt.generated.model.PredictRequestPayload; +import com.sap.ai.sdk.foundationmodels.rpt.generated.model.PredictionConfig; +import com.sap.ai.sdk.foundationmodels.rpt.generated.model.PredictionPlaceholder; +import com.sap.ai.sdk.foundationmodels.rpt.generated.model.RowsInnerValue; +import com.sap.ai.sdk.foundationmodels.rpt.generated.model.TargetColumnConfig; +import com.sap.cds.feature.ai.client.setup.AICoreSetupHandler; +import com.sap.cloud.sdk.services.openapi.apache.apiclient.ApiClient; +import com.sap.cloud.sdk.services.openapi.apache.core.OpenApiRequestException; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class AICoreClient implements AIClient { + + private final AICoreSetupHandler setup; + private static final Logger logger = LoggerFactory.getLogger(AICoreClient.class); + + // Retry inference call when resource group inference endpoint is not yet ready (403) + private static final int INFERENCE_READY_MAX_RETRIES = 8; + private static final long INFERENCE_READY_INITIAL_DELAY_MS = 500; + + // Safety-net: exclude draft/admin fields from the prediction request body. + // BLOB/Vector fields are already filtered upstream in FioriRecommendationHandler. + private static final Set EXCLUDED_FIELDS = + Set.of( + "HasActiveEntity", + "HasDraftEntity", + "IsActiveEntity", + "DraftAdministrativeData_DraftUUID", + "createdBy", + "modifiedBy", + "createdAt", + "modifiedAt"); + + public AICoreClient(AICoreSetupHandler setup) { + this.setup = setup; + } + + @Override + /* + * Prediction flow: + * 1. resolveResourceGroup(tenantId) to get the AI Core resource group for the tenant + * 2. call predict() with the resource group, input rows and prediction columns + */ + public List> fetchPredictions( + List rows, List predictionColumns, String tenantId) { + try { + String resourceGroup = setup.resolveResourceGroup(tenantId); + return predict(resourceGroup, rows, predictionColumns); + } catch (Exception e) { + logger.error("Failed to fetch predictions from AI Core", e); + throw new RuntimeException("Failed to fetch predictions from AI Core", e); + } + } + + /* + * As described in https://sap.github.io/ai-sdk/docs/java/foundation-models/sap-rpt/table-completion#simple-table-completion + * 1. Build a PredictRequestPayload with the input rows and prediction column config + * 2. Call the AI Core API to get predictions + * 3. Parse and return the predictions as List> + */ + private List> predict( + String resourceGroup, List rows, List predictionColumns) { + var targetColumns = + predictionColumns.stream() + .map( + col -> + TargetColumnConfig.create() + .name(col) + .predictionPlaceholder(PredictionPlaceholder.create("[PREDICT]")) + .taskType(TargetColumnConfig.TaskTypeEnum.CLASSIFICATION)) + .collect(Collectors.toList()); + + var sdkRows = + rows.stream() + .map( + row -> { + Map sdkRow = new LinkedHashMap<>(); + row.forEach( + (k, v) -> { + if (!EXCLUDED_FIELDS.contains(k) + && v != null + && (v instanceof String + || v instanceof Number + || v instanceof Boolean)) { + sdkRow.put(k.toString(), RowsInnerValue.create(v.toString())); + } + }); + return sdkRow; + }) + .collect(Collectors.toList()); + + var request = + PredictRequestPayload.create() + .predictionConfig(PredictionConfig.create().targetColumns(targetColumns)) + .rows(sdkRows) + .indexColumn("ID"); + + logger.debug( + "Sending prediction request for {} rows, {} target columns", + sdkRows.size(), + targetColumns.size()); + + // In multi-tenant mode, we manage the RPT-1 deployment lifecycle per resource group ourselves + // (create on subscribe, delete on unsubscribe), so we resolve the deployment ID explicitly. + // In single-tenant mode, we let the SDK resolve the deployment via forModel(), which queries + // AI Core for any running RPT-1 deployment in the resource group. + + // In multi-tenant mode, we cannot use RptClient.forModel(), because it calls + // AiCoreService().getInferenceDestination() with no arguments, + // which always resolves to the "default" resource group. Instead, we replicate + // the logic from RptClient using our per-tenant resource group, with the same arguments, i.e., + // JacksonConfiguration.getDefaultObjectMapper() and the default header "Content-Encoding: + // gzip". + System.out.println("Resolving inference destination for resource group: " + resourceGroup); + System.out.println( + "AICoreSetup.isMultitenancyEnabled() = " + AICoreSetupHandler.isMultitenancyEnabled()); + var inferenceBuilder = new AiCoreService().getInferenceDestination(resourceGroup); + var model = RptModel.SAP_RPT_1_SMALL; + System.out.println("Using model: " + model.name() + ", deployment: " + inferenceBuilder); + var destination = + AICoreSetupHandler.isMultitenancyEnabled() + ? inferenceBuilder.usingDeploymentId(setup.getDeploymentForResourceGroup(resourceGroup)) + : inferenceBuilder.forModel(RptModel.SAP_RPT_1_SMALL); + var apiClient = + ApiClient.create(destination) + .withObjectMapper(JacksonConfiguration.getDefaultObjectMapper()); + var api = new DefaultApi(apiClient).withDefaultHeaders(Map.of("Content-Encoding", "gzip")); + + // AI Core inference endpoints for freshly created resource groups may return 403 + // until the endpoint is fully provisioned — retry with exponential backoff. + long delay = INFERENCE_READY_INITIAL_DELAY_MS; + for (int i = 0; i < INFERENCE_READY_MAX_RETRIES; i++) { + try { + var response = api.predict(request); + logger.debug("Prediction response id: {}", response.getId()); + try { + return JacksonConfiguration.getDefaultObjectMapper() + .convertValue(response.getPredictions(), new TypeReference<>() {}); + } catch (Exception e) { + throw new RuntimeException("Failed to parse prediction response", e); + } + } catch (OpenApiRequestException e) { + if (AICoreSetupHandler.notReadyYet(e) && i < INFERENCE_READY_MAX_RETRIES - 1) { + logger.debug( + "Inference endpoint for resource group {} not ready yet (403), retrying in {} ms ({}/{})", + resourceGroup, + delay, + i + 1, + INFERENCE_READY_MAX_RETRIES); + try { + Thread.sleep(delay); + } catch (InterruptedException ie) { + Thread.currentThread().interrupt(); + throw new RuntimeException("Interrupted while waiting for inference endpoint", ie); + } + delay *= 2; + } else { + throw e; + } + } + } + throw new IllegalStateException("predict() exited retry loop unexpectedly"); + } +} diff --git a/srv/src/main/java/com/sap/cds/feature/ai/client/MockAIClient.java b/srv/src/main/java/com/sap/cds/feature/ai/client/MockAIClient.java new file mode 100644 index 0000000..8367a80 --- /dev/null +++ b/srv/src/main/java/com/sap/cds/feature/ai/client/MockAIClient.java @@ -0,0 +1,56 @@ +/* + * © 2026 SAP SE or an SAP affiliate company and cds-feature-ai contributors. + */ +package com.sap.cds.feature.ai.client; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Random; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class MockAIClient implements AIClient { + + private static final Logger logger = LoggerFactory.getLogger(MockAIClient.class); + + @Override + public List> fetchPredictions( + List rows, List predictionColumns, String tenantId) { + List> predictions = new ArrayList<>(); + Random random = new Random(); + + for (Map row : rows) { + Map prediction = new HashMap<>(); + boolean addPrediction = false; + for (String col : predictionColumns) { + if ("[PREDICT]".equals(row.get(col))) { + addPrediction = true; + List availableValues = + rows.stream() + .filter(r -> r.get(col) != null && !"[PREDICT]".equals(r.get(col))) + .map(r -> r.get(col)) + .collect(java.util.stream.Collectors.toList()); + Object contextValue = + availableValues.isEmpty() + ? null + : availableValues.get( + random.nextInt( + availableValues + .size())); // get a random value from the existing values for this + // column + Map predictionEntry = new HashMap<>(); + predictionEntry.put("prediction", contextValue); + prediction.put(col, List.of(predictionEntry)); + } + } + if (addPrediction) { + prediction.put("ID", row.get("ID")); + predictions.add(prediction); + } + } + logger.info("Generated mock predictions: " + predictions.toString()); + return predictions; + } +} diff --git a/srv/src/main/java/com/sap/cds/feature/ai/client/setup/AICoreSetupHandler.java b/srv/src/main/java/com/sap/cds/feature/ai/client/setup/AICoreSetupHandler.java new file mode 100644 index 0000000..2249167 --- /dev/null +++ b/srv/src/main/java/com/sap/cds/feature/ai/client/setup/AICoreSetupHandler.java @@ -0,0 +1,372 @@ +/* + * © 2026 SAP SE or an SAP affiliate company and cds-feature-ai contributors. + */ +package com.sap.cds.feature.ai.client.setup; + +import com.sap.ai.sdk.core.client.ConfigurationApi; +import com.sap.ai.sdk.core.client.DeploymentApi; +import com.sap.ai.sdk.core.client.ResourceGroupApi; +import com.sap.ai.sdk.core.model.AiConfiguration; +import com.sap.ai.sdk.core.model.AiConfigurationBaseData; +import com.sap.ai.sdk.core.model.AiConfigurationList; +import com.sap.ai.sdk.core.model.AiDeployment; +import com.sap.ai.sdk.core.model.AiDeploymentCreationRequest; +import com.sap.ai.sdk.core.model.AiDeploymentList; +import com.sap.ai.sdk.core.model.AiDeploymentStatus; +import com.sap.ai.sdk.core.model.AiParameterArgumentBinding; +import com.sap.ai.sdk.core.model.BckndResourceGroup; +import com.sap.ai.sdk.core.model.BckndResourceGroupLabel; +import com.sap.ai.sdk.core.model.BckndResourceGroupList; +import com.sap.ai.sdk.core.model.BckndResourceGroupsPostRequest; +import com.sap.cds.services.environment.CdsEnvironment; +import com.sap.cds.services.handler.EventHandler; +import com.sap.cds.services.handler.annotations.After; +import com.sap.cds.services.handler.annotations.Before; +import com.sap.cds.services.handler.annotations.ServiceName; +import com.sap.cds.services.mt.DeploymentService; +import com.sap.cds.services.mt.SubscribeEventContext; +import com.sap.cds.services.mt.UnsubscribeEventContext; +import com.sap.cloud.sdk.services.openapi.apache.core.OpenApiRequestException; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +@ServiceName(DeploymentService.DEFAULT_NAME) +public class AICoreSetupHandler implements EventHandler { + + private static final String DEFAULT_RESOURCE_GROUP = "default"; + private static final String TENANT_LABEL_KEY = "ext.ai.sap.com/CDS_TENANT_ID"; + private static final String RPT_SCENARIO_ID = "foundation-models"; + private static final String RPT_EXECUTABLE_ID = "aicore-sap"; + private static final String RPT_CONFIG_NAME = "sap-rpt-1-small"; + private static final String RPT_MODEL_NAME = "sap-rpt-1-small"; + private static final String RPT_MODEL_VERSION = "latest"; + // Max retries and initial delay (ms) when polling for RUNNING of deployment or readiness of + // resource group + private static final int AICORE_OPS_MAX_RETRIES = 10; + private static final long AICORE_OPS_INITIAL_DELAY_MS = 300; + private static final Logger logger = LoggerFactory.getLogger(AICoreSetupHandler.class); + + // In-memory cache: tenantId -> resourceGroupId + private final Map tenantResourceGroupCache = new ConcurrentHashMap<>(); + // In-memory cache: resourceGroupId -> RPT-1 deploymentId + private final Map resourceGroupDeploymentCache = new ConcurrentHashMap<>(); + + private final CdsEnvironment environment; + + // For testing + Map getTenantResourceGroupCache() { + return tenantResourceGroupCache; + } + + Map getResourceGroupDeploymentCache() { + return resourceGroupDeploymentCache; + } + + public AICoreSetupHandler(CdsEnvironment environment) { + this.environment = environment; + } + + /** + * Called automatically after a tenant subscribes: Creates an AI Core resource group for the + * tenant. + */ + @After(event = DeploymentService.EVENT_SUBSCRIBE) + public void afterSubscribe(SubscribeEventContext context) { + String tenantId = context.getTenant(); + logger.debug("Creating AI Core resources for tenant {}", tenantId); + try { + String resourceGroupId = getResourceGroupForTenant(tenantId); + logger.info("Created AI Core resource group {} for tenant {}", resourceGroupId, tenantId); + } catch (Exception e) { + // Don't throw - let subscription succeed + logger.error( + "Failed to create AI Core resources for tenant {} (retrying on demand)", tenantId, e); + } + } + + /** + * Called automatically before a tenant unsubscribes: Deletes the AI Core resource group for the + * tenant. + */ + @Before(event = DeploymentService.EVENT_UNSUBSCRIBE) + public void beforeUnsubscribe(UnsubscribeEventContext context) { + String tenantId = context.getTenant(); + logger.debug("Deleting AI Core resources for tenant {}", tenantId); + try { + deleteResourceGroupForTenant(tenantId); + logger.info("Deleted AI Core resources for tenant {}", tenantId); + } catch (Exception e) { + // Don't throw - let unsubscription succeed + logger.warn("Failed to delete AI Core resources for tenant {}: {}", tenantId, e.getMessage()); + } + } + + public static boolean isMultitenancyEnabled() { + return Boolean.parseBoolean( + System.getProperty( + "cds.multitenancy.enabled", + System.getenv().getOrDefault("CDS_MULTITENANCY_ENABLED", "false"))); + // this.environment.getProperty("cds.requires.multitenancy", Boolean.class, false)); + } + + /** + * Resolves the resource group for the given tenant. In multi-tenant mode, checks for an existing + * resource group or creates one. In single-tenant mode, returns the default resource group. + */ + public String resolveResourceGroup(String tenantId) { + if (isMultitenancyEnabled()) { + return getResourceGroupForTenant(tenantId); + } + String group = + this.environment.getProperty( + "cds.requires.AICore.resourceGroup", String.class, DEFAULT_RESOURCE_GROUP); + group = group != null ? group : DEFAULT_RESOURCE_GROUP; + logger.info("Multitenancy disabled, using resource group {}", group); + return group; + } + + /** + * Returns the resource group for a tenant, creating one in AI Core if it doesn't exist yet. + * Caches the result in memory. + */ + private String getResourceGroupForTenant(String tenantId) { + String cached = tenantResourceGroupCache.get(tenantId); + if (cached != null) { + return cached; + } + ResourceGroupApi api = new ResourceGroupApi(); + List labelSelector = List.of(TENANT_LABEL_KEY + "=" + tenantId); + BckndResourceGroupList result = api.getAll(null, null, null, null, null, null, labelSelector); + List resources = result.getResources(); + if (resources != null && !resources.isEmpty()) { + String resourceGroupId = resources.get(0).getResourceGroupId(); + tenantResourceGroupCache.put(tenantId, resourceGroupId); + return resourceGroupId; + } + String createdId = createResourceGroupForTenant(tenantId, api); + tenantResourceGroupCache.put(tenantId, createdId); + return createdId; + } + + // See + // https://javadoc.io/doc/com.sap.ai.sdk/core/latest/com/sap/ai/sdk/core/model/BckndResourceGroupsPostRequest.html + private String createResourceGroupForTenant(String tenantId, ResourceGroupApi api) { + // This resourceGroupId is needed for the request, will fail otherwise + String resourceGroupId = UUID.randomUUID().toString(); + BckndResourceGroupLabel label = + BckndResourceGroupLabel.create().key(TENANT_LABEL_KEY).value(tenantId); + BckndResourceGroupsPostRequest request = + BckndResourceGroupsPostRequest.create() + .resourceGroupId(resourceGroupId) + .labels(List.of(label)); + api.create(request); + logger.debug("Created resource group {} for tenant {}", resourceGroupId, tenantId); + return resourceGroupId; + } + + /** + * Returns the RPT-1 deployment ID for the given resource group, creating configuration and + * deployment if none exists. Polls until the deployment reaches RUNNING status, which might take + * a while. Caches the result in memory. + */ + public String getDeploymentForResourceGroup(String resourceGroup) { + String cached = resourceGroupDeploymentCache.get(resourceGroup); + if (cached != null) { + return cached; + } + DeploymentApi deploymentApi = new DeploymentApi(); + // Look for an existing running or pending RPT-1 deployment in this resource group. + AiDeploymentList deploymentList = + queryDeploymentsFromResourceGroupUntilReady(deploymentApi, resourceGroup); + Optional aiDeployment = + deploymentList.getResources().stream() + .filter( + d -> + RPT_CONFIG_NAME.equals(d.getConfigurationName()) + && (AiDeploymentStatus.RUNNING.equals(d.getStatus()) + || AiDeploymentStatus.PENDING.equals(d.getStatus()))) + .findFirst(); + if (aiDeployment.isPresent()) { + String deploymentId = aiDeployment.get().getId(); + resourceGroupDeploymentCache.put(resourceGroup, deploymentId); + return deploymentId; + } + + // No deployment found: we check if there is a configuration, if not create one and then create + // a deployment. + // The resource group should be ready for this call, since + // queryDeploymentsFromResourceGroupUntilReady made sure it is. + ConfigurationApi configApi = new ConfigurationApi(); + AiConfigurationList configList = + configApi.query(resourceGroup, RPT_SCENARIO_ID, null, null, null, null, null, null); + Optional existingConfig = + configList.getResources().stream() + .filter(c -> RPT_CONFIG_NAME.equals(c.getName())) + .findFirst(); + + String configId; + if (existingConfig.isPresent()) { + configId = existingConfig.get().getId(); + logger.debug( + "Reusing existing RPT-1 configuration {} in resource group {}", configId, resourceGroup); + } else { + // Configuration creation is synchronous and should be fast, so we don't implement a retry + // loop here. + AiConfigurationBaseData configRequest = + AiConfigurationBaseData.create() + .name(RPT_CONFIG_NAME) + .executableId(RPT_EXECUTABLE_ID) + .scenarioId(RPT_SCENARIO_ID); + configRequest.parameterBindings( + List.of( + AiParameterArgumentBinding.create().key("modelName").value(RPT_MODEL_NAME), + AiParameterArgumentBinding.create().key("modelVersion").value(RPT_MODEL_VERSION))); + configId = configApi.create(resourceGroup, configRequest).getId(); + logger.debug("Created RPT-1 configuration {} in resource group {}", configId, resourceGroup); + } + + // Now create a deployment for the configuration and poll until it's running and usable. + long delay = AICORE_OPS_INITIAL_DELAY_MS; + for (int i = 0; i < AICORE_OPS_MAX_RETRIES; i++) { + try { + var deployRequest = AiDeploymentCreationRequest.create().configurationId(configId); + var deployResponse = deploymentApi.create(resourceGroup, deployRequest); + String deploymentId = deployResponse.getId(); + logger.debug( + "Created RPT-1 deployment {} in resource group {}, polling for RUNNING", + deploymentId, + resourceGroup); + + return pollUntilRunning(deploymentApi, resourceGroup, deploymentId); + } catch (OpenApiRequestException e) { + if (notReadyYet(e) && i < AICORE_OPS_MAX_RETRIES - 1) { + logger.debug( + "Deployment of resource group {} not ready yet ({}), retrying in {} ms ({}/{})", + resourceGroup, + e.getMessage(), + delay, + i + 1, + AICORE_OPS_MAX_RETRIES); + try { + Thread.sleep(delay); + } catch (InterruptedException ie) { + Thread.currentThread().interrupt(); + throw new RuntimeException( + "Interrupted while waiting for resource group " + resourceGroup, ie); + } + delay *= 2; + } else { + throw e; + } + } + } + throw new IllegalStateException( + "Resource group " + resourceGroup + " never became ready for deployment"); + } + + private String pollUntilRunning( + DeploymentApi deploymentApi, String resourceGroup, String deploymentId) { + long delay = AICORE_OPS_INITIAL_DELAY_MS; + for (int i = 0; i < AICORE_OPS_MAX_RETRIES; i++) { + try { + Thread.sleep(delay); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new RuntimeException("Interrupted while waiting for deployment " + deploymentId, e); + } + var current = deploymentApi.get(resourceGroup, deploymentId); + logger.debug( + "Deployment {} status: {} (retry {}/{})", + deploymentId, + current.getStatus(), + i + 1, + AICORE_OPS_MAX_RETRIES); + if (AiDeploymentStatus.RUNNING.equals(current.getStatus())) { + resourceGroupDeploymentCache.put(resourceGroup, deploymentId); + return deploymentId; + } + delay *= 2; + } + throw new RuntimeException( + "RPT-1 deployment " + + deploymentId + + " did not reach RUNNING status after " + + AICORE_OPS_MAX_RETRIES + + " retries"); + } + + /* + * Queries deployments in the given resource group. + * In case the resource group isn't ready yet, i.e., the request returns a 403 or 412 status code, + * we query until the resource group becomes ready; this is neccessary for further interaction with + * the resource group. + */ + private AiDeploymentList queryDeploymentsFromResourceGroupUntilReady( + DeploymentApi deploymentApi, String resourceGroup) { + long delay = AICORE_OPS_INITIAL_DELAY_MS; + for (int i = 0; i < AICORE_OPS_MAX_RETRIES; i++) { + try { + return deploymentApi.query( + resourceGroup, null, null, RPT_SCENARIO_ID, null, null, null, null); + } catch (OpenApiRequestException e) { + if (notReadyYet(e) && i < AICORE_OPS_MAX_RETRIES - 1) { + logger.debug( + "Resource group {} not ready yet ({}), retrying in {} ms ({}/{})", + resourceGroup, + e.getMessage(), + delay, + i + 1, + AICORE_OPS_MAX_RETRIES); + try { + Thread.sleep(delay); + } catch (InterruptedException ie) { + Thread.currentThread().interrupt(); + throw new RuntimeException( + "Interrupted while waiting for resource group " + resourceGroup, ie); + } + delay *= 2; + } else { + throw e; + } + } + } + // unreachable — loop always returns or throws + throw new IllegalStateException("queryDeploymentsWithRetry exited unexpectedly"); + } + + /** + * Returns true if the exception (or its cause chain) represents an HTTP 403 or 412. AI Core + * returns 403 or 412 when a deployment is not yet provisioned or ready. In this case, we retry + * the operation that caused the exception after a delay. The SDK sometimes wraps the actual + * OpenApiRequestException in an IOException which is why we check the nested causes. + */ + public static boolean notReadyYet(OpenApiRequestException e) { + Throwable t = e; + while (t != null) { + if (t instanceof OpenApiRequestException oae) { + Integer code = oae.statusCode(); + if (Integer.valueOf(403).equals(code) || Integer.valueOf(412).equals(code)) { + return true; + } + } + t = t.getCause(); + } + return false; + } + + private void deleteResourceGroupForTenant(String tenantId) { + String resourceGroupId = tenantResourceGroupCache.remove(tenantId); + if (resourceGroupId == null) { + logger.debug("No cached resource group for tenant {}, nothing to delete", tenantId); + return; + } + resourceGroupDeploymentCache.remove(resourceGroupId); + new ResourceGroupApi().delete(resourceGroupId); + logger.info("Deleted resource group {} for tenant {}", resourceGroupId, tenantId); + } +} diff --git a/srv/src/main/resources/META-INF/services/com.sap.cds.services.runtime.CdsRuntimeConfiguration b/srv/src/main/resources/META-INF/services/com.sap.cds.services.runtime.CdsRuntimeConfiguration new file mode 100644 index 0000000..bb6e1d3 --- /dev/null +++ b/srv/src/main/resources/META-INF/services/com.sap.cds.services.runtime.CdsRuntimeConfiguration @@ -0,0 +1 @@ +com.sap.cds.feature.ai.AIRuntimeConfiguration \ No newline at end of file diff --git a/srv/src/main/resources/spotbugs-exclusion-filter.xml b/srv/src/main/resources/spotbugs-exclusion-filter.xml new file mode 100644 index 0000000..ee4e277 --- /dev/null +++ b/srv/src/main/resources/spotbugs-exclusion-filter.xml @@ -0,0 +1,24 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/srv/src/test/java/com/sap/cds/feature/ai/FioriRecommendationHandlerTest.java b/srv/src/test/java/com/sap/cds/feature/ai/FioriRecommendationHandlerTest.java new file mode 100644 index 0000000..3024268 --- /dev/null +++ b/srv/src/test/java/com/sap/cds/feature/ai/FioriRecommendationHandlerTest.java @@ -0,0 +1,299 @@ +/* + * © 2026 SAP SE or an SAP affiliate company and cds-feature-ai contributors. + */ +package com.sap.cds.feature.ai; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; + +import com.sap.cds.Result; +import com.sap.cds.ResultBuilder; +import com.sap.cds.feature.ai.client.MockAIClient; +import com.sap.cds.ql.cqn.CqnSelect; +import com.sap.cds.reflect.CdsAnnotation; +import com.sap.cds.reflect.CdsElement; +import com.sap.cds.reflect.CdsEntity; +import com.sap.cds.reflect.CdsType; +import com.sap.cds.services.cds.CdsReadEventContext; +import com.sap.cds.services.persistence.PersistenceService; +import com.sap.cds.services.request.UserInfo; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Mock; +import org.mockito.MockedConstruction; +import org.mockito.junit.jupiter.MockitoExtension; + +@ExtendWith(MockitoExtension.class) +class FioriRecommendationHandlerTest { + + @Mock private PersistenceService db; + @Mock private CdsReadEventContext context; + @Mock private CdsEntity entity; + @Mock private UserInfo userInfo; + + private FioriRecommendationHandler cut; + + @BeforeEach + void setup() { + cut = new FioriRecommendationHandler(Optional.empty(), db); + } + + @Test + void emptyRows_returnsEarlyWithoutPredictions() { + when(context.getResult()).thenReturn(result()); + cut.afterRead(context); + verifyNoInteractions(db); + } + + @Test + void multipleRows_returnsEarlyWithoutPredictions() { + when(context.getResult()) + .thenReturn( + result( + Map.of("ID", "1", "IsActiveEntity", false), + Map.of("ID", "2", "IsActiveEntity", false))); + cut.afterRead(context); + verifyNoInteractions(db); + } + + @Test + void activeEntity_returnsEarlyWithoutPredictions() { + when(context.getResult()).thenReturn(result(Map.of("ID", "1", "IsActiveEntity", true))); + cut.afterRead(context); + verifyNoInteractions(db); + } + + @Test + void noPredictionColumns_returnsEarlyWithoutPredictions() { + // association-typed element: passes ValueList filter but is excluded by the Association filter + CdsElement assocEl = mock(CdsElement.class); + when(assocEl.findAnnotation("@Common.ValueList")) + .thenReturn(Optional.of(mock(CdsAnnotation.class))); + CdsType type = mock(CdsType.class); + when(type.getQualifiedName()).thenReturn("cds.Association"); + when(assocEl.getType()).thenReturn(type); + when(context.getTarget()).thenReturn(entity); + when(entity.elements()).thenAnswer(inv -> java.util.stream.Stream.of(assocEl)); + when(context.getResult()).thenReturn(result(draftRow("title", "foo"))); + cut.afterRead(context); + verifyNoInteractions(db); + } + + @Test + void notEnoughContextRows_returnsEarlyWithoutPredictions() { + setupEntity(genreIdEl()); + Map row = draftRow("genre_ID", null); + when(context.getResult()).thenReturn(result(row)); + when(db.run(any(CqnSelect.class))) + .thenReturn( + ResultBuilder.selectedRows(List.of(Map.of("ID", "x1", "genre_ID", 12))).result()); + cut.afterRead(context); + assertThat(row).doesNotContainKey("SAP_Recommendations"); + } + + @Test + void allColumnsAlreadyFilled_returnsEarlyWithoutPredictions() { + setupEntity(genreIdEl()); + Map row = draftRow("genre_ID", 16); + when(context.getResult()).thenReturn(result(row)); + when(db.run(any(CqnSelect.class))).thenReturn(twoContextRows()); + cut.afterRead(context); + assertThat(row).doesNotContainKey("SAP_Recommendations"); + } + + @Test + void emptyPredictions_returnsEarlyWithoutRecommendations() { + setupEntityWithUserInfo(genreIdEl()); + Map row = draftRow("genre_ID", null); + when(context.getResult()).thenReturn(result(row)); + when(db.run(any(CqnSelect.class))).thenReturn(twoContextRows()); + try (MockedConstruction ignored = + mockConstruction( + MockAIClient.class, + (mock, ctx) -> + when(mock.fetchPredictions(any(), any(), any())).thenReturn(List.of()))) { + cut = new FioriRecommendationHandler(Optional.empty(), db); + cut.afterRead(context); + } + assertThat(row).doesNotContainKey("SAP_Recommendations"); + } + + @Test + void multiplePredictions_returnsEarlyWithoutRecommendations() { + setupEntityWithUserInfo(genreIdEl()); + Map row = draftRow("genre_ID", null); + when(context.getResult()).thenReturn(result(row)); + when(db.run(any(CqnSelect.class))).thenReturn(twoContextRows()); + try (MockedConstruction ignored = + mockConstruction( + MockAIClient.class, + (mock, ctx) -> + when(mock.fetchPredictions(any(), any(), any())) + .thenReturn(List.of(Map.of("ID", "id-1"), Map.of("ID", "id-2"))))) { + cut = new FioriRecommendationHandler(Optional.empty(), db); + cut.afterRead(context); + } + assertThat(row).doesNotContainKey("SAP_Recommendations"); + } + + @Test + @SuppressWarnings({"unchecked", "rawtypes"}) + void draftRow_withGenreAndCurrency_addsSapRecommendations() { + Map row = new HashMap<>(); + row.put("ID", "a009c640-434a-4542-ac68-51b400c880ec"); + row.put("IsActiveEntity", false); + row.put("genre_ID", null); + row.put("currency_code", null); + CdsAnnotation textAnn = mock(CdsAnnotation.class); + when(textAnn.getValue()).thenReturn("genre.name"); + setupEntityWithUserInfo( + element("genre_ID", "cds.Integer", true, Optional.empty()), + element("currency_code", "cds.String", true, Optional.empty()), + element("genre", "cds.Association", false, Optional.of(textAnn))); + when(context.getResult()).thenReturn(result(row)); + when(db.run(any(CqnSelect.class))) + .thenReturn( + ResultBuilder.selectedRows( + new ArrayList<>( + List.of( + Map.of("ID", "id-1", "genre_ID", 12, "currency_code", "USD"), + Map.of("ID", "id-2", "genre_ID", 16, "currency_code", "GBP")))) + .result(), + ResultBuilder.selectedRows(List.of()).result()); + cut.afterRead(context); + assertThat(row).containsKey("SAP_Recommendations"); + Map recs = (Map) row.get("SAP_Recommendations"); + assertThat((List) recs.get("genre_ID")).hasSize(1); + assertThat((List) recs.get("currency_code")).hasSize(1); + } + + @Test + @SuppressWarnings("unchecked") + void textAnnotation_asMap_withEqKey_resolvesTextPath() { + CdsAnnotation textAnn = mock(CdsAnnotation.class); + when(textAnn.getValue()).thenReturn(Map.of("=", "genre.name")); + setupEntityWithUserInfo( + genreIdEl(), element("genre", "cds.Association", false, Optional.of(textAnn))); + Map row = draftRow("genre_ID", null); + when(context.getResult()).thenReturn(result(row)); + when(db.run(any(CqnSelect.class))) + .thenReturn(twoContextRows(), ResultBuilder.selectedRows(List.of()).result()); + cut.afterRead(context); + assertThat((Map) row.get("SAP_Recommendations")).containsKey("genre_ID"); + } + + @Test + @SuppressWarnings("unchecked") + void textAnnotation_asMap_withoutEqKey_noDescription() { + CdsAnnotation textAnn = mock(CdsAnnotation.class); + when(textAnn.getValue()).thenReturn(Map.of("other", "value")); + setupEntityWithUserInfo( + genreIdEl(), element("genre", "cds.Association", false, Optional.of(textAnn))); + Map row = draftRow("genre_ID", null); + when(context.getResult()).thenReturn(result(row)); + when(db.run(any(CqnSelect.class))).thenReturn(twoContextRows()); + cut.afterRead(context); + Map recs = (Map) row.get("SAP_Recommendations"); + assertThat(((List>) recs.get("genre_ID")).get(0)) + .containsEntry("RecommendedFieldDescription", ""); + } + + @Test + @SuppressWarnings("unchecked") + void textPath_invalidFormat_skipsColumn() { + CdsAnnotation textAnn = mock(CdsAnnotation.class); + when(textAnn.getValue()).thenReturn("genre.parent.name"); + setupEntityWithUserInfo( + genreIdEl(), element("genre", "cds.Association", false, Optional.of(textAnn))); + Map row = draftRow("genre_ID", null); + when(context.getResult()).thenReturn(result(row)); + when(db.run(any(CqnSelect.class))).thenReturn(twoContextRows()); + cut.afterRead(context); + assertThat((Map) row.get("SAP_Recommendations")).doesNotContainKey("genre_ID"); + } + + @Test + void blobAndVectorFields_areExcludedFromContextSelect() { + // Arrange: entity with a predictable genre_ID, a LargeBinary (image), and a Vector field + setupEntityWithUserInfo( + genreIdEl(), + element("image", "cds.LargeBinary", false, Optional.empty()), + element("embedding", "cds.Vector", false, Optional.empty())); + Map row = draftRow("genre_ID", null); + when(context.getResult()).thenReturn(result(row)); + + ArgumentCaptor selectCaptor = ArgumentCaptor.forClass(CqnSelect.class); + when(db.run(selectCaptor.capture())).thenReturn(twoContextRows()); + + cut.afterRead(context); + + // The SELECT sent to db.run() must not contain the BLOB or Vector column names + String selectSql = selectCaptor.getValue().toString(); + assertThat(selectSql).doesNotContain("image"); + assertThat(selectSql).doesNotContain("embedding"); + assertThat(selectSql).contains("genre_ID"); + } + + // ── helpers ──────────────────────────────────────────────────────────────── + + @SafeVarargs + private static Result result(Map... rows) { + return ResultBuilder.selectedRows(List.of(rows)).result(); + } + + private Map draftRow(String col, Object val) { + Map row = new HashMap<>(); + row.put("ID", "id-1"); + row.put("IsActiveEntity", false); + row.put(col, val); + return row; + } + + private Result twoContextRows() { + return ResultBuilder.selectedRows( + new ArrayList<>( + List.of(Map.of("ID", "x1", "genre_ID", 12), Map.of("ID", "x2", "genre_ID", 16)))) + .result(); + } + + private CdsElement genreIdEl() { + return element("genre_ID", "cds.Integer", true, Optional.empty()); + } + + private void setupEntity(CdsElement... elements) { + when(context.getTarget()).thenReturn(entity); + lenient().when(entity.getName()).thenReturn("Books"); + lenient().when(entity.getQualifiedName()).thenReturn("bookshop.Books"); + when(entity.elements()).thenAnswer(inv -> java.util.stream.Stream.of(elements)); + } + + private void setupEntityWithUserInfo(CdsElement... elements) { + setupEntity(elements); + when(context.getUserInfo()).thenReturn(userInfo); + when(userInfo.getTenant()).thenReturn(null); // can be null, but must be callabe + } + + @SuppressWarnings({"rawtypes", "unchecked"}) + private static CdsElement element( + String name, String cdsType, boolean hasValueList, Optional textAnnotation) { + CdsElement el = mock(CdsElement.class); + when(el.getName()).thenReturn(name); + CdsType type = mock(CdsType.class); + lenient().when(type.getQualifiedName()).thenReturn(cdsType); + lenient().when(el.getType()).thenReturn(type); + when(el.findAnnotation("@Common.ValueList")).thenReturn(Optional.empty()); + Optional valueListAnn = + hasValueList ? Optional.of(mock(CdsAnnotation.class)) : Optional.empty(); + when(el.findAnnotation("@Common.ValueListWithFixedValues")).thenReturn(valueListAnn); + lenient().when(el.findAnnotation("@Common.Text")).thenReturn((Optional) textAnnotation); + return el; + } +} diff --git a/srv/src/test/java/com/sap/cds/feature/ai/client/AICoreClientPredictionTest.java b/srv/src/test/java/com/sap/cds/feature/ai/client/AICoreClientPredictionTest.java new file mode 100644 index 0000000..bdf43a0 --- /dev/null +++ b/srv/src/test/java/com/sap/cds/feature/ai/client/AICoreClientPredictionTest.java @@ -0,0 +1,232 @@ +/* + * © 2026 SAP SE or an SAP affiliate company and cds-feature-ai contributors. + */ +package com.sap.cds.feature.ai.client; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.sap.cds.feature.ai.client.setup.AICoreSetupHandler; +import com.sap.cds.services.environment.CdsEnvironment; +import java.net.URI; +import java.net.URLEncoder; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.mockito.Mockito; + +/** + * Integration test verifying the full prediction flow against a real AI Core instance. + * + *

Required environment variables: AICORE_SERVICE_KEY – Full AI Core service key JSON: { + * "clientid": "...", "clientsecret": "...", "url": "...", "serviceurls": { "AI_API_URL": "..." } } + */ +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +class AICoreClientPredictionTest { + + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private AICoreClient cut; + private Map credentials; + private String resourceGroup; + + @BeforeAll + void setup() throws Exception { + String serviceKey = System.getenv("AICORE_SERVICE_KEY"); + assumeTrue(serviceKey != null, "Skipping integration test: AICORE_SERVICE_KEY env var not set"); + + credentials = MAPPER.readValue(serviceKey, new TypeReference<>() {}); + resourceGroup = "default"; + CdsEnvironment environment = Mockito.mock(CdsEnvironment.class); + cut = new AICoreClient(new AICoreSetupHandler(environment)); + } + + /** + * Full prediction flow: 1. Check deployments in the resource group 2. If no RUNNING rpt-1 + * deployment exists, create one and wait for it to reach RUNNING 3. Call fetchPredictions with a + * small context row and a [PREDICT] row 4. Verify predictions are returned + */ + @Test + void prediction_deploymentMissingOrPresent_returnsPredictions() throws Exception { + String aiApiUrl = ((Map) credentials.get("serviceurls")).get("AI_API_URL").toString(); + String token = fetchToken(); + + // Step 1+2: ensure a RUNNING rpt-1 deployment exists (create if missing) + ensureRunningRpt1Deployment(aiApiUrl, token); + + // Step 3: build rows — two context rows + one [PREDICT] row + Map contextRow1 = new HashMap<>(); + contextRow1.put("ID", "ctx-1"); + contextRow1.put("genre_ID", 10); + contextRow1.put("title", "Eleonora"); + + Map contextRow2 = new HashMap<>(); + contextRow2.put("ID", "ctx-2"); + contextRow2.put("genre_ID", 20); + contextRow2.put("title", "Another Book"); + + Map predictRow = new HashMap<>(); + predictRow.put("ID", "predict-1"); + predictRow.put("genre_ID", "[PREDICT]"); + predictRow.put("title", "Eleonora"); + + List> predictions = + cut.fetchPredictions( + List.of(contextRow1, contextRow2, predictRow), List.of("genre_ID"), null); + + // Step 4: verify + assertThat(predictions) + .as("Should return at least one prediction result") + .isNotNull() + .isNotEmpty(); + + Map prediction = predictions.get(0); + assertThat(prediction).containsKey("genre_ID"); + } + + // ── helpers ────────────────────────────────────────────────────────────── + + /** + * Checks whether a RUNNING rpt-1 deployment exists. If not, creates one and polls until it + * reaches RUNNING (up to ~5 minutes with exponential back-off). + */ + private void ensureRunningRpt1Deployment(String aiApiUrl, String token) throws Exception { + HttpClient client = HttpClient.newHttpClient(); + + // Check existing deployments + HttpResponse listResponse = + client.send( + HttpRequest.newBuilder() + .uri(URI.create(aiApiUrl + "/v2/lm/deployments")) + .header("Authorization", "Bearer " + token) + .header("AI-Resource-Group", resourceGroup) + .GET() + .build(), + HttpResponse.BodyHandlers.ofString()); + + Map listResult = + MAPPER.readValue(listResponse.body(), new TypeReference<>() {}); + List> deployments = + MAPPER.convertValue(listResult.get("resources"), new TypeReference<>() {}); + + boolean hasRunning = + deployments != null + && deployments.stream() + .anyMatch( + d -> + d.get("configurationName") != null + && d.get("configurationName").toString().contains("rpt-1") + && "RUNNING".equals(d.get("status"))); + + if (hasRunning) { + return; // nothing to do + } + + // Find the rpt-1 configuration + HttpResponse cfgResponse = + client.send( + HttpRequest.newBuilder() + .uri(URI.create(aiApiUrl + "/v2/lm/configurations")) + .header("Authorization", "Bearer " + token) + .header("AI-Resource-Group", resourceGroup) + .GET() + .build(), + HttpResponse.BodyHandlers.ofString()); + + Map cfgResult = MAPPER.readValue(cfgResponse.body(), new TypeReference<>() {}); + List> configurations = + MAPPER.convertValue(cfgResult.get("resources"), new TypeReference<>() {}); + assertThat(configurations) + .as( + "No rpt-1 configuration found in resource group " + + resourceGroup + + " — cannot create a deployment. Ensure the configuration exists.") + .isNotNull() + .isNotEmpty(); + + String configurationId = + configurations.stream() + .filter(c -> c.get("name") != null && c.get("name").toString().contains("rpt-1")) + .map(c -> c.get("id").toString()) + .findFirst() + .orElseThrow( + () -> + new AssertionError( + "No rpt-1 configuration found in resource group: " + resourceGroup)); + + // Create the deployment + String createBody = MAPPER.writeValueAsString(Map.of("configurationId", configurationId)); + HttpResponse createResponse = + client.send( + HttpRequest.newBuilder() + .uri(URI.create(aiApiUrl + "/v2/lm/deployments")) + .header("Authorization", "Bearer " + token) + .header("Content-Type", "application/json") + .header("AI-Resource-Group", resourceGroup) + .POST(HttpRequest.BodyPublishers.ofString(createBody)) + .build(), + HttpResponse.BodyHandlers.ofString()); + + Map created = MAPPER.readValue(createResponse.body(), new TypeReference<>() {}); + String deploymentId = created.get("id").toString(); + + // Poll until RUNNING + for (int i = 0; i < 10; i++) { + long delay = 300L * (1L << i); + System.out.printf( + "Waiting %dms for deployment %s to reach RUNNING (attempt %d/10)%n", + delay, deploymentId, i + 1); + Thread.sleep(delay); + + token = fetchToken(); + HttpResponse statusResponse = + client.send( + HttpRequest.newBuilder() + .uri(URI.create(aiApiUrl + "/v2/lm/deployments/" + deploymentId)) + .header("Authorization", "Bearer " + token) + .header("AI-Resource-Group", resourceGroup) + .GET() + .build(), + HttpResponse.BodyHandlers.ofString()); + + Map status = + MAPPER.readValue(statusResponse.body(), new TypeReference<>() {}); + if ("RUNNING".equals(status.get("status"))) { + return; + } + } + throw new AssertionError( + "Deployment " + deploymentId + " did not reach RUNNING within timeout"); + } + + /** Fetches a fresh OAuth token using service key credentials. */ + private String fetchToken() throws Exception { + String body = + "grant_type=client_credentials" + + "&client_id=" + + URLEncoder.encode(credentials.get("clientid").toString(), "UTF-8") + + "&client_secret=" + + URLEncoder.encode(credentials.get("clientsecret").toString(), "UTF-8"); + + HttpResponse response = + HttpClient.newHttpClient() + .send( + HttpRequest.newBuilder() + .uri(URI.create(credentials.get("url") + "/oauth/token")) + .header("Content-Type", "application/x-www-form-urlencoded") + .POST(HttpRequest.BodyPublishers.ofString(body)) + .build(), + HttpResponse.BodyHandlers.ofString()); + + Map data = MAPPER.readValue(response.body(), new TypeReference<>() {}); + return data.get("access_token").toString(); + } +} diff --git a/srv/src/test/java/com/sap/cds/feature/ai/client/MockAIClientTest.java b/srv/src/test/java/com/sap/cds/feature/ai/client/MockAIClientTest.java new file mode 100644 index 0000000..b9649ec --- /dev/null +++ b/srv/src/test/java/com/sap/cds/feature/ai/client/MockAIClientTest.java @@ -0,0 +1,146 @@ +/* + * © 2026 SAP SE or an SAP affiliate company and cds-feature-ai contributors. + */ +package com.sap.cds.feature.ai.client; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class MockAIClientTest { + + private MockAIClient cut; + + @BeforeEach + void setup() { + cut = new MockAIClient(); + } + + @Test + void noRowsReturnsEmpty() { + List> result = + cut.fetchPredictions(new ArrayList<>(), List.of("genre_ID"), null); + assertThat(result).isEmpty(); + } + + @Test + void rowWithoutPredictPlaceholderIsSkipped() { + Map row = new HashMap<>(); + row.put("ID", "id-1"); + row.put("genre_ID", 10); + + List> result = + cut.fetchPredictions(List.of(row), List.of("genre_ID"), null); + + assertThat(result).isEmpty(); + } + + @Test + void rowWithPredictPlaceholderReturnsPrediction() { + Map contextRow = new HashMap<>(); + contextRow.put("ID", "id-1"); + contextRow.put("genre_ID", 10); + + Map predictRow = new HashMap<>(); + predictRow.put("ID", "id-2"); + predictRow.put("genre_ID", "[PREDICT]"); + + List> result = + cut.fetchPredictions(List.of(contextRow, predictRow), List.of("genre_ID"), null); + + assertThat(result).hasSize(1); + assertThat(result.get(0).get("ID")).isEqualTo("id-2"); + + @SuppressWarnings("unchecked") + List> preds = (List>) result.get(0).get("genre_ID"); + assertThat(preds).hasSize(1); + assertThat(preds.get(0).get("prediction")).isEqualTo(10); + } + + @Test + void predictionPicksValueFromContextRows() { + Map c1 = new HashMap<>(); + c1.put("ID", "id-1"); + c1.put("genre_ID", 10); + + Map c2 = new HashMap<>(); + c2.put("ID", "id-2"); + c2.put("genre_ID", 20); + + Map predictRow = new HashMap<>(); + predictRow.put("ID", "id-3"); + predictRow.put("genre_ID", "[PREDICT]"); + + List> result = + cut.fetchPredictions(List.of(c1, c2, predictRow), List.of("genre_ID"), null); + + assertThat(result).hasSize(1); + @SuppressWarnings("unchecked") + List> preds = (List>) result.get(0).get("genre_ID"); + assertThat(preds.get(0).get("prediction")).isIn(10, 20); + } + + @Test + void multipleColumnsEachGetPrediction() { + Map contextRow = new HashMap<>(); + contextRow.put("ID", "id-1"); + contextRow.put("genre_ID", 10); + contextRow.put("currency_code", "EUR"); + + Map predictRow = new HashMap<>(); + predictRow.put("ID", "id-2"); + predictRow.put("genre_ID", "[PREDICT]"); + predictRow.put("currency_code", "[PREDICT]"); + + List> result = + cut.fetchPredictions( + List.of(contextRow, predictRow), List.of("genre_ID", "currency_code"), null); + + assertThat(result).hasSize(1); + Map prediction = result.get(0); + assertThat(prediction).containsKey("genre_ID"); + assertThat(prediction).containsKey("currency_code"); + } + + @Test + void noContextValuesResultsInNullPrediction() { + // Only the predict row, no context rows with real values + Map predictRow = new HashMap<>(); + predictRow.put("ID", "id-1"); + predictRow.put("genre_ID", "[PREDICT]"); + + List> result = + cut.fetchPredictions(List.of(predictRow), List.of("genre_ID"), null); + + assertThat(result).hasSize(1); + @SuppressWarnings("unchecked") + List> preds = (List>) result.get(0).get("genre_ID"); + assertThat(preds.get(0).get("prediction")).isNull(); + } + + @Test + void multipleRowsWithPredictEachGetPredicted() { + Map contextRow = new HashMap<>(); + contextRow.put("ID", "id-1"); + contextRow.put("genre_ID", 10); + + Map predictRow1 = new HashMap<>(); + predictRow1.put("ID", "id-2"); + predictRow1.put("genre_ID", "[PREDICT]"); + + Map predictRow2 = new HashMap<>(); + predictRow2.put("ID", "id-3"); + predictRow2.put("genre_ID", "[PREDICT]"); + + List> result = + cut.fetchPredictions( + List.of(contextRow, predictRow1, predictRow2), List.of("genre_ID"), null); + + assertThat(result).hasSize(2); + } +} diff --git a/srv/src/test/java/com/sap/cds/feature/ai/client/setup/AICoreSetupHandlerTest.java b/srv/src/test/java/com/sap/cds/feature/ai/client/setup/AICoreSetupHandlerTest.java new file mode 100644 index 0000000..5d40fd7 --- /dev/null +++ b/srv/src/test/java/com/sap/cds/feature/ai/client/setup/AICoreSetupHandlerTest.java @@ -0,0 +1,216 @@ +/* + * © 2026 SAP SE or an SAP affiliate company and cds-feature-ai contributors. + */ +package com.sap.cds.feature.ai.client.setup; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assumptions.assumeTrue; +import static org.mockito.Mockito.*; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.sap.cds.feature.ai.client.AICoreClient; +import com.sap.cds.services.environment.CdsEnvironment; +import com.sap.cds.services.mt.SubscribeEventContext; +import com.sap.cds.services.mt.UnsubscribeEventContext; +import java.net.URI; +import java.net.URLEncoder; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Integration test verifying the full AICoreSetup lifecycle against a real AI Core instance. + * Requires an AI Core service instance bound to the app (VCAP_SERVICES). + */ +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +class AICoreSetupHandlerTest { + + private static final String TEST_TENANT = "it-test-tenant-" + System.currentTimeMillis(); + private static final String TENANT_LABEL_KEY = "ext.ai.sap.com/CDS_TENANT_ID"; + private static final ObjectMapper MAPPER = new ObjectMapper(); + private static final Logger logger = LoggerFactory.getLogger(AICoreSetupHandlerTest.class); + + private AICoreSetupHandler cut; + private AICoreClient client; + private Map credentials; + private String aiApiUrl; + + @BeforeAll + void setup() throws Exception { + String vcap = System.getenv("VCAP_SERVICES"); + String serviceKey = null; + if (vcap != null) { + Map vcapServices = MAPPER.readValue(vcap, new TypeReference<>() {}); + List> aicoreBindings = + MAPPER.convertValue(vcapServices.get("aicore"), new TypeReference<>() {}); + if (aicoreBindings != null && !aicoreBindings.isEmpty()) { + serviceKey = MAPPER.writeValueAsString(aicoreBindings.get(0).get("credentials")); + } + } + assumeTrue( + serviceKey != null, "Skipping integration test: VCAP_SERVICES with aicore binding not set"); + + credentials = MAPPER.readValue(serviceKey, new TypeReference<>() {}); + aiApiUrl = ((Map) credentials.get("serviceurls")).get("AI_API_URL").toString(); + + System.setProperty("cds.multitenancy.enabled", "true"); + CdsEnvironment environment = mock(CdsEnvironment.class); + cut = new AICoreSetupHandler(environment); + client = new AICoreClient(cut); + } + + @AfterAll + void tearDown() { + System.clearProperty("cds.multitenancy.enabled"); + } + + /** + * Full lifecycle: 1. Subscribe → resource group created online + in local cache 2. + * fetchPredictions → RPT-1 deployment created online + in local cache 3. Unsubscribe → resource + * group deleted online + removed from both caches + */ + @Test + void lifecycle_subscribeCreatesPredictCreatesDeploymentUnsubscribeDeletesAll() throws Exception { + + // ── 1. Subscribe ────────────────────────────────────────────────────── + SubscribeEventContext subCtx = mock(SubscribeEventContext.class); + when(subCtx.getTenant()).thenReturn(TEST_TENANT); + cut.afterSubscribe(subCtx); + + String token = fetchToken(); + String resourceGroupId = findResourceGroupByTenant(token, TEST_TENANT); + assertThat(resourceGroupId) + .as("Resource group should exist online after subscribe") + .isNotNull(); + assertThat(cut.getTenantResourceGroupCache()) + .as("Resource group should be cached after subscribe") + .containsKey(TEST_TENANT); + + // ── 2. fetchPredictions ─────────────────────────────────────────────── + // This triggers RPT-1 deployment creation + polling until RUNNING. + // The inference call itself may fail (due to no meaningful data) but the deployment + // must be RUNNING before inference is attempted. + try { + client.fetchPredictions( + List.of(Map.of("ID", "1", "title", "test book")), List.of("genre"), TEST_TENANT); + } catch (RuntimeException e) { + // Inference errors are acceptable; we only assert the deployment was created. + } + + token = fetchToken(); + String deploymentId = findDeploymentForResourceGroup(token, resourceGroupId); + assertThat(deploymentId) + .as("RPT-1 deployment should exist online after fetchPredictions") + .isNotNull(); + assertThat(cut.getResourceGroupDeploymentCache()) + .as("Deployment should be cached after fetchPredictions") + .containsEntry(resourceGroupId, deploymentId); + + // ── 3. Unsubscribe ──────────────────────────────────────────────────── + UnsubscribeEventContext unsubCtx = mock(UnsubscribeEventContext.class); + when(unsubCtx.getTenant()).thenReturn(TEST_TENANT); + cut.beforeUnsubscribe(unsubCtx); + + // Caches are cleared synchronously + assertThat(cut.getTenantResourceGroupCache()) + .as("Resource group should be removed from cache after unsubscribe") + .doesNotContainKey(TEST_TENANT); + assertThat(cut.getResourceGroupDeploymentCache()) + .as("Deployment should be removed from cache after unsubscribe") + .doesNotContainKey(resourceGroupId); + + // AI Core deletes resource groups asynchronously — poll until gone + waitUntilResourceGroupGone(TEST_TENANT); + } + + // ── helpers ────────────────────────────────────────────────────────────── + + private void waitUntilResourceGroupGone(String tenant) throws Exception { + long delay = 500; + int maxRetries = 10; + for (int i = 0; i < maxRetries; i++) { + Thread.sleep(delay); + String id = findResourceGroupByTenant(fetchToken(), tenant); + if (id == null) return; + logger.debug( + "Resource group still present after unsubscribe, retrying in {} ms ({}/{})", + delay * 2, + i + 1, + maxRetries); + delay *= 2; + } + assertThat(findResourceGroupByTenant(fetchToken(), tenant)) + .as("Resource group should be gone online after unsubscribe") + .isNull(); + } + + private String findResourceGroupByTenant(String token, String tenant) throws Exception { + String encoded = URLEncoder.encode(TENANT_LABEL_KEY + "=" + tenant, "UTF-8"); + HttpResponse response = + HttpClient.newHttpClient() + .send( + HttpRequest.newBuilder() + .uri(URI.create(aiApiUrl + "/v2/admin/resourceGroups?labelSelector=" + encoded)) + .header("Authorization", "Bearer " + token) + .GET() + .build(), + HttpResponse.BodyHandlers.ofString()); + Map result = MAPPER.readValue(response.body(), new TypeReference<>() {}); + List> resources = + MAPPER.convertValue(result.get("resources"), new TypeReference<>() {}); + if (resources == null || resources.isEmpty()) return null; + return resources.get(0).get("resourceGroupId").toString(); + } + + private String findDeploymentForResourceGroup(String token, String resourceGroupId) + throws Exception { + HttpResponse response = + HttpClient.newHttpClient() + .send( + HttpRequest.newBuilder() + .uri(URI.create(aiApiUrl + "/v2/lm/deployments")) + .header("Authorization", "Bearer " + token) + .header("AI-Resource-Group", resourceGroupId) + .GET() + .build(), + HttpResponse.BodyHandlers.ofString()); + Map result = MAPPER.readValue(response.body(), new TypeReference<>() {}); + List> resources = + MAPPER.convertValue(result.get("resources"), new TypeReference<>() {}); + if (resources == null || resources.isEmpty()) return null; + return resources.stream() + .filter(d -> "RUNNING".equals(d.get("status")) || "PENDING".equals(d.get("status"))) + .findFirst() + .map(d -> d.get("id").toString()) + .orElse(null); + } + + private String fetchToken() throws Exception { + String body = + "grant_type=client_credentials" + + "&client_id=" + + URLEncoder.encode(credentials.get("clientid").toString(), "UTF-8") + + "&client_secret=" + + URLEncoder.encode(credentials.get("clientsecret").toString(), "UTF-8"); + HttpResponse response = + HttpClient.newHttpClient() + .send( + HttpRequest.newBuilder() + .uri(URI.create(credentials.get("url") + "/oauth/token")) + .header("Content-Type", "application/x-www-form-urlencoded") + .POST(HttpRequest.BodyPublishers.ofString(body)) + .build(), + HttpResponse.BodyHandlers.ofString()); + Map data = MAPPER.readValue(response.body(), new TypeReference<>() {}); + return data.get("access_token").toString(); + } +}