Thursday, May 31, 2018

Notes Series : ODATA Part1

ODATA

ODATA is the means to create one kind of RESTFUL API.
API is a code that allows two S/W programs to communicate with each other.
RESTFUL – representational state transfer is a style of developing web services.
In contrast to SOAP which is action based (get an employee, get a product, get sales order), REST is resource based (employee, product, sales order).

REST Principles

1.        Everything is a resource and it is identified by URI (unique resource identifier) which is a form or URL.
URL: hostname: port no of hub/service name/resource name
2.        When a resource is requested a representation or copy is sent in XML or JSON format

REST Constraints

1.       Uniform Interface – Architecture can evolve independently. Separation of display and business logic.  Irrespective of display logic, business logic uses following HTTP methods.
a.       Create -> POST
b.      Read ->GET
c.       Update->PUT
d.      Delete->DELETE
2.       Stateless – After server sends a response to a request, it does not hold a session or user-related information.
3.       Client Server-Uniform interface separates client & server, as a result, frontend can be replaced easily, flexibility to customers to choose UI of their own choice
4.       Cacheable – Cache memory can hold server response
5.       Layered system – Client should not assume it interacts with the server directly, there can be middle layers

SAP NetWeaver Gateway

 Simple way to connect devices, environments & platforms to SAP s/w.
SAP Gateway Service Builder:
TCode : SEGW
Below 7.4
1.       Gateway core -GW_CORE
2.       Business enablement provisioning -IW_BEP
3.       Foundation- IW_FND
Above 7.4
SAP_GWFND -> Gateway foundation
Possible architecture
1.       Hub architecture (Gateway hub where service is built in a separate system than business suite where implementation is done)
2.       Embedded architecture (both service and implementation in the business suite)

Standard Steps
1.       The consumer sends HTTP request
2.       Registered service in the gateway is called (/IWEND/MAINT_SERVICE)
3.        ODATA service called through RFC from the backend

Entity data model

1.       Entity type: required structure/ bunch of named properties with associated data types
2.       Entity: Instance of entity type
3.       Association
4.       Entity Sets: Set of Entity records

Design Approach

1.        Create a structure with required fields.
2.       Create an ODATA project in SEGW
A project has
a.       Data model: Entity type, Association, Entity Sets
b.       Service implementation
c.       Runtime Artifacts
d.       Service maintenance
3.       In data model import the created structure, choose key fields
4.       Generate runtime artifacts.
It creates the following:
a.       Model provider class (_MPC, _MPC_EXT)
                                                               i.      MPC is the runtime object for design time modeling
ii.      MPC extension is used when design-time environment needs to be changed at runtime. Redefine the method.
b.       Data provider class (_DPC, _DPC_EXT)
                                                               i.      <Entity_Set>_create_entity ->HTTP POST
                                                             ii.      <Entity_Set>_delete_entity   ->HTTP DELETE
                                                           iii.      <Entity_Set>_update_entity   ->HTTP PUT
                                                           iv.      <Entity_Set>_get_entity          ->HTTP GET
c.       Service registration (_MDL, _SRV)
5.       Register service
a.       Using tcode /IWFND/MAINT_SERVICE, add the service
b.       It creates a SICF node which is needed for all web based apps
6.       Gateway client
a.       Using tcode /IWFND/GW_CLIENT test a service
b.       URI path:
Hostinfo/path/servicename

Modeling Techniques

1.       Inside Out
Create service out of existing business component (function module, classes)
2.       Outside In

Look at service/ app first, then think of business component to fulfill a need., if business component is not optimized then don’t use it. Go for the custom component. UI enforces business logic here

Wednesday, May 30, 2018

Notes Series : LUW, Lock Objects & Memory


Logical Unit of Work
_________________________________________

Application programs/database transactions (sequence of actions belonging together) can change database tables. Time span in which one consistent state is transferred to another consistent state (or changes thrown back/rolled back) is called LUW.
It guarantees database integrity through locking mechanism to protect transaction integrity (as SAP is a multi-user system).

Types-

1.       DB LUW – Realized by database system with the help of database lock.
Data base transaction refers to non-separable sequence of database operations.
Database commit:
a.       Implicit
a.       Completion of a dialog step
b.       Synchronous or asynchronous function call
c.       Completion of a function module call
d.       Wait up to, wait for
e.       Sending errors , warnings
b.       Explicit
a.       Database specific native SQL  statements
b.       Between Exec-End exec statement
c.       Calling function module DB_COMMIT
d.       Using Open SQL statement Commit Work
Commit not allowed in AMDP methods.

2.       SAP LUW- Set of DB LUW(Several dialog steps combined, set of tasks combined).  Done using ABAP technique with help of SAP Lock.
a.       Using Bundling technique
                                                               i.      Update function call – All database operation executed in update work process
                                                             ii.      TRFC function call
                                                           iii.      Subroutine call using perform.. on commit.
b.       Commit work makes end of SAP LUW
c.       All changes are written to database in final DB LUW

Lock Objects
______________________________________

 Lock objects helps in integrity when there is simultaneous access of same data records by several users.
When a lock object(EZ_<LOCK>) is created it creates ENQUEUE_<LOCK>, DEQUEUE_<LOCK> function modules. These function modules/group are not transported, rather when lock object transported , it regenerates them in target system.

Lock Mode

1.       Shared or Read Lock
2.       Exclusive and cumulative or Write Lock
3.       Exclusive but not cumulative – only once per transaction

Lock Arguments

1.       Key fields form the lock arguments
2.       It defines which set of data records to be blocked

Lock Table

1.       In main memory of enqueue server records of current lock in the system with owner, lock mode, fields are saved.

Scope

1.       Dialog owner
2.       Update Owner
3.       Both Owners

Update
_________________________________________

 When time consuming changes are made to database, process is carried asynchronously by update work process.
Types
1.       Time critical V1 update -> primary changes (synchronous)
a.       Processed in single update work process in single DB LUW. Executed under SAP Lock.
2.       Non time critical (statistical or V1 dependent) V2 update (Asynchronous)
Update request is triggered from Dialog server and it decides which update server to use.

Work Processors(Screen processor, ABAP interpreter, DB Task handler)
_______________________________________________________________

 All requests that comes in from presentation server are written to a dispatcher queue. Then the dispatcher pulls them in FIFO to first available work process which handles one request at a time.

1.       Dialog WP handles online jobs, interactive request
2.       Update WP saves data in DB using V1 & V2 Update
3.       Background WP
4.       Spool WP
5.       Enqueue WP
6.       Message WP
7.       Gateway WP

Memory
__________________________________________

1.       ABAP Memory

a.       Import/Export
b.       Within a session
c.       Values stored in SPARAM
d.       Export<> to memory id<>
e.       Import<> to <> from memory id <>
f.        Useful when 2 reports use same top include, Parameter ID TPARA

2.       SAP Memory

a.       SET/GET
b.       Session to Session
c.       Can’t carry table data, only field values
d.       Remain until over written or deleted, so clear it before initial use
e.       Set parameter id <> field <>
f.        Get parameter id <> field <>


Notes Series : Order to Cash And Simple Finance


Finance Basics:
Basic Accounting:
Accounting is the economic information meant for informed judgement
Basic equation
Asset = Liability +Equity +Revenue -Expenditure -Dividend
Where Asset->generates future revenue
Liability ->Obligations
Equity->Owner’s claim
Revenue->Increase in ownership claim
Expenditure->Decrease in ownership claim

Debit Entry (Left hand side)->Increase in Asset/Expense Or Decrease in liability/equity
Credit Entry(Right hand side)->Increase in liability/Equity Or Decrease in Asset/Expense
General rule of debit & credit (No logic behind)
A
=
L
E
Dr(+)        Cr(-)

Dr(-)        Cr(+)
Dr(-)        Cr(+)

Examples:
Sale for cash: Cash(Dr)|Revenue(Cr)
Sale on credit: Account Receivable(Dr)|Revenue(Cr)

Balance sheet  :  financial position on a certain date (Liability & Equity)
P&L : Income statement for a particular period(Revenue & Expense)
Financial Accounting is meant for people out side the organization to evaluate.
Management Accounting is meant for management for investment decisions.
Retained Earnings: Undisputed profit excluding owner’s capital
Cash Flow : Operating activities, Investing activities, Financing activities
Account Receivables : Amount due from customers
Account Payable: Amount owed to vendors

Order to cash process: Finance perspective
1.       Sales Team coordinates with customer to finalize a deal.
(Sales enquiry by customer(VA11), legally binding offer-sales quotation(VA21),Formal request to vendor-Purchase order(ME21),Order issued to customer-Sales order(VA01))
Sales order creation-Material check(not available->MM, Available->PP), tables VBAK, VBAP
2.       Out Bound delivery(VL01N) Tables LIKP, LIPS
a.       Picking from company ware house
b.       Packing in container
c.       Loading for transport, ready for delivery
d.       Logistics for shipment
3.       Dispatch Goods (move out of company premise)
a.       Physical inventory reduced
b.       Inventory credited and COGS debited
4.       Bill sent to customers (VBRK, VBRP)
a.       Finance department records sales & increases accounts receivables
Billing document(VBRK,VBRP)VF01
Invoice Document(BKPF,BSEG) VF21
Created with reference to delivery document.
It’s a sales document not a account document
It’s the document which requests for payment for the goods supplied
When billing document is released automatically an accounting document gets created.
It’s a commercial document with details like product, quantity , agreed price etc.


5.       After customer makes payment
a.       Finance department reduces account payable, increase in bank balance
b.       No payment received->Dunning & write-off


Simple Finance
Earlier accounting transactions were getting stored in different finance tables. Therefore reconciliation needed for all components. One must check 2 set of records to check if transaction is correct or not. Reporting used to be difficult.
GL reconciliation from following 4 groups
Balance Sheet                                                                                                        Profit & Loss
Asset Accounting

Controlling

G/L Accounting

Material Ledger

Profitability

1.       GL Accounting Master data used to gets stored in SKA1 & SKB1.
2.       GL Accounting transaction data gets stored in BSIS & BSAS
3.       Account receivable information stored in BSIS & BSAD
4.       Account payable information stored in BSIK & BSAK
All these data linked to Accounting tables BKPF & BSEG through document number , year etc.
Submodules include
1.       G/L Acc
2.       Account Receivables
3.       Account Payables
4.       Asset Accounting
5.       Management Accounting
6.       Cash management
7.       Integrated business planning

With SFIN, there is emergence of Universal journal entry with one line item in table with full details of all components. No reconciliation needed as data stored only once. Only one document number for related components.
Universal Journal (ACDOCA)
G/L
Asset Accounting
Material Ledger
Controlling
COPA

Index tables such as BSAD, BSID, BSIK, BSAK, BSIS, BSAS removed and changed to views for support.
Aggregate tables removed.
GAAP standard 23 character currency field support & 6 digit document line item support.
Journal entry header exists in BKPF and item in ACDOCA for new transactions and in BSEG for old transactions.

Modules include:

1.       Universal journal
2.       Central finance
3.       New Asset accounting
4.       Cash management
5.       Controlling & Profitability Analysis COPA
6.       IBPF for finance

 (Similarly with new S4HANA paradigm the usual customer and Vendor creation tcodes(XK01 & XD01) are redirected to transaction for business partner (BP). New MATDOC table which holds data from around 26 tables. MATNR length changed from 18 to 40)

Notes Series : CDS view

DATA to CODE        VS    CODE to DATA

Earlier calculation logic used to be written on the application server, later with the invention of powerful HANA DB time-consuming calculation logic was pushed to database layer itself.

Bottom Up              VS     Top Down

Before 7.4 SP2 HANA view and Stored procedures were written on HANA layer and on application server they are consumed using External view and stored procedure proxy respectively.
Later with the help of CDS views and AMDP, it becomes possible to write the code in ABAP layer itself and push it down to HANA view & stored procedures in HANA layer.

CDS (Core data services)

Enhancement of SQL standard to define the semantically rich data model.
Go for it if functionality needed more than once else use direct SQL statement.

Value-add from SE11 views:
1.       Code to data paradigm/Code push down
2.       Complex expressions can be used
3.       The possibility of outer join
4.       Analytical adaptation
5.       Used for OData services
6.       Separate UI annotations & core functionality
7.       Built-in functions like Union, Union All, Intersection
8.       Parameters for dynamic selection

Annotations :

Annotations use metadata to enrich CDS objects. These data modifies the properties of the view and the behavior when accessed at runtime. These can be defined for entire CDS or elements of a SELECT statement.
During activation, annotations get saved in System tables & their system classes are available to evaluate them. ABAP annotations are evaluated directly by ABAP runtime environment during activation.

When a CDS view is created
1.       a DDL SQL view gets created which is visible in SE11 but can’t be edited
2.       a CDS VIEW ENTITY gets created which is the DDL source file (Actual view)

S4HANA virtual data model used to define the type of views.

1.      Interface View/Basic View->Directly access a DB master data table, reused by other CDS
2.       Composite View->Use of association, the composition of basic and other composite views (Just a guideline or convention)

3.       Consumption View->These are accessible to end user, exposed to ODATA





Example Basic View
@AbapCatalog.sqlViewName: 'YSD4_AIR_TEXT'
@AbapCatalog.compiler.compareFilter: true
@AccessControl.authorizationCheck: #CHECK
@EndUserText.label: 'Airline Text CDS'
@VDM.viewType: #BASIC
@Analytics.dataCategory: #DIMENSION
@Analytics.dataExtraction.enabled : true
@ObjectModel.representativeKey: 'Airline'


define view YCDS_airlineTXT as select from scarr

{
key scarr.carrid as airline,
@Semantics.text:true
@EndUserText.label : 'Airline Name'
scarr.carrname as AirlineName
   
}
Example of Basic view with association

@AbapCatalog.sqlViewName: 'YSD4_AIRLINE'
@AbapCatalog.compiler.compareFilter: true
@AccessControl.authorizationCheck: #NOT_REQUIRED
@EndUserText.label: 'Airline CDS'
@ObjectModel.dataCategory: #TEXT
@Analytics.dataExtraction.enabled: true
@VDM.viewType: #BASIC
@ObjectModel.representativeKey: 'Airline'

define view YCDS_airline as select from scarr
association [0..1] to YCDS_airline as _text
on $projection.Airline = _text.Airline
{
key scarr.carrid as Airline,
@Semantics.currencyCode: true
scarr.currcode as AirlineLocalCurrency,
@Semantics.url:true
scarr.url as AirlineURI,
_text
   
}
Example of Consumption view
@AbapCatalog.sqlViewName: 'YSD4_CAIRLINE'
@AbapCatalog.compiler.compareFilter: true
@AccessControl.authorizationCheck: #NOT_REQUIRED
@EndUserText.label: 'Airline Consumption View'
@VDM.viewType: #CONSUMPTION
@OData.publish: true
define view YCDS_C_Airline as select from YCDS_airline {
    //YCDS_airline
    key Airline,
    AirlineLocalCurrency,
    AirlineURI,
    /* Associations */
    //YCDS_airline
    _text
}
Example of CDS with parameter
@AbapCatalog.sqlViewName:’DEMO_INPUT_CDS’
    Define view demo_parameters_cds
    With parameters p_country:LAND1_GP,  p_region:REGIO
    as Select from KNA1
        { key kunnr,
                land1 as Country key,
                name1,
                ort01 as City,
                region as Region
        } where land1 = : p_country and regio = : p_region;