0% found this document useful (0 votes)
5 views68 pages

Complete Updated Rough

The project report details the development of the SAP BTP Order Processing Architecture with AI integration, aimed at modernizing B2B sales order management through a centralized digital platform. It addresses challenges such as order inaccuracies and operational inefficiencies by integrating various functional modules, including order management, credit control, and document intelligence, all supported by an AI-powered risk engine. The system enhances processing speed, transparency, and decision-making capabilities while ensuring data integrity and security through role-based access and automated processes.

Uploaded by

blesswinsj
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views68 pages

Complete Updated Rough

The project report details the development of the SAP BTP Order Processing Architecture with AI integration, aimed at modernizing B2B sales order management through a centralized digital platform. It addresses challenges such as order inaccuracies and operational inefficiencies by integrating various functional modules, including order management, credit control, and document intelligence, all supported by an AI-powered risk engine. The system enhances processing speed, transparency, and decision-making capabilities while ensuring data integrity and security through role-based access and automated processes.

Uploaded by

blesswinsj
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

SAP BTP ORDER PROCESSING ARCHITECTURE

WITH AI INTEGRATION

PROJECT REPORT

Submitted by
BLESSWIN SAM JACOB J
(Register No: 713524CA804)

Submitted to the
FACULTY OF COMPUTER APPLICATIONS

In partial fulfillment for the award of the degree


Of

MASTER OF COMPUTER APPLICATIONS


in

SNS COLLEGE OF TECHNOLOGY, COIMBATORE – 641035


(AN AUTONOMOUS INSTITUTION)

DEPARTMENT OF COMPUTER APPLICATIONS


MAY 2026
BONAFIDE CERTIFICATE

It is certified that this project report "SAP BTP ORDER PROCESSING ARCHITECTURE
WITH AI INTEGRATION" is the bonafide work of Mr. BLESSWIN SAM JACOB J, who
carried out this project work under my supervision. Certified further, that to the best of my
knowledge the work reported herein does not form part of any other project report or dissertation
on the basis of which a degree or award was conferred on an earlier occasion to this or any other
candidate.

HEAD OF THE DEPARTMENT PROJECT GUIDE

Submitted for the Viva-Voce examination held at SNS


COLLEGE OF TECHNOLOGY, held on .

INTERNAL EXAMINER EXTERNAL EXAMINER


DECLARATION

I, BLESSWIN SAM JACOB J, declare that this project work entitled "SAP BTP ORDER
PROCESSING ARCHITECTURE WITH AI INTEGRATION" submitted to SNS
COLLEGE OF TECHNOLOGY (AN AUTONOMOUS INSTITUTION), Coimbatore, in
partial fulfilment of the requirements for the award of Degree of MASTER OF COMPUTER
APPLICATIONS, is a record of original work done by me under the guidance of Ms. E.
YUVARANI, Assistant Professor of Master of Computer Applications, SNS COLLEGE OF
TECHNOLOGY, Coimbatore.

Place: Coimbatore Signature of the Candidate


Date: _________ ____________________
ACKNOWLEDGEMENT

First, I solicit my humble thanks to God Almighty for being with me, guiding me the right
way throughout my project work.

I express my heart-felt gratitude to the management of SNS College of Technology,


Coimbatore, Deiva Thiru Dr. S.N. SUBBRAMANIAN, Chairman, Dr. S. RAJALAKSHMI,
Correspondent, Dr. NALIN SNS, Technical Director for providing me with all sorts of support
in completion of this project.

I extend my sincere thanks to Dr. S. CHARLES, our Respected Principal, SNS College of
Technology, for the encouragement and facilities offered to complete this project.

I express my heartfelt thanks to Dr. S. SUNDARARAJAN, Professor and Head of the


Department of Master of Computer Applications for the encouragement and relevant instructions,
which made me to complete the project.

I also extend my thanks to my internal guide Ms. E. YUVARANI, Assistant Professor


of Master of Computer Applications, who paved the way for me to complete my project
successfully. Her instruction and presence has guided me a lot for completing the project.

Finally, I thank our parents for their financial and moral support and our friends who
helped us in completion of our project work successfully.
Mr. Blesswin Sam Jacob J
713524CA804
M.C.A
SNS College of Technology

Sub: Internship Approval - Regarding

I am pleased to inform you that after careful consideration, we have selected you for the Internship at
Markdot Intellect for the position ABAP Developer, we believe that your skills, qualifications, and enthusiasm
will make a valuable contribution to our team. The Internship starts from 05/01/2026. During this period,
you will be working closely with our team, whom will provide guidance and mentorship to ensure a
meaningful and educational experience.

UDYAM Reg. No: UDYAM-TN-03-0163347


Warm Regards,
2, Crystal Plaza, Near KCT Tech Park, Thudiyalur Main Road, Saravanampatti, For Markdot Intellect Ptd. Ltd.
Coimbatore, Tamilnadu-641035
Mob. +91 73732 72144 | +91 99440 01552
E-mail: contact@[Link] | Web: [Link]

Tharun Danial S
CEO
25/04/26

TO WHOM SO EVER IT MAY CONCERN

This is to certify that Mr. Blesswin Sam Jacob J (713524CA804, Master of Computer Applications) SNS
College of Technology, Coimbatore, has under gone internship training in our company from 05/01/26 to
25/04/26 as ABAP Developer.

During the internship in our company, his conduct and character are found very well, he is very industrious
and hard-working.

Warm Regards,
For Markdot Intellect Ptd. Ltd.

UDYAM Reg. No: UDYAM-TN-03-0163347


2, Crystal Plaza, Near KCT Tech Park, Thudiyalur Main Road, Saravanampatti,
Coimbatore, Tamilnadu-641035 Tharun Danial S
Mob. +91 73732 72144 | +91 99440 01552 CEO
E-mail: contact@[Link] | Web: [Link]
ABSTRACT
In the modern B2B commerce sector, businesses face increasing pressure to process sales orders
accurately, manage customer credit exposure, control inventory in real time, and maintain full
operational transparency across procurement and fulfillment workflows. Yet many organizations
still rely on disconnected systems or manual processes for order entry, stock tracking, document
handling, and approval routing. This fragmented approach often leads to credit overruns, stock
mismatches, delayed approvals, billing errors, and limited visibility into overall sales performance.
To address these challenges, this project introduces a centralized, role-based Order Management
Suite built on the SAP Business Technology Platform (BTP) that unifies customer management,
product cataloguing, order lifecycle processing, inventory control, document extraction, and
analytics into a single real-time digital platform for better efficiency, control, and decision-making.

The BTP Order Suite is a full-stack enterprise application designed to digitally connect and
streamline the complete B2B sales order workflow through six integrated functional areas: Order
Management, Customer and Credit Control, Product and Inventory Management, Document
Intelligence, AI-Powered Order Analysis, and Operations Dashboard. The Order Management
module supports the complete order lifecycle from draft creation through submission, approval,
fulfillment, shipment, and delivery, with auto-generated year-scoped order numbers, priority
classification, shipping details, and real-time GST-inclusive billing.

The Customer and Credit Control module manages customer master data, enforces credit limit
validation at order submission, reserves credit upon approval, and automatically releases it upon
delivery or cancellation. The Product and Inventory module maintains a SKU-based product
catalog with stock quantities and automatically deducts inventory on order approval while
restoring stock if an order is cancelled.

The Document Intelligence module integrates with SAP Document Information Extraction (DIEx)
to accept uploaded PDF documents- invoices, purchase orders, receipts, and bank statements - and
extract structured field data through asynchronous AI-powered processing jobs. The AI Order
Analysis module leverages a large language model to evaluate each order’s risk profile based on
credit exposure, customer history, delivery urgency, quantity anomalies, and product category mix,
generating a scored risk assessment with actionable discount recommendations and sales team
guidance.
The Operations Dashboard aggregates key performance indicators including revenue by region and
category, order status distribution, top customers by spend, monthly trends, and low-stock alerts
for informed management decision-making.

The system is built using the SAP Cloud Application Programming Model (CAP) with a [Link]
service layer exposing OData v4 APIs, a SAP HANA HDI database for persistent storage, and a
SAP UI5 Fiori Elements frontend for a consistent, responsive user interface. Business rules
including credit limit enforcement, stock validation, GST calculation, line item pricing, and order
total rollup are implemented as automated event hooks within the service layer, ensuring data
integrity without manual intervention.

A comprehensive audit trail records every order status transition, credit movement, and stock
adjustment with actor, timestamp, and before-after values for full operational traceability. The
application is secured through XSUAA OAuth2 with three role collections - Viewer, Editor, and
Admin - and deployed as a Multi-Target Application (MTA) on SAP BTP Cloud Foundry with
managed services for authentication, database, HTML5 hosting, and document extraction.

The system follows a role-based and session-secure architecture with API-driven communication
between modules, ensuring reliable coordination from customer order placement through credit
validation, inventory deduction, and fulfillment tracking. It also includes intelligent support
through an AI-assisted order risk engine that uses credit exposure, customer purchase history,
delivery windows, and product mix data to flag high-risk orders and suggest timely discount
decisions.

Overall, the project delivers a practical and scalable digital solution that improves order processing
speed, operational transparency, inventory accuracy, credit governance, and data-driven decision-
making for modern B2B sales management.
CHAPTER 1
INTRODUCTION
The BTP Order Suite is a comprehensive cloud-based enterprise application designed to
modernize and automate end-to-end B2B sales order management. In today’s highly competitive
commercial environment, businesses must process orders accurately, fulfill customer commitments
on time, and manage credit and inventory efficiently while meeting the growing expectations of
enterprise buyers. Traditional manual processes and disconnected tools often cause order
mismatches, credit overruns, stock discrepancies, approval delays, and limited visibility into sales
performance. This project addresses these challenges by providing a centralized digital platform
built on the SAP Business Technology Platform (BTP) that unifies all core order management
operations into a single, role-governed system.

Built with the SAP Cloud Application Programming Model (CAP) and [Link] for dynamic
backend processing, and SAP HANA as the secure relational database, the application ensures
reliability, scalability, and maintainability for enterprise workloads. Role-based authentication and
access control through SAP XSUAA OAuth2 protect sensitive business data while allowing users
to access only the functions relevant to their responsibilities. Real-time dashboards provide clear
visibility into critical metrics such as order status distribution, revenue by region, top customers by
spend, low-stock alerts, and monthly sales trends, enabling faster and more informed decision-
making.

The system is organized into integrated functional modules covering Order Management,
Customer and Credit Control, Product and Inventory Management, Document Intelligence, AI
Order Analysis, and Operations Analytics. Each module is tailored to specific business
responsibilities, enabling seamless coordination from order creation and credit validation through
product pricing, GST calculation, inventory deduction, and post-delivery reconciliation.
An AI-powered risk engine evaluates each order using credit profiles, purchase history, and
delivery timelines to support smarter sales decisions. By connecting sales, finance, and warehouse
workflows in real time, the platform reduces coordination gaps, enforces business rules
automatically, and supports smooth operations even at high transaction volumes.

1
1.1 Company Profile
Markdot Intellect is a dynamic and forward-thinking IT services and consulting company
dedicated to delivering exceptional digital solutions that empower businesses and individuals
alike. Founded in 2024 and headquartered in Coimbatore, Tamil Nadu, the company has quickly
established itself as a reliable technology partner for clients seeking innovative and high-quality
digital services. With a strong focus on providing client-centric, results-driven solutions, Markdot
Intellect specializes in web development, mobile app development, UI/UX design, digital
marketing, and custom software development. The company is deeply committed to not only
serving its clients with excellence but also investing in the future of technology by nurturing
skilled IT professionals. Through its dedicated training division, Markdot FFL (Fit For Learn), the
company offers industry-relevant courses including Digital Marketing, MERN Stack
Development, and more, bridging the gap between academic learning and real-world industry
demands.
Website : [Link]
Industries : IT Services & IT Consulting
Specialities : Web Development, Mobile App Development, Digital Marketing,
UI/UX Design, Software Development, Technology Training
Company Size : 8 – 9 Employees
Headquarters : Coimbatore, Tamil Nadu
Type : Self Owned
Founded : 2024
CEO : Mr. Tharun Danial

Specialities -
Web Development
Mobile App Development
UI/UX Design
Digital Marketing
Software Development
Technology Training (FFL – Fit For Learn)

2
1.2 About Project

The BTP Order Suite is a modern cloud-based enterprise application developed to simplify
and automate B2B sales order operations. This project integrates key functions such as order
lifecycle management, customer credit control, product and inventory management, document
extraction, AI-powered order analysis, and operational analytics into one centralized platform.
By replacing manual workflows and disconnected tools, the system helps businesses improve
order accuracy, processing speed, and overall operational efficiency.

The application enables sales teams to create and manage orders efficiently, track order status
in real time, and generate GST-inclusive bills with full accuracy. It also supports smooth
coordination between sales, finance, and warehouse teams by enforcing credit limits,
validating stock availability, and maintaining a complete audit trail — reducing delays and
discrepancies during high-volume periods. Through dashboards and reports, managers can
monitor revenue, order trends, customer performance, and inventory health for better decision-
making.

A major strength of the project is its role-based module structure, covering Order
Management, Customer and Credit Control, Product and Inventory Management, Document
Intelligence, AI Order Analysis, and Operations Analytics. Each user gets secure access to
relevant features based on their responsibilities through SAP XSUAA OAuth2 role collections
- Viewer, Editor, and Admin. The system also includes inventory-focused capabilities such as
real-time stock deduction on order approval, stock restoration on cancellation, low-stock
alerts, and product catalog management to improve cost control and supply accuracy.

To further enhance efficiency, the project incorporates an AI-assisted order risk engine that
evaluates each order using credit exposure, customer purchase history, delivery timelines, and
product mix to generate risk scores and discount recommendations. It also integrates SAP
Document Information Extraction (DIEx) to automatically extract structured data from
uploaded PDF invoices and purchase orders. Built using SAP CAP, [Link], and SAP HANA,
the system is reliable, scalable, and suitable for enterprise-grade B2B operations. Overall, the
project provides a practical, secure, and intelligent solution for efficient, data-driven sales
order management.

3
CHAPTER 2
SYSTEM STUDY
2.1 Existing System
The existing B2B sales order management approach generally follows a traditional and
fragmented method, where orders are raised through emails, phone calls, or spreadsheets and
processed manually by sales teams. This process is time-consuming and prone to errors such as
incorrect product entries, pricing issues, missing GST calculations, and inaccurate order totals.
Communication between sales, finance, and warehouse teams is often unsynchronized, causing
approval delays, stock mismatches, and fulfillment errors. Since records are maintained across
separate files or disconnected systems, there is no centralized way to track order status, monitor
customer credit exposure, or manage inventory effectively.

Credit management is often handled manually, with no automatic validation during order
submission, which can lead to orders being processed beyond customer credit limits. Similarly,
stock tracking is handled separately, causing over-commitment of inventory or unexpected stock
shortages. Document handling relies on manual data entry, increasing errors and slowing
procurement workflows. As a result, businesses face heavy administrative workload, difficulty
retrieving historical data, weak real-time decision-making support, and reduced overall
operational efficiency.

2.1.1 Drawbacks
The existing manual or semi-digital B2B order management approach has several limitations
affecting operational efficiency. Manual order creation and billing often lead to errors in product
entry, pricing, discounts, and GST calculation. Lack of integration between sales, finance, and
warehouse teams causes delays in credit validation, stock confirmation, and order fulfillment. In
addition, the absence of automated credit checks and real-time inventory tracking can result in
credit overruns, stock shortages, and order cancellations. Manual document handling also
increases errors and slows procurement processes.

Another drawback is the lack of centralized real-time data management, making it difficult to
track order status, monitor customer activity, and generate reliable reports. The absence of a
structured audit trail reduces transparency, while scattered records increase administrative
workload, slow data retrieval, and limit scalability as business volume grows.

4
2.2 Proposed System
The proposed system automates and integrates complete B2B sales order management operations
through a centralized cloud platform built on the SAP Business Technology Platform (BTP). It
supports real-time order creation, customer credit control, product pricing, inventory tracking,
document extraction, and operational analytics. By enabling automated order generation, GST-
inclusive billing, credit validation, and stock deduction on approval, the system reduces manual
effort, improves accuracy, and speeds up processing.

A key feature of the system is its role-based architecture, connecting modules such as Order
Management, Customer and Credit Control, Product and Inventory Management, Document
Intelligence, AI Order Analysis, and Operations Analytics for smooth coordination across teams.
Built using SAP HANA, the system supports dashboards, audit trails, inventory monitoring, and
automated business rule enforcement, including credit checks and stock restoration. It also
includes an AI-powered order risk engine and integration with SAP Document Information
Extraction (DIEx) for automated document processing, improving efficiency and scalability in
B2B order management.

2.2.1 Advantages
Integrates order management, customer credit control, product catalog, inventory
tracking, document extraction, and analytics into one centralized cloud platform on
SAP BTP.
Reduces human errors through automated GST-inclusive billing, real-time credit limit
validation, and automatic stock deduction and restoration.
Improves processing speed and business efficiency through faster order creation,
automated approval workflows, and seamless coordination across teams.
Provides role-based access control through SAP XSUAA OAuth2 with Viewer,
Editor, and Admin roles, ensuring security and accountability.
Supports real-time dashboards and reports for order status, revenue trends, top
customers, and low-stock alerts for better decision-making.
Maintains a complete audit trail of order status changes, credit movements, and stock
updates for full operational traceability.
Enhances sales decisions through an AI-powered order risk engine with risk scoring
and discount recommendations.

5
2.3 Feasibility Study
The feasibility study confirms that the proposed BTP Order Suite is practical and viable
across technical and operational aspects. Built using enterprise technologies such as SAP
CAP, [Link], SAP HANA, and SAPUI5, the system ensures stability, security, scalability,
and maintainability without complex on-premise infrastructure. Deployed on SAP BTP Cloud
Foundry, it supports reliable cloud-based operations and allows future enhancements such as
predictive analytics and extended AI features. Operationally, role-based access, automated
credit and stock validations, GST calculations, and audit logging reduce manual effort,
improve coordination, and support smooth adoption with minimal training.

Economically, the system is feasible because cloud-based automation reduces administrative


overhead, minimizes billing and inventory errors, lowers credit risk exposure, and improves
procurement accuracy through AI-assisted document extraction and order analysis. By
reducing manual data entry and improving order processing efficiency, the system lowers
operational costs, speeds up turnaround time, and supports long-term business profitability.

2.3.1 Technical Feasibility


The project is technically feasible because it is built using enterprise-grade technologies such as
SAP CAP, [Link], SAP HANA, SAPUI5, and OData v4, fully compatible with SAP BTP Cloud
Foundry and modern web browsers. The system uses managed BTP services including XSUAA,
HANA HDI containers, and HTML5 Repository, eliminating the need for specialized on-premise
infrastructure. Its modular role-based architecture ensures stable integration of order
management, credit control, inventory tracking, document extraction, and analytics while
maintaining data consistency and secure access.

The AI-powered order risk analysis is technically feasible through API integration with the Groq
large language model using structured order and customer data from HANA. The system receives
risk scores and recommendations in real time and stores the results back in order records.
Likewise, SAP Document Information Extraction (DIEx) uses OAuth2 and REST APIs for
automated document processing without additional infrastructure. Both integrations are loosely
coupled, scalable, and support future AI enhancements without major architectural changes.

6
2.3.2 Market Research

Market research indicates that the proposed BTP Order Suite addresses a clear gap in the digital
transformation of B2B order management, particularly among mid-sized and large enterprises
that still depend on fragmented practices such as spreadsheets, email-based approvals, and loosely
integrated ERP processes. Such fragmentation often leads to delayed approvals, weak
coordination between sales and inventory functions, poor credit control, limited auditability, and
inadequate real-time visibility into operational and financial performance. In this context, the
BTP Order Suite demonstrates market relevance by offering an integrated, cloud-native platform
on SAP Business Technology Platform that unifies order processing, customer and product data,
business rule enforcement, inventory and credit validation, audit logging, and analytical reporting
within a single environment.

IIts value is strengthened by intelligent features such as AI-assisted order risk scoring, discount
recommendations, and analytics that improve decision-making and reduce manual effort. The
solution is well suited for organizations within the SAP ecosystem, offering a flexible and cost-
effective alternative to large-scale ERP customization with broader capabilities than standalone
order-tracking tools.

2.3.3 User Requirements

The user requirements for the BTP Order Suite emphasize a reliable, efficient, and user-oriented
platform for key enterprise roles such as administrators, sales users, and read-only stakeholders
involved in order, finance, and inventory processes. The system is expected to support rapid order
creation through auto-generated order numbers, customer and product value-help selection,
automatic GST-based calculations, and business-rule-driven validation of credit exposure and
stock availability. It should also provide real-time inventory visibility, controlled stock
adjustments during approval and cancellation, and secure access management through SAP BTP
authentication and role modeling to protect sensitive customer and financial data.

From an operational perspective, sales users need tools to create and track orders, finance users
require visibility into credit, taxes, and audit records, while management needs dashboards and
reports for data-driven decisions. Intelligent features such as AI-assisted risk analysis and
document data extraction further reduce manual effort and improve decision-making speed and
accuracy.

7
2.3.4 Economic Feasibility
The economic feasibility of the BTP Order Suite confirms that it is a cost-effective solution for
enterprises seeking to modernize B2B sales order operations. Built on SAP BTP managed cloud
services with a pay-per-use model, the system eliminates the need for expensive on-premise
hardware, dedicated database servers, or large IT maintenance teams, reducing upfront investment
compared to traditional ERP deployments. By leveraging managed services for authentication,
database hosting, and application delivery, operational costs remain predictable and scalable as
transaction volumes grow.

By automating order generation, credit validation, GST-inclusive billing, stock deduction, audit
logging, and document data extraction, the system reduces manual effort, administrative
overhead, and the cost of correcting billing or inventory errors. These improvements help prevent
revenue loss, avoid stock shortages, and increase workforce productivity by enabling sales teams
to handle larger order volumes efficiently.

In addition, real-time dashboards, sales reports, and AI-assisted order risk analysis support better
financial planning, smarter decisions, and improved resource utilization. Its modular cloud-native
architecture also allows future enhancements to be adopted incrementally without major
reinvestment, ensuring long-term economic viability as the business scales.

8
CHAPTER 3
SYSTEM SPECIFICATION

3.1 Hardware Specification

3.2 Software Specification

9
CHAPTER 4
SOFTWARE DESCRIPTION
4.1 Frontend
4.1.1 Introduction
The frontend of the BTP Order Suite is a responsive enterprise web application developed using
SAP UI5 and SAP Fiori design principles to support efficient B2B sales order operations on
desktop and laptop devices. It provides users with an intuitive interface for core activities such as
order creation, product selection, automatic pricing and GST calculation, credit visibility, and
order status tracking.

The interface is structured to simplify navigation across operational and analytical screens,
allowing users to complete tasks quickly and accurately with minimal training. Overall, the
frontend is designed to enhance usability, improve operational efficiency, and provide a
consistent digital experience for users involved in order processing and monitoring.

4.1.2 Features

The BTP Order Suite follows a cloud-native client-server architecture in which the SAP UI5
frontend communicates with an SAP CAP [Link] backend through OData V4 services and
application APIs, while business data is stored in an SAP HANA HDI database. This architecture
enables reliable data exchange across functional areas such as order management, customer and
product master data, credit control, inventory visibility, audit logging, analytics, and AI-assisted
order evaluation.

The frontend supports major business functions including order lifecycle tracking, automated
GST-inclusive calculations, value-help-based customer and product selection, dashboard
reporting, customer performance views, and audit-oriented order monitoring. It also integrates
intelligent features such as AI-based order risk scoring and discount recommendation support to
improve decision-making and reduce manual effort. The modular frontend and backend design
allows the application to be extended with additional business functions and analytics without
major disruption.

10
4.1.3 Technology Stack
The frontend of the BTP Order Suite is built using SAP UI5 (version 1.120.0) as the core UI
framework, following the Freestyle UI5 approach with custom XML views, controllers, and
client-side routing via [Link]. This approach provides full control over layout and
interaction design, enabling screens to be tailored precisely to the operational requirements of
each module.

The application uses the following SAP UI5 libraries:

Backend communication is handled through OData V4 services, with the OData model
configured in server-side operation mode to ensure queries and filters are processed at the
backend rather than the client.

The application is themed with SAP Fiori Horizon (sap_horizon), the current SAP design
standard, and supports both compact and cozy content densities to accommodate different user
preferences. Internationalization is managed through a resource model
([Link]) using i18n property files.

The build and development toolchain is based on UI5 Tooling v4 (@ui5/cli ^4.0.33) with the
following supporting tools:
@sap/ux-ui5-tooling — Fiori Tools middleware for local development proxy, live reload,
and Fiori Launchpad preview
@sap-ux/eslint-plugin-fiori-tools with eslint ^9 — Static code analysis enforcing SAP Fiori
coding standards
ui5-task-zipper — Packages the built application into a deployable archive for SAP BTP
The application is deployed to SAP BTP Cloud Foundry using the HTML5 Application
Repository, with the build pipeline configured via [Link] and triggered through the npm
run build:cf script.

11
4.1.4 Navigation Flow
The BTP Order Suite uses a persistent sidebar for primary navigation, allowing users to switch
between the main modules at any time. Secondary navigation occurs within screens based on user
actions such as selecting a record or submitting a form.
The application uses the following SAP UI5 libraries:

Order Lifecycle Flow

The order status progresses through the following stages, tracked as a visual stepper on the
OrderDetail screen:
DRAFT → APPROVED → SHIPPED → DELIVERED

CANCELLED (reachable from any stage)

12
4.1.5 Architecture

13
4.2 Backend
4.2.1 Introduction
The backend of the BTP Order Suite is a robust and scalable server-side application built using
the SAP Cloud Application Programming Model (CAP) with [Link], responsible for handling
business logic, data processing, API communication, and service integration across the
platform. It acts as the core engine of the system, processing frontend requests, enforcing
business rules automatically, and coordinating data flow between order management, credit
control, inventory, document extraction, and AI analysis modules. All data is securely stored in
an SAP HANA HDI database, ensuring performance, reliability, and consistency even under
high transaction volumes.
The backend exposes an OData v4 service covering core entities such as Orders, Order Items,
Customers, Products, Order Status, Priority, Notes, Audit Logs, and Business Rules. Beyond
standard CRUD operations, the service layer implements event-driven hooks for order number
generation, credit validation, stock deduction and restoration, GST calculations, order total
rollup, and audit logging. Additional REST APIs support AI-powered order risk analysis
through Groq, document extraction through SAP Document Information Extraction (DIEx), and
dashboard data delivery with caching for performance. Together, these components form a
secure and intelligent backend supporting modern B2B sales order management.

4.2.2 Features
Automatic Order Number Generation
Orders are assigned a year-scoped sequential number on creation (format ORD-YYYY-
NNNNNN), generated server-side by counting existing orders for the current year and zero-
padding the sequence. This prevents client-side number collisions and ensures cross-year
uniqueness.

Automatic GST and Line Item Calculation


On every CREATE or PATCH to OrderItems, the backend recalculates all line amounts using
the formula:
netAmount = quantity × unitPrice × (1 − discount/100)
taxAmount = netAmount × (taxRate/100)
lineAmount = netAmount + taxAmount
After any item change (create, update, or delete), the parent order’s subTotal, taxAmount, and
totalAmount are automatically recomputed by summing all item amounts.

14
Credit Limit Management
When an order transitions to SUBMITTED, the backend validates that the order’s totalAmount
does not exceed the customer’s available credit (creditLimit − creditUsed). If credit is
insufficient, the request is rejected with a 400 error. On a successful submission, the order
amount is reserved by incrementing creditUsed. When the order reaches DELIVERED or is
CANCELLED, the reserved amount is released back to the customer’s available credit.

Stock Inventory Control


When an order is approved (status changes to APPROVED), the backend performs a two-pass
stock check: first validating that all line item quantities are available, then atomically deducting
stock from each product’s stockQty. If any product has insufficient stock, the approval is
blocked and a descriptive error lists each shortfall. If an approved or in-progress order is
subsequently cancelled, stock quantities are fully restored.

Audit Logging
All significant events are written to the AuditLogs entity with a timestamp, action code, entity
type, entity ID, entity reference, actor (from the request user), old value, new value, and details.
Audit events include: ORDER_CREATED, STATUS_CHANGED, CREDIT_RESERVED,
CREDIT_RELEASED, STOCK_DEDUCTED, STOCK_RESTORED, and
CUSTOMER_UPDATED. Logs are also written via HANA database-level hooks registered on
the served event for additional coverage.

Document AI — PDF Extraction


The Document Information Extraction service is integrated via two endpoints. POST
/api/uploadDocument accepts a PDF file (maximum 10 MB, validated by content type) and a
document type (invoice, purchaseOrder, receipt, bankStatement), obtains an OAuth2 token from
the XSUAA UAA endpoint of the DIEx service, and submits the document to the SAP
Document Information Extraction API using the appropriate SAP-provided schema
(SAP_invoice_schema, SAP_purchase_order_schema, etc.), returning a job ID. GET
/api/getJobResult?jobId=<id> polls the job status until the extracted fields and line items are
returned. Credentials are resolved from VCAP_SERVICES in Cloud Foundry or from default-
[Link] in local development.

15
Credit Limit Management
When an order transitions to SUBMITTED, the backend validates that the order’s totalAmount
does not exceed the customer’s available credit (creditLimit − creditUsed). If credit is
insufficient, the request is rejected with a 400 error. On a successful submission, the order
amount is reserved by incrementing creditUsed. When the order reaches DELIVERED or is
CANCELLED, the reserved amount is released back to the customer’s available credit.

AI Order Risk Analysis


POST /api/analyzeOrder { orderId } assembles a full order context (order header, enriched line
items with product names and categories, customer profile, and the customer’s last 10 orders)
and sends it to the Groq LLaMA 3.3-70B model with a structured system prompt. The AI
returns a JSON object containing: a riskScore (0–100), riskLevel
(LOW/MEDIUM/HIGH/CRITICAL), flags (specific risk indicators with severity), a
discountRecommendation (suggested discount % and reason), actionable recommendations, and
a summary. The risk score is persisted back to the order (aiScore, aiRecommended).

Audit Logging
All significant events are written to the AuditLogs entity with a timestamp, action code, entity
type, entity ID, entity reference, actor (from the request user), old value, new value, and details.
Audit events include: ORDER_CREATED, STATUS_CHANGED, CREDIT_RESERVED,
CREDIT_RELEASED, STOCK_DEDUCTED, STOCK_RESTORED, and
CUSTOMER_UPDATED. Logs are also written via HANA database-level hooks registered on
the served event for additional coverage.

Document AI — PDF Extraction


The Document Information Extraction service is integrated via two endpoints. POST
/api/uploadDocument accepts a PDF file (maximum 10 MB, validated by content type) and a
document type (invoice, purchaseOrder, receipt, bankStatement), obtains an OAuth2 token from
the XSUAA UAA endpoint of the DIEx service, and submits the document to the SAP
Document Information Extraction API using the appropriate SAP-provided schema
(SAP_invoice_schema, SAP_purchase_order_schema, etc.), returning a job ID. GET
/api/getJobResult?jobId=<id> polls the job status until the extracted fields and line items are
returned. Credentials are resolved from VCAP_SERVICES in Cloud Foundry or from default-
[Link] in local development.

16
Stock Inventory Control
When an order is approved (status changes to APPROVED), the backend performs a two-pass
stock check: first validating that all line item quantities are available, then atomically deducting
stock from each product’s stockQty. If any product has insufficient stock, the approval is
blocked and a descriptive error lists each shortfall. If an approved or in-progress order is
subsequently cancelled, stock quantities are fully restored.

Order PDF Generation


The GET /api/orderPDF?orderId=<uuid> endpoint generates a formatted A4 PDF order
confirmation using PDFKit. The document includes a branded header, order details (number,
date, status, priority, shipping address), customer information (name, GST number, city/state), a
line item table with quantities, unit prices, discounts, GST rates, and amounts, and a financial
summary showing sub-total, tax, and total. The PDF is streamed directly to the response.

Dashboard Analytics API


GET /api/dashboardData computes full dashboard metrics from the database, including KPIs
(total revenue, order count, estimated profit, average order value), revenue by month, order
status distribution with percentages and colours, a top-50 order table, OHLC candlestick data
for monthly revenue trends, and bubble chart data for the top 12 customers by revenue. All four
entity sets are queried in parallel, and results are cached in memory for 60 seconds. The cache is
invalidated on any write operation (CDS succeeded event).
GET /api/dashboardInsights computes an extended analytics payload for the OrdersList
embedded dashboard: top customers, priority distribution, order health score (weighted formula
based on completion efficiency, pipeline health, and cancellation rate), overdue order count and
value broken down by priority, 6-month revenue with 2-month linear forecast, and category
performance. This endpoint also calls Groq LLaMA 3.3-70B to generate 3 AI business insights
referencing the actual metric values.

Bulk Order Import


GET /api/importTemplate generates and downloads a sample .xlsx file with the required column
structure. POST /api/bulkImport accepts an Excel file, parses each row using ExcelJS, resolves
CustomerCode to a customer ID and ProductSKU to a product ID, applies defaults for missing
fields, and creates orders and order items in the database, returning a per-row result summary of
successes and failures.

17
Report Engine
GET /api/reportData?type=<type>&dateFrom=&dateTo= supports five report types:

GET /api/exportReport?type=&format= exports any report in three formats: CSV (plain text,
immediately streamed), Excel (.xlsx via ExcelJS with styled header row and a Summary
worksheet), and PDF (A4 landscape via PDFKit with a branded header, paginated data table,
and footer).
POST /api/emailReport sends a formatted HTML email containing the report table and KPI
summary. It supports three delivery paths in priority order: SMTP (configured via smtpConfig
in [Link] or environment variables), Brevo transactional email API (configured via
BREVO_API_KEY), and Ethereal Email (for development preview when no provider is
configured).

SQL Console API


GET /api/sql/schema introspects the CDS model and returns the table and column schema for
use in the SQL console’s autocomplete. POST /api/sql/execute { sql, writeMode } executes
arbitrary SQL against the HANA/SQLite database with a security guard: DDL operations
(DROP, TRUNCATE, ALTER, CREATE, ATTACH, DETACH) are always blocked; DML
operations (INSERT, UPDATE, DELETE) are blocked unless writeMode is explicitly enabled.
Query execution time is measured and returned. POST /api/sql/ai { prompt, schemaContext }
uses Groq LLaMA 3.3-70B to translate a natural language question into a valid SQL SELECT
query, returning only the raw SQL.

18
4.2.3 Architecture
Technology Stack

Business Logic Layer (CAP Event Handlers)


All order business logic is implemented as CAP event handlers in [Link]:
before CREATE Orders → generate order number, set defaults
after CREATE Orders → write ORDER_CREATED audit log
before PATCH Orders → credit check/reserve/release, stock validate/deduct/restore
after PATCH Orders → write audit logs for status change, credit, stock events
before CREATE OrderItems → set line number, pull product price/UOM/tax rate, calculate
amounts
before PATCH OrderItems → re-pull product price if changed, recalculate amounts
after CREATE/PATCH OrderItems → recalculate parent order totals
before DELETE OrderItems → capture parent order ID
after DELETE OrderItems → recalculate parent order totals

19
4.2.3 Architecture
Technology Stack
The schema (db/[Link]) defines nine entities in the [Link] namespace:

GDPR personal data annotations are applied to Customers (name, email, phone), marking the
entity as a DataSubject with DataSubjectRole: Customer.

Build and Deployment Pipeline


The backend is built by the MTA build pipeline:
1. before-all: npm ci installs root dependencies; npx cds build --production generates the
gen/srv/ and gen/db/ artifacts.
2. btp-order-suite-db-deployer (type hdb): deploys the HDI container artifacts from gen/db/ to
the HANA HDI container.
3. btp-order-suite-srv (type nodejs): deploys the compiled CAP service from gen/srv/ to Cloud
Foundry with nodejs_buildpack.
Service bindings wired to the backend module:
btp-order-suite-auth (XSUAA) — JWT authentication
btp-order-suite-db (HANA HDI) — database connection
btp-order-suite-destination — Destination service for outbound connectivity
btp-order-suite-diex — Document Information Extraction service (existing service
DocAI_Trial)

20
21
CHAPTER 5
PROJECT DESCRIPTION
5.1 Module Description
The frontend of the BTP Order Suite is organized into multiple functional modules, each
designed to support a specific area of the order management process and address different
operational responsibilities across sales, finance, inventory, and management teams. These
modules are integrated through a unified user interface, enabling smooth navigation between
transaction processing, monitoring, reporting, and decision-support activities. Each module is
designed with specific business functions while working together as part of a single coordinated
system, reducing process fragmentation and improving usability.

1. Orders Management Module


This is the core module of the application and is responsible for creating, viewing, updating, and
tracking sales orders. It allows users to enter customer details, select products, manage
quantities and pricing, and monitor order progress through stages such as draft, submitted,
approved, shipped, and delivered. It also supports automatic order number generation, GST-
based calculations, and business-rule validation.

2. Order Detail Module


The Order Detail module provides a complete view of a selected order, including customer
information, delivery details, line items, totals, status, and notes. It enables users to review and
edit order information, observe status transitions, and access audit-related tracking data for
operational transparency.

3. Dashboard and Analytics Module


This module presents visual summaries of operational and financial indicators such as revenue,
active orders, order status distribution, sales trends, and customer contribution. It helps users
monitor performance in real time and supports decision-making through charts, KPIs, and
analytics.

4. Customer 360 Module


The Customer 360 module provides a consolidated view of customer information, including
order history, revenue contribution, credit utilization, and recent activity. It helps users
understand customer value, financial exposure, and engagement patterns in a single interface.

22
5. Reports Module
The Reports module generates structured reports related to sales performance, order status,
customer activity, product demand, financial summaries, and AI-based order evaluation to
support managerial analysis.

6. Rules and Regulations Module


This module allows users to manage and review business rules governing order processing. It
supports operational thresholds, validation conditions, and policy controls to ensure compliance
with business requirements.

7. AI Order Analysis Module


This module supports intelligent order evaluation by generating risk scores, flags, and decision-
support recommendations. It helps users identify unusual or high-risk orders for review and
action.

8. Query and Data Analysis Module


This module provides an advanced interface for executing predefined or custom SQL-based
queries for administrative and analytical purposes. It is useful for technical users requiring deeper
visibility beyond standard dashboards and reports.
Overall, these modules work together to provide a unified frontend environment that supports
transaction processing, monitoring, analytics, and intelligent decision support within the BTP
Order Suite.

23
5.2 Data Flow Diagram

24
5.3 ER Diagram
The ER Diagram of the BTP Order Suite defines the key entities and relationships required for
complete B2B sales order operations, including Customer, Product, Product Category, Order,
Order Item, Order Status, Priority, Notes, Rules, and Audit Logs. A customer can place multiple
orders, each linked to a status and priority, while every order contains multiple order items
connected to products and categories, with totals automatically calculated from line items. The
system validates customer credit during order submission, reserves credit, deducts stock on
approval, and restores both credit and stock on cancellation or delivery. Notes support order
tracking and follow-ups, while business rules govern thresholds, approvals, and constraints.
Critical activities such as order creation, status transitions, credit reservations, and stock
movements are recorded in Audit Logs for traceability. An integrated AI analysis engine
evaluates orders using credit health, purchase history, delivery urgency, and product mix to
generate risk scores and discount recommendations, ensuring data accuracy, credit control, real-
time inventory management, and efficient B2B order workflow integration.

25
5.4 Input Design
The input design of the BTP Order Suite is built for accuracy, efficiency, and seamless B2B
order management across roles such as sales executives, store managers, and approvers. It
provides role-based, form-driven interfaces for modules including customer management,
product cataloguing, order creation, order item entry, notes management, business rules
configuration, and AI-driven order analysis.

Inputs are organized using searchable dropdowns for customer and product selection,
category-based product filters, quantity and pricing controls with auto-calculation, date
pickers for order dates and requested delivery, status selectors for order lifecycle
management, and priority selectors to flag urgency. Order item entries automatically populate
unit price, unit of measure, and tax rate from linked product data, reducing manual entry and
errors.

Client-side and server-side validations ensure required fields are completed, numeric values
are valid, credit availability is checked before submission, and stock sufficiency is verified
before approval. Duplicate order numbers are prevented through a year-scoped auto-
generation mechanism, and only authorized users can submit, approve, or cancel orders based
on roles.

The system also supports real-time input effects such as automatic order total recalculation,
live credit usage updates, and dynamic stock adjustments on approval or cancellation. Notes
can be linked to orders or created independently with priority tags for quick reference. All
submissions are secured through SAP BTP authentication, and the responsive layout supports
desktops and tablets, making B2B order data entry fast, controlled, and fully traceable.

5.5 Output Design


The output design of the BTP Order Suite focuses on clear, accurate, and actionable results for
all user roles including sales executives, store managers, approvers, and management. The
system generates structured outputs such as order summaries, order item breakdowns,
customer credit reports, product stock views, audit logs, business rule reports, AI risk analysis
reports, and operational dashboards.

26
Order outputs include auto-generated order numbers, item-wise net amounts, tax
calculations, subtotals, and grand totals in INR, providing complete financial transparency.
Customer outputs display credit utilization, available credit balance, and order history to
support informed sales and approval decisions.

Operational outputs provide real-time visibility into order lifecycle stages—from Draft to
Delivered or Cancelled—along with live stock quantity updates reflecting deductions and
restorations. Low-stock conditions are also traceable to support timely replenishment
decisions.

AI analysis outputs provide structured risk assessments for each order, including risk scores,
classifications, actionable flags, discount recommendations, and order summaries to support
data-driven approval decisions. Audit log outputs capture a chronological record of critical
actions such as status changes, credit movements, and stock updates with actor details and
timestamps for accountability. Notes outputs present reminders linked to orders with
priority, due date, and completion status.

All outputs are role-based, securely accessible through SAP BTP authentication, responsive
across desktops and tablets, and formatted for both on-screen viewing and document export,
ensuring efficient and transparent B2B order operations.

5.6 Database Design


The database design of the BTP Order Suite uses a normalized relational structure built on SAP
HANA Cloud, modeled through SAP Cloud Application Programming Model (CAP) using
Core Data Services (CDS). It manages customers, products, orders, order items, notes, audit
logs, and business rules with strong data integrity and referential consistency.

Primary keys use UUID-based identifiers across transactional entities such as Customers,
Products, Orders, Order Items, Notes, Audit Logs, and Rules, ensuring globally unique record
identification. Foreign key associations enforce referential integrity between related entities,
while code list entities such as Order Status, Priority, and Product Category use short string
codes as lookup references across the system.

27
5.7 Table Design
5.7.1 OrderStatus

5.7.2 Priority

5.7.3 Orders

5.7.4 AuditLogs

5.7.5 ProductCategory

28
5.7.6 Products

5.7.7 Customers

5.7.8 Notes

29
5.7.9 OrderItems

5.7.10 Rules

30
CHAPTER 6
SYSTEM TESTING

Objectives of Testing
The primary objective of testing in the BTP Order Suite is to ensure that all integrated modules
work correctly, securely, and reliably as a complete B2B order management application
deployed on the SAP Business Technology Platform. Testing validates core functions such as
customer and product master data management, order creation with auto-generated order
numbers, order item entry with automatic pricing and tax calculations, order lifecycle transitions,
credit validation, stock checks, and credit or stock restoration on cancellation or delivery.

It also verifies the accuracy of financial calculations including item-level and order-level totals,
ensuring consistency across create, update, and delete operations. Testing confirms that audit
logging captures critical actions such as order creation, status changes, credit movements, and
stock adjustments with accurate timestamps and user details. In addition, the AI risk analysis
engine is tested for correct data retrieval, reliable communication with the Groq API, and proper
persistence of risk scores and recommendations. Business rules stored in the Rules entity are also
verified for correct thresholds and applicability.

Testing further ensures that only authorized users can access or perform actions based on
assigned SAP BTP roles, and that all OData v4 service endpoints function correctly for CRUD
operations. The system is also tested for stability, data integrity, and consistent performance
under normal operating conditions, ensuring a dependable and efficient order management
solution.

Test Plan
The test plan for the BTP Order Suite follows a systematic approach to validate core
functionalities including SAP BTP role-based authentication, customer and product master
data management, order creation with auto-generated numbering, order item entry with
automatic pricing and tax calculations, order lifecycle transitions, credit limit enforcement,
stock validation, and AI-driven risk analysis.

The plan emphasizes verification of real-time module synchronization and accurate database
transactions such as order total recalculation, customer credit updates, stock deductions on
approval, and stock restoration on cancellation.

31
Each order lifecycle stage-from Draft through Delivered or Cancelled—is tested to ensure
business rules, financial computations, and inventory adjustments are correctly triggered and
recorded in audit logs.

Testing covers OData v4 service endpoints for entities including Orders, Order Items,
Customers, Products, Notes, Rules, Order Status, Priority, Product Category, and Audit Logs,
ensuring correct responses for CRUD operations. The AI analysis module is tested for
reliable communication with the Groq API, accurate parsing of risk results, and proper
persistence of AI evaluation data.

The plan also verifies Notes management, Rules configuration, Audit Log traceability, role-
based access restrictions, and secure submissions through SAP BTP XSUAA authentication.
In addition, it confirms the responsive user interface performs consistently across desktop and
tablet devices for all user roles.

Testing Method
The testing methodology for the BTP Order Suite combines Black-Box and White-Box testing to
ensure complete validation of functional, business logic, and integration aspects of the
application.

Black-Box testing is applied at the user interface and OData v4 API level to verify customer and
product management, order creation and submission, order item entry, status transitions, notes
management, business rules configuration, and AI risk analysis outputs without examining
internal code structure. This ensures all user-facing features behave correctly across assigned
SAP BTP roles.

White-Box testing is applied to the CAP [Link] backend services to validate internal business
logic including order number generation, financial calculations, order total recalculation, credit
validation, stock checks, credit and stock restoration, and audit log creation. SAP HANA CDS
queries, associations, and computed field persistence are also verified at this level.

Integration testing confirms accurate data flow between the SAP Fiori frontend, CAP OData v4
service layer, SAP HANA Cloud database, and the Groq API. This includes validating
synchronized credit and stock updates, order total propagation, and persistence of AI analysis
results.

32
6.1 Unit Testing
Unit testing in the BTP Order Suite checks individual functions and service handler modules
separately before full integration. It covers order number auto-generation, financial calculations,
order total recalculation, credit validation, stock availability checks, credit and stock restoration
logic, audit log creation, AI data aggregation, and risk score persistence.

Each unit is tested with valid, invalid, and boundary inputs to verify output accuracy, validation
enforcement, and error handling. For example, item calculation functions are tested with varying
quantities, discounts, and tax rates to confirm correct net amount, tax amount, and line amount
calculations. Order total recalculation is tested with single-item, multi-item, and empty-order
scenarios to ensure accurate subtotal, tax, and grand total aggregation. Credit and stock validation
logic is tested under normal, boundary, and failure conditions to verify correct approval, rejection,
and restoration behavior.

The AI service unit is tested for accurate data assembly, delivery window calculation, reliable
communication with the Groq API, correct response parsing, and persistence of risk scores and
recommendation flags. Audit log units verify accurate recording of action type, entity reference,
actor identity, old and new values, and event details. Database-related logic is also tested for
correct CDS query execution, association traversal, and transaction consistency across order,
customer, and product updates. This approach helps detect issues early and improves the
reliability of the BTP Order Suite on the SAP BTP platform.

6.2 Integration Testing


Integration testing in the BTP Order Suite checks whether all modules work together correctly
through the SAP Fiori frontend, CAP [Link] backend service layer, SAP HANA Cloud
database, and the external Groq API. It validates end-to-end data flow from customer and
product setup through order creation, order item processing, status transitions, credit and stock
management, audit logging, notes handling, and AI risk analysis.

Integration testing verifies that when order items are created, updated, or deleted, financial
calculations are triggered automatically and order totals are recalculated and stored correctly. It
confirms that order submission properly validates customer credit, updates credit utilization,
checks stock availability during approval, deducts inventory, and restores credit and stock
accurately during cancellation or delivery.

33
Integration testing in the BTP Order Suite checks whether all modules work together correctly
through the SAP Fiori frontend, CAP [Link] backend service layer, SAP HANA Cloud
database, and the external Groq API. It validates end-to-end data flow from customer and
product setup through order creation, order item processing, status transitions, credit and stock
management, audit logging, notes handling, and AI risk analysis.

Integration testing verifies that when order items are created, updated, or deleted, financial
calculations are triggered automatically and order totals are recalculated and stored correctly. It
confirms that order submission properly validates customer credit, updates credit utilization,
checks stock availability during approval, deducts inventory, and restores credit and stock
accurately during cancellation or delivery.

6.3 Validation Testing


Validation testing in the BTP Order Suite ensures that the final application meets real B2B
business and user requirements in practical sales order management scenarios on the SAP
BTP platform. It confirms that core functions such as role-based authentication, customer
and product management, order creation, order item processing, lifecycle transitions, credit
enforcement, stock validation, AI risk analysis, notes management, and business rules
configuration operate as expected by end users.

Validation testing verifies that the system produces accurate financial outputs, including
item-level and order-level calculations that reflect real pricing, discounts, and GST
requirements. It confirms that credit boundaries are enforced correctly, stock shortages are
communicated clearly, and order lifecycle stages progress logically without conflicts while
triggering the correct effects on credit balances, stock quantities, and audit logs.

Testing also validates AI analysis outputs to ensure risk scores, flags, and recommendations
are meaningful and aligned with order and customer data. In addition, usability is checked
across roles such as sales executives, store managers, approvers, and management to verify
correct access permissions, restricted operations, and a consistent user experience across
desktop and tablet devices, ensuring the solution is reliable and suitable for daily B2B
operations.

34
6.4 Output Testing
Output testing in the BTP Order Suite verifies that all generated outputs are accurate, complete,
and properly formatted across all modules of the B2B order management application on the SAP
BTP platform. It checks order summaries, order item breakdowns, customer credit reports,
product stock status views, audit trail logs, AI risk analysis reports, notes listings, business rules
configurations, and operational dashboards for correct values and full consistency with the
underlying SAP HANA Cloud database records.

Customer output testing validates that credit limit, credit used, and available credit balance values
displayed on the customer record are always synchronized with the latest order submission,
delivery, and cancellation events, providing sales executives and approvers with accurate and real-
time credit visibility for informed decision-making. Product output testing confirms that stock
quantity values correctly reflect live deductions on order approval and restorations on order
cancellation, providing accurate inventory visibility at all times and preventing overselling across
concurrent B2B transactions.

Audit log output testing verifies that every logged entry displays the correct action type, entity
reference, actor identity, old value, new value, timestamp, and detail message, ensuring the audit
trail is complete, chronologically ordered, and fully traceable for every critical system event
including order creation, status transitions, credit reservations, credit releases, stock deductions,
and stock restorations. The audit log outputs are tested across multiple user roles to confirm that
actor identity is correctly captured regardless of which role initiated the action.

AI analysis output testing confirms that risk scores, risk level classifications — LOW, MEDIUM,
HIGH, and CRITICAL — severity-tagged flags, discount recommendation percentages with
business justification, actionable recommendation lists, and order summary text are correctly
rendered and fully consistent with the order, customer, and product data submitted to the Groq
API. It verifies that the aiScore and aiRecommended flag values displayed on the order record
accurately reflect the latest analysis result and are updated immediately following each AI
analysis execution.

Notes output testing confirms that note title, content, type, linked order number, due date,
completion status, priority level, and color tag are all correctly displayed and consistently reflect
the latest saved values.

35
6.5 Test Cases

36
CHAPTER 7
SYSTEM IMPLEMENTATION
7.1 Implementation Procedures
The implementation of the BTP Order Suite begins with environment setup on the SAP
Business Technology Platform, including the creation of a Cloud Foundry space, provisioning
of an SAP HANA Cloud database instance, configuration of the SAP Authorization and Trust
Management Service (XSUAA) with the required role collections, and setup of the SAP
HTML5 Application Repository for frontend hosting.

After provisioning the BTP services, the development environment is configured by installing
the SAP CAP CLI (@sap/cds-dk), [Link] runtime, and required npm dependencies including
@sap/cds, @sap/xssec, groq-sdk, and related packages. The [Link] file is configured
with the Groq API key and local HANA or SQLite connection settings for development and
testing purposes.

The database schema is initialized by deploying the CDS data model from db/[Link],
which creates all core tables for OrderStatus, Priority, ProductCategory, Customers, Products,
Orders, OrderItems, Notes, AuditLogs, and Rules on the SAP HANA Cloud instance. Seed data
for code list entities - OrderStatus, Priority, and ProductCategory - is loaded from the
corresponding CSV files in the db/data/ directory to populate the initial reference values
required for system operation.

The system is then deployed module by module using the MTA (Multi-Target Application)
build and deployment process. Deployment begins with the database deployer module (btp-
order-suite-db-deployer) to establish the schema and seed data, followed by the CAP backend
service module (btp-order-suite-srv) exposing the OData v4 OrderService endpoints, and finally
the SAP Fiori frontend application module (btp-order-suite-app-deployer) published to the
HTML5 Application Repository.

Role-based access control is configured through the [Link] file, defining scopes and
role templates for sales executives, store managers, approvers, and administrators, which are
then mapped to SAP BTP role collections and assigned to relevant users in the BTP cockpit.
The AI analysis integration is activated by verifying the Groq API key configuration and
confirming successful connectivity between the CAP backend service and the Groq API
endpoint.

37
The AI analysis integration is activated by verifying the Groq API key configuration and
confirming successful connectivity between the CAP backend service and the Groq API
endpoint.

Existing master data for customers and products, if available, is migrated carefully through CSV
import or OData batch operations with validation checks to ensure data integrity, correct field
mapping, and consistency across all related entities before the system goes live on the SAP BTP
platform.

7.2 System Maintenance


System maintenance in the BTP Order Suite includes regular performance monitoring, security
patching, and database optimization to keep B2B order operations fast, stable, and secure on the
SAP Business Technology Platform. Routine maintenance tasks involve checking the health of
all application modules including customer and product master data management, order creation
and lifecycle processing, credit limit enforcement, stock management, audit logging, notes
management, AI risk analysis, and business rules configuration.

SAP HANA Cloud database maintenance includes periodic index optimization, query
performance analysis, and monitoring of storage consumption to ensure fast retrieval of order,
customer, product, and audit log records as transaction volumes grow over time. Scheduled
automated backups of the HANA Cloud instance are configured and verified regularly through
backup recovery tests to prevent data loss and ensure business continuity in the event of an
unexpected failure.

Security maintenance involves regular review and patching of npm package dependencies
including @sap/cds, @sap/xssec, groq-sdk, and related libraries to address known
vulnerabilities. SAP BTP XSUAA role collections, scope assignments, and user authorizations
are periodically audited to confirm that role-based access controls remain correctly configured
and that no unauthorized access exists across sales executive, store manager, approver, and
administrator roles.

Application-level maintenance includes monitoring CAP service logs for runtime errors,
resolving reported bugs in order calculation logic, status transition handlers, credit and stock
management routines, and audit log generation.

38
The Groq AI API key validity and connectivity are checked periodically to ensure uninterrupted
AI risk analysis functionality, and the system prompt and scoring criteria are reviewed and
updated as business requirements evolve.

Proactive maintenance includes upgrading SAP CAP framework versions, [Link] runtime, and
MTA build tools as new releases are available, improving features based on user feedback from
sales and operations teams, and scaling SAP BTP Cloud Foundry application instances and
HANA Cloud compute resources as order transaction volumes increase. Periodic security
audits, updated technical documentation, and regular review of business rules thresholds and
severity configurations ensure long-term reliability, data protection, and smooth future
enhancements of the BTP Order Suite on the SAP BTP platform.

39
CHAPTER 8
CONCLUSION AND FUTURE ENHANCEMENT

8.1 Conclusion
The BTP Order Suite successfully provides a complete digital solution for automating and
integrating core B2B sales order management operations on the SAP Business Technology
Platform. By combining a responsive SAP Fiori frontend with a reliable CAP [Link] backend
and SAP HANA Cloud database, the project streamlines customer and product master data
management, order creation and lifecycle processing, credit limit enforcement, real-time stock
management, audit trail logging, notes management, and AI-driven risk analysis within a unified
and scalable cloud platform.

The system eliminates manual errors in order numbering, financial calculations, and inventory
tracking by automating order item pricing, tax computation, order total aggregation, credit
reservation and release, and stock deduction and restoration through intelligent server-side
business logic. Role-based access control enforced through SAP BTP XSUAA ensures that sales
executives, store managers, approvers, and administrators each operate securely within their
defined responsibilities, maintaining data integrity and operational accountability across all
modules.

The integration of AI-powered order risk analysis through the Groq API adds significant business
intelligence capability to the platform, enabling approvers to make data-driven decisions on high-
value or risky orders by evaluating customer credit health, order history, delivery urgency, and
product mix in real time. The comprehensive audit logging mechanism provides full traceability
of every critical action across orders, customers, and products, supporting compliance, dispute
resolution, and management oversight.

Overall, the BTP Order Suite is practical, scalable, and well-suited for modern B2B sales
environments, offering a strong foundation for future expansion such as multi-company order
management, advanced sales analytics, automated approval workflows, mobile application
support, and deeper integration with SAP S/4HANA procurement and finance modules on the
SAP BTP platform.

40
8.2 Future Enhancements
Future enhancements of the BTP Order Suite will focus on making the platform more intelligent,
scalable, and deeply integrated within the SAP Business Technology Platform ecosystem to
support growing B2B sales operations.

Advanced machine learning models can be integrated to predict customer order patterns, forecast
product demand, and recommend optimal stock replenishment quantities based on historical
order data, seasonal trends, and customer buying behavior. These predictive capabilities will
reduce stockout risks, improve inventory planning, and enable proactive credit limit adjustments
based on customer growth and payment history.

The system can be expanded with multi-company and multi-warehouse support, allowing
organizations to manage orders, stock levels, credit limits, and approval workflows across
multiple business units and distribution centers through a centralized SAP BTP dashboard with
real-time synchronization. Advanced approval workflow automation using SAP Build Process
Automation can be integrated to replace manual status transitions with configurable multi-level
approval chains based on order value, customer risk score, and business rules thresholds.

A customer-facing self-service portal can be developed to allow B2B buyers to place orders,
track order status, view credit balance, download order summaries, and access AI-generated
discount recommendations directly without requiring sales executive intervention, reducing
order processing time and improving customer satisfaction.

Deep integration with SAP S/4HANA for finance and procurement modules will enable
automatic invoice generation, payment reconciliation, and purchase order synchronization,
creating a fully connected order-to-cash workflow. Integration with SAP Analytics Cloud will
provide advanced sales performance dashboards, credit utilization trend reports, AI risk score
analytics, and product category revenue breakdowns for strategic management decisions.

A mobile application for sales executives and approvers built on SAP Mobile Development Kit
will enable on-the-go order creation, real-time approval actions, AI risk review, and stock
monitoring from smartphones and tablets, further accelerating B2B sales operations in the field.
Enhanced GDPR compliance features including automated personal data anonymization, data
retention policy enforcement, and audit report exports will strengthen data protection capabilities
as the platform scales across larger enterprise environments.

41
CHAPTER 9
APPENDICES
9.1 SOURCE CODE
/home/user/projects/btp-order-suite/db/[Link]

namespace [Link]; currency : Currency default 'INR';


shippingCity : String(100);
using { Currency, managed, cuid } from '@sap/cds/common'; shippingState : String(100);
shippingPincode : String(10);
// ─── Code Lists notes : String(2000);
─────────────────────────────────────────── approvedBy : String(100);
──────────────────── aiRecommended : Boolean default false;
aiScore : Decimal(5,2);
entity OrderStatus { }
key code : String(20);
name : String(50); entity OrderItems : cuid {
} order_ID : UUID;
order : Association to Orders on [Link] = order_ID;
entity Priority { lineNumber : Integer;
key code : String(10); product_ID : UUID;
name : String(30); product : Association to Products on [Link] = product_ID;
} quantity : Decimal(13,3);
uom : String(10);
entity ProductCategory { unitPrice : Decimal(15,2);
key code : String(20); discount : Decimal(5,2) default 0;
name : String(50); taxRate : Decimal(5,2) default 18;
} netAmount : Decimal(15,2);
taxAmount : Decimal(15,2);
// ─── Master Data lineAmount : Decimal(15,2);
─────────────────────────────────────────── notes : String(500);
─────────────────── }

entity Customers : cuid, managed { // ─── Notes


customerCode : String(20) @mandatory; ────────────────────────────────────────
name : String(100) @mandatory; ────────────────────────────
email : String(100);
phone : String(20); entity Notes : cuid, managed {
gstNumber : String(15); title : String(200) @mandatory;
city : String(100); content : LargeString;
state : String(100); type : String(20) default 'PERSONAL'; // PERSONAL | ORDER
creditLimit : Decimal(15,2) default 500000; order_ID : UUID;
creditUsed : Decimal(15,2) default 0; order : Association to Orders on [Link] = order_ID;
status_code : String(20) default 'ACTIVE'; dueDate : Date;
orders : Association to many Orders on orders.customer_ID = $[Link]; isDone : Boolean default false;
} priority : String(10) default 'MEDIUM'; // LOW | MEDIUM | HIGH
color : String(10) default 'YELLOW'; // YELLOW | BLUE | GREEN |
entity Products : cuid, managed { PINK
sku : String(30) @mandatory; }
name : String(200) @mandatory;
category_code : String(20); // ─── Audit Logs
basePrice : Decimal(15,2) @mandatory; ────────────────────────────────────────
currency : Currency default 'INR'; ───────────────────────
uom : String(10) default 'EA';
stockQty : Integer default 0; entity AuditLogs : cuid {
taxRate : Decimal(5,2) default 18.00; timestamp : Timestamp @[Link]: $now;
isActive : Boolean default true; action : String(50);
} entityType : String(50);
entityId : UUID;
// ─── Orders entityRef : String(50);
─────────────────────────────────────────── actor : String(100);
──────────────────────── oldValue : String(500);
newValue : String(500);
entity Orders : cuid, managed { details : String(1000);
orderNumber : String(20); }
customer_ID : UUID;
customer : Association to Customers on [Link] = customer_ID; // ─── Rules & Regulations
orderDate : Date; ────────────────────────────────────────
requestedDelivery : Date; ─────────────
status_code : String(20) default 'DRAFT';
status : Association to OrderStatus on [Link] = status_code; entity Rules : cuid, managed {
priority_code : String(10) default 'MEDIUM'; ruleCode : String(30) @mandatory;
priority : Association to Priority on [Link] = priority_code; name : String(200) @mandatory;
items : Composition of many OrderItems on items.order_ID = $[Link]; description : String(1000);
subTotal : Decimal(15,2); ruleType : String(30) default 'GENERAL'; // ORDER_VALUE |
taxAmount : Decimal(15,2); CREDIT_LIMIT | APPROVAL | PRODUCT | SHIPPING |
totalAmount : Decimal(15,2); GENERAL
currency : Currency default 'INR'; severity : String(10) default 'INFO'; // INFO | WARNING |
CRITICAL

42
isActive : Boolean default true; [Link]('CREATE', Orders, async (req) => {
threshold : Decimal(15,2); const { Orders: db } = [Link]('[Link]');
minValue : Decimal(15,2); // Year-scoped sequence to avoid cross-year duplicates
maxValue : Decimal(15,2); const year = new Date().getFullYear();
applicableTo: String(200); // ALL | HIGH_VALUE | DRAFT | etc. const count = await [Link]`count(*) as cnt`.from(db)
notes : String(1000); .where`orderNumber like ${'ORD-' + year + '-%'}`;
} const seq = String((count?.cnt ?? 0) + 1).padStart(6, '0');
[Link] = `ORD-${year}-${seq}`;
// ─── Personal Data annotations (GDPR) [Link].status_code = [Link].status_code || 'DRAFT';
──────────────────────────────────────── [Link].priority_code = [Link].priority_code || 'MEDIUM';
[Link] = [Link] || new
annotate Customers with @PersonalData: { Date().toISOString().split('T')[0];
EntitySemantics : 'DataSubject', });
DataSubjectRole : 'Customer'
}{ [Link]('CREATE', Orders, async (data, req) => {
name @[Link]; await _audit('ORDER_CREATED', 'Orders', [Link],
email @[Link]; [Link],
phone @[Link]; null, data.status_code,
} `Order ${[Link]} created`, req);
});
/home/user/projects/btp-order-suite/srv/[Link]
// ── PATCH Order: credit limit + stock management on status
using { [Link] as db } from '../db/schema'; change ──────────
[Link]('PATCH', Orders, async (req) => {
@path: '/odata/v4/order' const newStatus = [Link].status_code;
service OrderService { if (!newStatus) return;

entity Orders as projection on [Link] { const paramKeys = [Link] ?? [];


*, const orderId = paramKeys[[Link] - 1]?.ID ??
[Link] as customerName : String paramKeys[0]?.ID;
}; if (!orderId) return;

entity OrderItems as projection on [Link] { const { Orders: dbOrders, Customers: dbCustomers, OrderItems:
*, dbItems, Products: dbProducts } = [Link]('[Link]');
[Link] as productName : String,
[Link] as productSku : String, const order = await [Link](dbOrders).where({ ID: orderId
[Link] as productBasePrice : Decimal(15,2) });
}; if (!order || order.status_code === newStatus) return;

entity Customers as projection on [Link]; const oldStatus = order.status_code;


entity Products as projection on [Link]; req._statusChange = { orderId, oldStatus, newStatus, orderNumber:
@readonly entity OrderStatus as projection on [Link]; [Link] };
@readonly entity Priority as projection on [Link];
@readonly entity ProductCategory as projection on // ── Credit limit: reserve on SUBMIT
[Link]; ────────────────────────────────────
@readonly entity AuditLogs as projection on [Link]; const creditActiveStatuses = ['SUBMITTED', 'APPROVED',
'IN_PROGRESS', 'SHIPPED'];
entity Rules as projection on [Link]; if (newStatus === 'SUBMITTED' &&
![Link](oldStatus)) {
entity Notes as projection on [Link] { if (order.customer_ID) {
*, const customer = await [Link](dbCustomers).where({ ID:
[Link] as orderNumber : String order.customer_ID });
}; if (customer) {
const available = parseFloat([Link] || 0) -
} parseFloat([Link] || 0);
const orderAmount = parseFloat([Link] || 0);
/home/user/projects/btp-order-suite/srv/[Link] if (orderAmount > 0 && orderAmount > available) {
return [Link](400,
const cds = require('@sap/cds'); `Credit limit exceeded for "${[Link]}". ` +
`Available: ₹${[Link](2)}, Order total: ₹
[Link] = [Link](async function (srv) { ${[Link](2)}`
const { Orders, OrderItems, Products } = [Link]; );
}
// ── Audit log helper await [Link](UPDATE(dbCustomers)
──────────────────────────────────────── .set({ creditUsed: _r(parseFloat([Link] || 0) +
─────────────── orderAmount) })
async function _audit(action, entityType, entityId, entityRef, oldValue, .where({ ID: [Link] }));
newValue, details, req) { req._creditReserved = { customerId: [Link], customerName:
const { AuditLogs } = [Link]('[Link]'); [Link], amount: orderAmount };
const actor = req?.user?.id || req?.user?.name || 'system'; }
try { }
await [Link]([Link](AuditLogs).entries({ }
action, entityType, entityId, // ── Credit limit: release on DELIVERED or CANCELLED
entityRef: entityRef ? String(entityRef).substring(0, 50) : null, ────────────────────
actor: String(actor).substring(0, 100), if (['DELIVERED', 'CANCELLED'].includes(newStatus) &&
oldValue: oldValue != null ? String(oldValue).substring(0, 500) : null, [Link](oldStatus)) {
newValue: newValue != null ? String(newValue).substring(0, 500) : if (order.customer_ID) {
null, const customer = await [Link](dbCustomers).where({ ID:
details: details != null ? String(details).substring(0, 1000) : null order.customer_ID });
})); if (customer) {
} catch (e) { const release = parseFloat([Link] || 0);
[Link]('[Audit] Failed to write log:', [Link]); await [Link](UPDATE(dbCustomers)
} .set({ creditUsed: _r([Link](0, parseFloat([Link] || 0)
} - release)) })

43
.where({ ID: [Link] })); if (req._stockDeducted) {
req._creditReleased = { customerId: [Link], amount: release }; await _audit('STOCK_DEDUCTED', 'Orders', orderId, orderNumber,
} null, null, `Stock deducted for items in order ${orderNumber}`, req);
} }
} if (req._stockRestored) {
await _audit('STOCK_RESTORED', 'Orders', orderId, orderNumber,
// ── Stock: deduct on APPROVED null, null, `Stock restored for items in order ${orderNumber}
─────────────────────────────────────────── (cancelled)`, req);
if (newStatus === 'APPROVED' && oldStatus !== 'APPROVED') { }
const items = await [Link](dbItems).where({ order_ID: orderId }); });

// First pass: validate stock availability // ── CREATE OrderItem


const shortfalls = []; ────────────────────────────────────────
for (const item of items) { ───────────────
if (!item.product_ID) continue; [Link]('CREATE', OrderItems, async (req) => {
const product = await [Link](dbProducts).where({ ID: [Link] = [Link] ?? 0;
item.product_ID }); [Link] = [Link] ?? 18;
if (product) { [Link] = [Link] ?? 1;
const available = parseInt([Link] || 0);
const needed = parseFloat([Link] || 0); const orderId = [Link].order_ID;
if (needed > available) { if (orderId) {
[Link](`${[Link]} (need: ${needed}, stock: ${available})`); const rows = await [Link](OrderItems).where({ order_ID:
} orderId });
} [Link] = (rows?.length ?? 0) + 1;
} }
if ([Link] > 0) {
return [Link](400, `Insufficient stock: ${[Link]('; ')}`); if ([Link].product_ID) {
} const p = await [Link](Products)
.where({ ID: [Link].product_ID })
// Second pass: deduct .columns('basePrice', 'uom', 'taxRate');
for (const item of items) { if (p) {
if (!item.product_ID) continue; [Link] = [Link] || [Link];
const product = await [Link](dbProducts).where({ ID: [Link] = [Link];
item.product_ID }); [Link] = [Link];
if (product) { }
await [Link](UPDATE(dbProducts) }
.set({ stockQty: [Link](0, [Link](parseInt([Link] || 0) -
parseFloat([Link] || 0))) }) _calcItem([Link], [Link]);
.where({ ID: [Link] })); [Link]('[CREATE item] line:', [Link]);
} });
}
req._stockDeducted = true; // ── PATCH OrderItem
} ────────────────────────────────────────
────────────────
// ── Stock: restore on CANCELLED (if was approved/in-progress) [Link]('PATCH', OrderItems, async (req) => {
────────── try {
if (newStatus === 'CANCELLED' && ['APPROVED', 'IN_PROGRESS', const paramKeys = [Link] ?? [];
'SHIPPED'].includes(oldStatus)) { const itemId = paramKeys[[Link] - 1]?.ID ??
const items = await [Link](dbItems).where({ order_ID: orderId }); paramKeys[0]?.ID;
for (const item of items) {
if (!item.product_ID) continue; if ([Link].product_ID) {
const product = await [Link](dbProducts).where({ ID: const p = await [Link](Products)
item.product_ID }); .where({ ID: [Link].product_ID })
if (product) { .columns('basePrice', 'uom', 'taxRate');
await [Link](UPDATE(dbProducts) if (p) {
.set({ stockQty: [Link](parseInt([Link] || 0) + [Link] = [Link];
parseFloat([Link] || 0)) }) [Link] = [Link];
.where({ ID: [Link] })); [Link] = [Link];
} }
} }
req._stockRestored = true;
} if (!itemId) return;
}); const existing = await [Link](OrderItems).where({ ID:
[Link]('PATCH', Orders, async (data, req) => { itemId });
if (!req._statusChange) return; if (!existing) return;
const { orderId, oldStatus, newStatus, orderNumber } = req._statusChange;
_calcItem([Link], existing);
await _audit('STATUS_CHANGED', 'Orders', orderId, orderNumber, ✓
[Link]('[PATCH item] net:', [Link], 'line:',
oldStatus, newStatus, [Link]);
`Order ${orderNumber} moved from ${oldStatus} → ${newStatus}`, req); } catch (err) {
[Link]('[PATCH item] ERROR:', [Link]);
if (req._creditReserved) { }
await _audit('CREDIT_RESERVED', 'Customers', });
req._creditReserved.customerId, orderNumber,
null, String(req._creditReserved.amount), // ── After CREATE/PATCH/DELETE OrderItem → update order
`Credit ₹${req._creditReserved.amount} reserved for totals ─────────────
"${req._creditReserved.customerName}" on order ${orderNumber}`, req); [Link](['CREATE', 'PATCH'], OrderItems, async (data, req) => {
} const orderId = [Link](data) ? data[0]?.order_ID :
if (req._creditReleased) { data?.order_ID;
await _audit('CREDIT_RELEASED', 'Customers', if (orderId) await _recalcOrderTotals(orderId);
req._creditReleased.customerId, orderNumber, });
String(req._creditReleased.amount), null,
`Credit ₹${req._creditReleased.amount} released on order ${orderNumber} [Link]('DELETE', OrderItems, async (req) => {
(${newStatus})`, req); const paramKeys = [Link] ?? [];
} const itemId = paramKeys[[Link] - 1]?.ID ??

44
paramKeys[0]?.ID; const SYSTEM_PROMPT = `You are an intelligent order intelligence
if (itemId) { system for a B2B sales platform in India (currency: INR).
const item = await [Link](OrderItems).where({ ID: itemId }); Analyze the provided sales order and respond with a JSON object
req._deleteOrderId = item?.order_ID; matching this exact schema — no extra keys, no markdown:
}
}); {
"riskScore": <integer 0-100, where 0 = no risk, 100 = extremely high
[Link]('DELETE', OrderItems, async (data, req) => { risk>,
if (req._deleteOrderId) await _recalcOrderTotals(req._deleteOrderId); "riskLevel": <"LOW" | "MEDIUM" | "HIGH" | "CRITICAL">,
}); "flags": [
{ "code": <SHORT_UPPER_SNAKE_CASE string>, "severity":
// ── Startup recalc (local dev only — HANA data is pre-loaded via CSV) <"LOW"|"MEDIUM"|"HIGH">, "message": <one sentence> }
── ],
[Link]('served', async () => { "discountRecommendation": {
if ([Link].VCAP_SERVICES) return; // skip in Cloud Foundry / "suggested": <number, discount % between 0 and 20>,
HANA "reason": <one sentence>
try { },
const allOrders = await [Link]([Link](Orders).columns('ID')); "recommendations": [<actionable string>, ...],
for (const o of allOrders) await _recalcOrderTotals([Link]); "summary": <1-2 sentences overall assessment>
[Link]('[totals] Startup recalc done for', [Link], 'orders.'); }
} catch (e) {
[Link]('[totals] Startup recalc failed:', [Link]); Risk scoring criteria (cumulative):
} - Credit exposure: order amount vs customer's available credit
}); (creditLimit - creditUsed)
- Size anomaly: order value vs customer's historical average order
// ── helpers value
─────────────────────────────────────────── - New customer with high-value first order (no history + large amount)
───────────────────── - Urgent or very short delivery window (< 5 days)
- Single line item with unusually large quantity
function _calcItem(patch, existing) { - Mix of unrelated product categories in one order
const qty = parseFloat([Link] ?? [Link] ?? 0);
const price = parseFloat([Link] ?? [Link] ?? 0); Discount recommendation criteria:
const disc = parseFloat([Link] ?? [Link] ?? 0); - Loyalty (number of past completed orders)
const tax = parseFloat([Link] ?? [Link] ?? 18); - Lifetime spend volume
if (qty <= 0 || price <= 0) return; - Current order size
const net = _r(qty * price * (1 - disc / 100)); - Customer credit health (lower credit usage = healthier)
const taxA = _r(net * (tax / 100)); - Maximum suggested discount should not exceed 15% for high-risk
[Link] = net; orders`;
[Link] = taxA;
[Link] = _r(net + taxA); // ── Main analysis function
} ────────────────────────────────────────
─────────────
async function _recalcOrderTotals(orderId) { async function analyzeOrder(orderId) {
const items = await [Link]([Link](OrderItems).where({ order_ID: const apiKey = getApiKey();
orderId })); if (!apiKey) throw new Error('GROQ_API_KEY not configured. Add
let sub = 0, taxTotal = 0, total = 0; it to [Link] or set the environment variable.');
for (const i of items) {
sub += parseFloat([Link] || 0); const { Orders, OrderItems, Customers, Products } =
taxTotal += parseFloat([Link] || 0); [Link]('[Link]');
total += parseFloat([Link] || 0);
} // Fetch order
await [Link]( const order = await [Link](Orders).where({ ID: orderId
UPDATE(Orders) });
.set({ subTotal: _r(sub), taxAmount: _r(taxTotal), totalAmount: _r(total) }) if (!order) throw new Error('Order not found: ' + orderId);
.where({ ID: orderId })
); // Fetch items + enrich with product info
[Link]('[totals] order', orderId, '→ sub:', _r(sub), 'total:', _r(total)); const rawItems = await [Link](OrderItems)
} .where({ order_ID: orderId })
.columns('lineNumber', 'product_ID', 'quantity', 'unitPrice', 'discount',
function _r(n) { return [Link]((parseFloat(n) || 0) * 100) / 100; } 'taxRate', 'netAmount', 'lineAmount', 'notes')
}); .orderBy('lineNumber');

/home/user/projects/btp-order-suite/srv/[Link] const items = await [Link]([Link](async item => {


if (!item.product_ID) return item;
const cds = require('@sap/cds'); const p = await [Link](Products)
const Groq = require('groq-sdk'); .where({ ID: item.product_ID })
.columns('name', 'sku', 'category_code');
// ── API Key resolution return { ...item, productName: p?.name, productSku: p?.sku, category:
─────────────────────────────────────────── p?.category_code };
────────────── }));
function getApiKey() {
if ([Link].GROQ_API_KEY) return [Link].GROQ_API_KEY; // Fetch customer
try { const customer = order.customer_ID
const env = require('../[Link]'); ? await [Link](Customers).where({ ID:
return env.GROQ_API_KEY || null; order.customer_ID })
} catch { .columns('name', 'creditLimit', 'creditUsed', 'city', 'state', 'gstNumber')
return null; : null;
}
} // Fetch customer order history (last 10, excluding current order)
const history = order.customer_ID
? (await [Link](Orders)

45
.where({ customer_ID: order.customer_ID }) const analysis = [Link]([Link][0].[Link]);
.columns('ID', 'orderDate', 'totalAmount', 'status_code', 'priority_code')
.orderBy('orderDate desc') // ── Persist to DB
.limit(11)) ────────────────────────────────────────
.filter(o => [Link] !== orderId) ──────────────────
.slice(0, 10) const aiScore = [Link](0, [Link](100,
: []; [Link](Number([Link]) || 0)));
await UPDATE(Orders)
const totalLifetimeSpend = [Link]((s, o) => s + .set({ aiScore, aiRecommended: aiScore >= 50 })
parseFloat([Link] || 0), 0); .where({ ID: orderId });
const avgOrderValue = [Link] ? totalLifetimeSpend / [Link]
: 0; [Link](`[AI] Order ${[Link]} → riskScore:
const completedOrders = [Link](o => ['DELIVERED', 'SHIPPED', ${aiScore}, level: ${[Link]}`);
'APPROVED'].includes(o.status_code)).length;
const availableCredit = customer return { ...analysis, riskScore: aiScore };
? parseFloat([Link] || 0) - parseFloat([Link] || }
0)
: null; [Link] = { analyzeOrder, getApiKey };
const orderTotal = parseFloat([Link] || 0);
const creditUsagePct = availableCredit && availableCredit > 0
? ((orderTotal / availableCredit) * 100).toFixed(1) + '%'
: 'N/A';

// Delivery window in days


let deliveryDays = null;
if ([Link] && [Link]) {
const d1 = new Date([Link]);
const d2 = new Date([Link]);
deliveryDays = [Link]((d2 - d1) / (1000 * 60 * 60 * 24));
}

const userPrompt = `Analyze this B2B sales order:

ORDER:
Number: ${[Link]}
Date: ${[Link] || 'N/A'}
Requested Delivery:${[Link] || 'N/A'}${deliveryDays !==
null ? ` (${deliveryDays} days window)` : ''}
Status: ${order.status_code}
Priority: ${order.priority_code}
Sub Total: ₹${[Link]}
Tax Amount: ₹${[Link]}
Total Amount: ₹${orderTotal}

CUSTOMER:
Name: ${customer?.name || 'Unknown'}
Location: ${[customer?.city, customer?.state].filter(Boolean).join(', ') || '–'}
Credit Limit: ₹${customer?.creditLimit ?? 'N/A'}
Credit Used: ₹${customer?.creditUsed ?? 0}
Available Credit: ₹${availableCredit ?? 'N/A'}
Order / Avail Credit: ${creditUsagePct}

CUSTOMER HISTORY:
Total Past Orders: ${[Link]}
Completed/Shipped Orders:${completedOrders}
Total Lifetime Spend: ₹${[Link](2)}
Average Order Value: ₹${[Link](2)}
This Order vs Avg: ${avgOrderValue > 0 ? (orderTotal /
avgOrderValue).toFixed(2) + 'x' : 'First order'}

LINE ITEMS (${[Link]}):


${[Link](i =>
` [${[Link]}] ${[Link] || 'Unknown'} (SKU: ${[Link]
|| '?'}, Cat: ${[Link] || '?'}) | Qty: ${[Link]} | Unit: ₹${[Link]} |
Disc: ${[Link]}% | GST: ${[Link]}% | Net: ₹${[Link]} | Line
Total: ₹${[Link]}`
).join('\n')}

Respond with the JSON schema only.`;

// ── Call Groq
───────────────────────────────────────────
───────────────────
const client = new Groq({ apiKey });
const response = await [Link]({
model: 'llama-3.3-70b-versatile',
messages: [
{ role: 'system', content: SYSTEM_PROMPT },
{ role: 'user', content: userPrompt }
],
response_format: { type: 'json_object' },
temperature: 0.2
});

46
9.2 SCREENSHOTS

47
48
49
50
51
52
53
54
55
CHAPTER 10
REFERENCES

10.1WEBSITE REFERENCES
SAP Business Technology Platform (BTP) Official Documentation –
[Link]
SAP Cloud Application Programming Model (CAP) Documentation –
[Link]
SAP HANA Cloud Documentation – [Link]
SAP Fiori Design Guidelines – [Link]
SAP Authorization and Trust Management Service (XSUAA) –
[Link]
management-service
SAP CAP [Link] Services Documentation – [Link]
SAP OData V4 Protocol Reference –
[Link]
/[Link]
Groq API Official Documentation – [Link]
Groq SDK for [Link] (npm) – [Link]
Meta LLaMA 3.3 70B Model Overview – [Link]
SAP MTA (Multi-Target Application) Build Tool – [Link]
business-technology-platform/multitarget-applications
SAP BTP Cloud Foundry Environment Documentation – [Link]
business-technology-platform/cloud-foundry-environment
[Link] Official Documentation – [Link]
OData V4 Specification (OASIS Standard) – [Link]
SAP HTML5 Application Repository Documentation – [Link]
application-repository

10.2 BOOK REFERENCES

Hanika, J. (2022). SAP Cloud Application Programming Model: Build Enterprise-Grade


Applications with CAP for Java and [Link]. SAP Press.
Drees, H., & Hügens, T. (2021). SAP HANA Cloud: Administration and Operations. SAP
Press.

56
Wood, J. (2023). SAP BTP Solutions: Architecture and Implementation Guide. SAP Press.
Densborn, F., Hrastnik, M., & Seubert, S. (2022). SAP Fiori: The Comprehensive Guide.
SAP Press.
Kimming, A., & Trauthwein, H. (2020). SAP Cloud Platform: An Introduction. SAP Press.
Hfavor, J., & Baumgartl, R. (2021). SAP HANA 2.0: An Introduction. SAP Press.
Densborn, F., & Englbrecht, W. (2022). Developing Apps with SAP Fiori Elements. SAP
Press.
Baumgartl, R., Chauhan, M., & Sinha, A. (2021). SAP Authorization Concept: Practical
Approaches for SAP Security. SAP Press.
Lorenz, M., & Trapp, M. (2022). SAP Integration Suite: The Comprehensive Guide. SAP
Press.
Hfavor, J. (2023). SAP BTP, Cloud Foundry Environment: Development and Operations.
SAP Press.

57

You might also like