5

Developing CAP-Based Fiori App(Draft-Enabled) with Node.js and VSCode

 1 year ago
source link: https://blogs.sap.com/2023/05/15/developing-cap-based-fiori-appdraft-enabled-with-node.js-and-vscode/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
May 15, 2023 8 minute read

Developing CAP-Based Fiori App(Draft-Enabled) with Node.js and VSCode

Introduction

In this blog, I will try to show you how you can start developing CAP-based Fiori apps. My purpose is to learn and share the basics of CAP application building. I’m just getting started with developing cap applications, so any advice or feedback is really appreciated.

You will learn below topics;

  • Developing a basic CAP Application
  • Consuming CAP Project for Fiori Environment
  • UI Annotations, Code Lists, and Extending ApplicationService

Prerequisites

Steps

  1. Node.js
  2. Adding CAP Tools
  3. Visual Studio Code and Extensions
  4. Creating CAP Project in VSCode
  5. Creating Model/Schema
  6. Define the Service
  7. Create Fiori Project and in VSCode
  8. Prepare the UI Annotations
  9. Implementing Events and Testing the App

Step 1 – Node.JS

After downloading and installing Node.js packages please use the below shell/bash command to verify whether Node.js packages are correctly installed or not

node --version

You should get an output like this:

v18.12.1

Step 2 – Adding CAP Tools

Shall/Bash command for installing CAP tools:

npm install –global @sap/cds-dk

The version check for CAP tools is correctly installed:

cds --version

You should get an output like this:

1-51.png

Step 3 – Visual Studio Code and Extensions

After downloading and installing VS Code, there are some required extensions for developing CAP applications. You can install all the extensions I have in the screenshot but not all of them are required. I am sharing all the extensions because they can also be helpful to use other SAP tools. I would suggest you download all the extensions below.

2-22.png

Step 4 – Creating CAP Project in VSCode

The first step is creating a folder wherever you want in your workspace. In my case, I have created a folder called “CAP Tutorial” on my desktop.2023-05-09-13_37_28-Realtek-Audio-Console-1.png

After creating the document, you can open VSCode. Then you click “Open Folder” and select the folder you created.

3-24.png

After selecting the folder, you will see your workspace like this:

4-15.png

You can now start adding project files manually or via command lines. I will show you how to create and set up necessary packages with command line inputs.

In VS Code choose Terminal → New Terminal from its menu then you will see the command line prompt screen in the lower right part of the VS Code screen

5-13.png

Create a new folder for our project:

mkdir captravel

Switch to the project folder you created:

cd captravel

Create an initial CAP project by executing the below command:

cds init

Install npm packages:

npm install

The project looks like this in VSCode:

6-12.png

You can now start your local CAP servers with the below command:

cds watch

After executing the above command you will get an error like this but do not worry because you do not have any model yet.

2023-05-09-14_02_39-CAP-Tutorial-Visual-Studio-Code-1.png

NOTE: if you want to stop your local CAP server hit “ctrl + c”

Step 5 – Creating Model/Schema

In the VSCode, create a file called “schema.cds” under the file “captravel/db” folder and you can create your DB model.

Here is the database model I have used for Travel App:

using { Currency, managed, sap.common.CodeList } from '@sap/cds/common';

namespace captravel;

// Travel Entity - Parent
entity Travel : managed {
    key TravelUUID : UUID;
    TravelID       : Integer @readonly;
    BeginDate      : Date;
    EndDate        : Date;
    TravelPrice    : Decimal(16,2) @Measures.ISOCurrency: TravelCurrency_code;
    TravelCurrency : Currency;
    Description    : String(255);
    to_Booking     : Composition of many Booking on to_Booking.to_Travel = $self;
}

// Booking Entity - Child
entity Booking: managed {
    key BookingUUID : UUID;
    BookingID       : Integer @readonly;
    BookingDate     : Date;
    ConnectionID    : String(4);
    FlightDate      : Date;
    FlightPrice     : Decimal(16,2) @Measures.ISOCurrency: FlightCurrency_code;
    FlightCurrency  : Currency;
    BookingStatus   : Association to BookingStatus;
    to_Travel       : Association to Travel;
}

// Code List
entity BookingStatus : CodeList {
  key Code : String enum {
    New      = 'N';
    Booked   = 'B';
    Canceled = 'C';
  };
};

Step 6 – Define the service

Create a file called “service.cds” under the “captravel/srv” folder

using { captravel as my } from '../db/schema';

service TravelService {
    @odata.draft.enabled //Enable Draft
    entity Travel as projection on my.Travel;
    entity Booking as projection on my.Booking;
}

After the above step, you can now again start “cds watch” command and see the changes below address(http://localhost:4004/)

7-11.png

You will see the result like this.

8-13.png

So you can fill some entities with initial data if you would like by creating a “data” folder under the “captravel/db” as shown below.

We will insert data for Travel and Booking entities via the Fiori app when we are done with the tutorial so we can fill entities Currencies and BookingStatus for now.

Create CSV files and fill the files:

9-12.png

IMPORTANT NOTE: Naming standard for the data files is so important to get the results correctly. If you use Common Reuse Types like Countries, Currencies, and Languages or Code Lists like BookingStatus you have to use its namespaces while naming the .csv files. For detailed information please visit the below addresses

Reuse Types

Code Lists

captravel-BookingStatus.csv:

code;name
N;New
X;Canceled
B;Booked

sap.common.Currencies.csv:

code;symbol;name;descr
EUR;€;Euro;European Euro
USD;$;US Dollar;United States Dollar
CAD;$;Canadian Dollar;Canadian Dollar
AUD;$;Australian Dollar;Australian Dollar
GBP;£;British Pound
ILS;₪;Shekel
INR;₹;Rupee;Indian Rupee
QAR;﷼;Riyal;Katar Riyal
SAR;﷼;Riyal;Saudi Riyal
JPY;¥;Yen;Japanese Yen
CNY;¥;Yuan;Chinese Yuan Renminbi
SGD;S$;Singapore Dollar;Singapore Dollar
ZAR;R;Rand;South African Rand

Now you can see the results if you click on the entities Currencies or BookinStatus

BookingStatus2023-05-09-18_01_26-localhost_4004_travel_BookingStatus-1.png

Currencies

2023-05-09-18_02_03-localhost_4004_travel_Currencies-1.png

Step 7 – Create Fiori Project in VSCode

In the VSCode, go “View->Command Palette” or “CTRL+SHIFT+P” and launch the Application generator

2023-05-09-18_08_55-CAP-Tutorial-Visual-Studio-Code-1.png

Select SAP Fiori Elements Templates and List Report Page Template

2023-05-09-18_10_08-Template-Wizard-CAP-Tutorial-Visual-Studio-Code-1.png

In the next screen, select “Use Local CAP Project” as a data source, select the path of your CAP Application, and select the service as shown below

2023-05-09-18_13_06-Template-Wizard-CAP-Tutorial-Visual-Studio-Code-1.png

In the next screen, you can choose your main entity and navigation entity as shown below

2023-05-09-18_15_15-Template-Wizard-CAP-Tutorial-Visual-Studio-Code-1.png

In the last screen, you can now set the project attributes and click the finish button

2023-05-09-18_17_06-Template-Wizard-CAP-Tutorial-Visual-Studio-Code-1.png

After successfully creating the project you will see the app is created under the app folder like this

2023-05-09-18_20_20-CAP-Tutorial-Visual-Studio-Code-1.png

After creating the Fiori app, set the creation mode as inline for the booking entity in the VSCode Page Editor tool as shown below

2023-05-10-11_04_32-Page-Editor-travelfioriapp-CAP-Tutorial-Visual-Studio-Code-2.png

Step 8 – Prepare the UI Annotations

At the same level(under “captravel/srv”) create a file called “service-ui.cds” for the annotations

using TravelService from './service';

annotate TravelService.Travel with{
    TravelID        @title : 'Travel ID';
    BeginDate       @title : 'Begin Date';
    EndDate         @title : 'End Date';
    TravelPrice     @title : 'Price';
    TravelCurrency  @title : 'Currency';
    Description     @title : 'Description';
    to_Booking      @title : 'Bookings';
}

annotate TravelService.Booking with{
    BookingID       @title : 'Booking ID';
    BookingDate     @title : 'Booking Date';
    ConnectionID    @title : 'Connection ID';
    FlightDate      @title : 'Flight Date';
    FlightPrice     @title : 'Flight Price';
    FlightCurrency  @title : 'Currency';
}

annotate TravelService.Travel with @(
    UI: {
        HeaderInfo: {
			TypeName: 'Travel',
			TypeNamePlural: 'Travels',
			Title          : {
                $Type : 'UI.DataField',
                Value : TravelID
            },
			Description : {
				$Type: 'UI.DataField',
				Value: Description
			}
		},
        SelectionFields: [TravelID],
        LineItem:[
            {Value: TravelID},
            {Value: BeginDate},
            {Value: EndDate},
            {Value: TravelPrice},
            {Value: Description}
        ],
        Facets: [
            {$Type: 'UI.ReferenceFacet', Label: 'Main', Target: '@UI.FieldGroup#Main'},
            {$Type: 'UI.ReferenceFacet', Label: 'Flights', Target: 'to_Booking/@UI.LineItem' }
        ],
        FieldGroup#Main: {
            Data: [
                {Value: TravelID},
                {Value: BeginDate},
                {Value: EndDate},
                {Value: TravelPrice},
                {Value: Description}
            ]
        }
    }
){};

annotate TravelService.Booking with @(
    UI: {
        LineItem: [
            {Value: BookingID},
            {Value: BookingDate},
            {Value: ConnectionID},
            {Value: FlightDate},
            {Value: FlightPrice},
            {Value: BookingStatus_Code, Label: 'Booking Status'}
        ]
    }
){};

You can now check your service and you will see the web application link on your local as shown below

2023-05-09-18_25_06-captravel-1.0.0-2.png
2023-05-09-18_26_35-Travels-1.png

Step 9 – Implementing Events and Testing the App

You can start testing at this point but we are not done yet. Let’s calculate/set some fields when the draft is active.

As you may already notice the app has UUID fields for key management, we don’t have to do anything for the UUID fields but we have two fields that need to be calculated which are “TravelID” and “BookingID”. We have to code “service.js” file under the “captravel/srv” folder for the calculation or setting fields.

As you can see in the code, there are events we can use for our needs. I have used the below events but you can check the event list here.

const cds = require('@sap/cds');

class TravelService extends cds.ApplicationService{
    async init(){
        const { Travel, Booking } = this.entities;

        this.before('NEW', Travel, async req => {
            const { maxID } = await SELECT.one `max(TravelID) as maxID` .from (Travel)
            req.data.TravelID = maxID + 1
        } )

        this.before('NEW', Booking, async req => {
            const { to_Travel_TravelUUID } = req.data
            const { maxID } = await SELECT.one `max(BookingID) as maxID` .from (Booking.drafts) .where ({to_Travel_TravelUUID})
            req.data.BookingID = maxID + 1
            req.data.BookingStatus_code = 'N'
            req.data.BookingDate = (new Date).toISOString().slice(0,10)
        } )

        await super.init()
    }
}

module.exports = TravelService

You can now test the app and see the results

Execute “cds watch” and go http://localhost:4004, then click your web application

2023-05-10-11_34_23-captravel-1.0.0-1.png

You are ready for the CRUD operations and testing of the app.

2023-05-10-11_39_15-Travels-1.png

You can fill in the data

2023-05-10-11_42_07-Travels-2.png

You can also see the Booking Status(Code List) has been loaded automatically

2023-05-10-11_46_30-Travels-1.png

The data I have created and the general view of the app

2023-05-10-11_48_01-Travels-1.png

Conclusion

In this blog, I have explained how to develop CAP-Based Fiori Applications with draft capabilities. This article can be used as a starting point. I’ll try to write a blog in the future where I explain the subject in more detail.

References


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK