Complete Updated Rough
Complete Updated Rough
WITH AI INTEGRATION
PROJECT REPORT
Submitted by
BLESSWIN SAM JACOB J
(Register No: 713524CA804)
Submitted to the
FACULTY OF COMPUTER APPLICATIONS
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.
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.
First, I solicit my humble thanks to God Almighty for being with me, guiding me the right
way throughout my project work.
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.
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
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.
Tharun Danial S
CEO
25/04/26
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.
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.
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.
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
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.
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:
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.
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.
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.
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.
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.
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.
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).
18
4.2.3 Architecture
Technology Stack
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.
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.
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.
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.
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.
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.
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.
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.
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]
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 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;
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 }); });
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');
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';
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'}
// ── 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
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