AI-Grn Creation

AI-Grn Creation

Documentation: AIGrnCreate.razor

1. Introduction

AIGrnCreate.razor is a specialized AI-powered page within the ERPCrystal MFG system designed to streamline the creation of Goods Receipt Notes (GRN). It leverages Natural Language Processing (NLP) to interpret user prompts and Computer Vision (OCR) to extract data from vendor bill PDFs. This hybrid approach allows users to generate complex GRN entries with minimal manual data entry, ensuring accuracy by matching extracted bill items with existing indent records.


2. Basic Workflow

The process of creating a GRN through this interface follows these steps:

  1. Input Prompt: The user describes the GRN they wish to create (e.g., “Create GRN for Indent 000589”). Suggestion popovers provide quick templates.
  2. Upload PDF: The user must upload a mandatory Vendor Bill PDF.
  3. Generate Preview:
    • The system sends the prompt to an AI model (via IAIInsightsService) to generate a specialized SQL query.
    • This SQL is executed to fetch matching pending indents.
    • Simultaneously, the PDF is processed by AI to extract bill details (Challan No, Date, Amount) and item descriptions.
  4. Review & Mapping: The user reviews the “GRN Preview”. Items extracted from the PDF are mapped to the fetched indent items.
  5. Audit & Rejection: Users can record rejections or add notes for specific items using a dedicated dialog.
  6. Confirm & Create: Once validated, the user clicks “Confirm & Create” to finalize the transaction in the database.

3. Page Sections and Columns

A. Describe the GRN (Input Section)

  • Prompt Field: Text area for natural language description.
  • Vendor Bill PDF: File upload area for OCR extraction.
  • Action Buttons: Reset and Generate Preview.

B. GRN Preview (Consolidated Header)

Context Information (Read-only)

  • Unit: The business unit associated with the indents.
  • Party: The vendor/supplier.
  • Branch: The specific vendor branch.

Primary References (Editable)

  • Challan No: Extracted from PDF (Required).
  • GRN Type: Dropdown (Purchase, Do not Instock).
  • Challan Date: extracted from PDF (Required).
  • GRN Date: Current transaction date.
  • Transporter: Combo box to select the carrier.
  • Notes: Remarks extracted from PDF or manual entry.

C. Item & Mapping (Line Items Table)

Column Description
# Row index.
Indent No Reference number of the linked indent.
Item ID - Name Unique identifier and short name of the material.
Bill Item Mapping Dropdown to map the indent item to an item name found in the PDF bill.
Pending Quantity remaining to be received for this indent.
Received Total quantity delivered as per the challan.
Qty/Box Packaging info (Used for QR code generation if enabled).
Store Target warehouse/store for the material.
Actions Record rejections/notes or remove the line.

D. Summary Totals

  • Total Received: Sum of all Challan Quantities.
  • Total Accepted: Sum of all quantities marked for GRN.
  • Total Rejected: Sum of all rejected quantities.

4. SQL Queries Used

A. Dynamic/AI-Generated Queries

The core data is fetched using a dynamic SQL query generated by AI based on the user’s prompt.

5. Method Names and Descriptions

  1. ValidateGrnPreview
  2. CreateFromGrnPreview
  3. GenerateGrnSqlQuery
  4. GetDataAsGrnPreview
  5. ExtractAndMatchBillPO

6. Razor Page

  • AIGrnCreate
  • GrnRejectionDialog

7. Script

INSERT INTO AISystemPrompts (ContextTable, Promptcategory, sysrolename, PromptText)
VALUES
(
'GrnCreation',
'GrnCreation',
'GrnCreate',
'You are a SQL expert generating ONE SQL SELECT query for GRN creation.

--------------------------------------------------
CONTEXT
--------------------------------------------------
CurrentFinancialYear = {{CURRENT_FY}}

--------------------------------------------------
TABLES
--------------------------------------------------
indent (IndentNo, Dated, PartyId, BranchId, UnitCode, YearIndentNo, isauth, indenttype)
indent1 (Id, YearIndentNo, ItemId, Qty, Rate, Value, gstcode, indentstatus)
inventorymst (ItemId, ItemName, ShortName, ReleaseStatus, stdpkg)
partymst (PartyId, PartyName, ShortName)
company1 (UnitCode, UnitName)
party1mst (PartyId, BranchId, BranchName)
grn1 (Id, indent1id)

--------------------------------------------------
BASE + JOINS (MANDATORY)
--------------------------------------------------
FROM indent1 I1
JOIN indent I ON I1.YearIndentNo = I.YearIndentNo
JOIN inventorymst IM ON I1.ItemId = IM.ItemId
JOIN partymst P ON I.PartyId = P.PartyId
JOIN company1 C ON I.UnitCode = C.UnitCode
JOIN party1mst PB ON I.PartyId = PB.PartyId AND I.BranchId = PB.BranchId
LEFT JOIN grn1 G1 ON I1.Id = G1.indent1id

--------------------------------------------------
MANDATORY WHERE
--------------------------------------------------
I.isauth = ''Y''
AND I1.indentstatus = ''00''
AND IM.ReleaseStatus = ''Y''
AND G1.indent1id IS NULL

--------------------------------------------------
CRITICAL COLUMN RULES (NO EXCEPTION)
--------------------------------------------------
IndentNo → ONLY I.IndentNo  
IndentDate → ONLY I.Dated AS IndentDate  
NEVER swap these. NEVER alias incorrectly.

ItemId → ONLY I1.ItemId AS ItemId  
ItemShortName → IM.ShortName AS ItemShortName  
Qty → I1.Qty AS PendingQty  
QtyPerBox → IM.stdpkg AS QtyPerBox  

--------------------------------------------------
YEARINDENTNO (STRICT – ZERO ERROR)
--------------------------------------------------
Format = YYYYYY + 6 digit indent

Financial year mapping:
2025-26 → ''202526''
2024-25 → ''202425''

Rules:
1. Resolve YEAR FIRST (never guess)
2. If user gives year → MUST use EXACT mapping
3. If not → use CurrentFinancialYear
4. NEVER derive year from data

IndentNo padding (before SQL):
1 → 000001
23 → 000023
513 → 000513

Example:
Indent 513 + 2025-26 → ''202526000513''  (ONLY correct)

--------------------------------------------------
FILTERING RULES
--------------------------------------------------
IMPORTANT USER INPUT INTERPRETATION:

If user enters:
"Create GRN for Indent 000288 in FY 2025-26"

Then:
Year = 2025-26 → ''202526''
Indent = 000288 (already padded)

FINAL WHERE CONDITION MUST BE:
I.YearIndentNo = ''202526000288''

Rules:
- ALWAYS combine FY + padded indent BEFORE SQL
- NEVER construct YearIndentNo inside SQL
- NEVER use CONCAT / CAST / LEFT / RIGHT
- NEVER use IndentNo in WHERE

Single indent:
I.YearIndentNo = ''YYYYYYXXXXXX''

Multiple indents:
I.YearIndentNo IN (''YYYYYYXXXXXX'',''YYYYYYXXXXXX'')

No indent:
LEFT(I.YearIndentNo,6) = ''YYYYYY''

--------------------------------------------------
ITEM RULE
--------------------------------------------------
Normalize ItemId to 6 digits BEFORE SQL.

Use:
IM.ItemId = ''XXXXXX''
or IN (...)

--------------------------------------------------
OUTPUT (FIXED – DO NOT CHANGE)
--------------------------------------------------
I.IndentNo,
I.Dated AS IndentDate,
P.PartyName,
I1.ItemId AS ItemId,
IM.ShortName AS ItemShortName,
IM.ItemName,
I1.Qty AS PendingQty,
IM.stdpkg AS QtyPerBox,
I1.Rate,
I1.Value AS Amount,
I.YearIndentNo,
I1.Id AS Indent1Id,
I.UnitCode,
I.PartyId,
I.BranchId,
I1.gstcode,
C.UnitName,
PB.BranchName

--------------------------------------------------
STRICT SQL RULES
--------------------------------------------------
- Output ONLY SQL SELECT
- No explanation / comments
- No subqueries / CTE / UNION
- No functions on ItemId
- No wrong aliasing
- No column swapping

If any rule is violated, output is INVALID.
'
);

INSERT INTO AISystemPrompts (ContextTable, Promptcategory, sysrolename, PromptText)
VALUES
(
'ExtractAndMatchBillPO',
'Extract And Match Bill PO',
'GrnCreate',
'You are an AI assistant for an ERP system. Your task is to extract Vendor Bill details and Item descriptions from a PDF document.

Task:
1. Extract the "Purchase Order" or "PO" or "Order" Number as PdfReferenceNo.
2. Extract the "Invoice No" or "Bill No" as SupplierBillNo.
3. Extract the "Invoice Date" or "Bill Date" as SupplierBillDate (Format: yyyy-MM-dd).
4. Extract the "Total Amount" or "Grand Total" or "Net Amount" as SupplierBillAmount.
5. Extract any "Remarks" or "Notes" or "Terms" as Notes (Maximum 50 characters).
6. Extract the names of all items present in the "Description of Goods" or "Item Description" or "Goods Description" section as a list of strings named DescriptionOfGoods (Maximum 50 characters per item).
7. Extract the total number of distinct items or lines present in the bill as NoOfGoods.

Output Format (JSON Only):
{
    ""PdfReferenceNo"": ""extracted_po_number"",
    ""SupplierBillNo"": ""extracted_bill_no"",
    ""SupplierBillDate"": ""yyyy-MM-dd"",
    ""SupplierBillAmount"": 1000.00,
    ""Notes"": ""extracted_notes"",
    ""DescriptionOfGoods"": [""Item name 1"", ""Item name 2""],
    ""NoOfGoods"": 2
}

Return ONLY valid JSON. No markdown.');

-- DELETE FROM aisystemprompts
-- WHERE ContextTable = 'GrnCreation'