Core System Competencies

Operational Utilities.

A systematic breakdown of process frameworks, live data orchestration pipelines, and analytical data layers mapped by primary technology architecture. Click any card to examine implementation frameworks.

Excel / Power Query / VBA

Financial Incentive Reconciliation Suite

Constructed systematic audit environments with dynamic Power Query extractions and targeted VBA automation macro runs to process monthly logistics balances across multi-district systems.

๐ŸŽฏ99%Accuracy
๐Ÿ”85%Automation
โšก90%Efficiency
Technical Execution Details
  • ">ETL Automation: Extracted disparate district performance logs using modular M-code parameters to align schema formats.
  • ">Logic & Auditing: Built VBA scripts converting volatile analytical arrays to static values to streamline document performance.
  • ">Reconciliation: Programmed multi-tier verification conditional workflows ensuring accurate incentive payouts.
Explore Workbook Blueprint
View Implementation Details
Excel / Office Scripts / TypeScript

Autonomous Treasury & Ledger Engine

Engineered a cloud-native Office Scripts engine that ingests raw ERP general ledgers and provisions 200+ individual vendor ledger sheets, aging matrices, and a bi-directional hyperlinked master dashboard in a single click.

โšก98%Performance
๐Ÿ›ก๏ธ100%Reliability
๐Ÿ“ˆ95%Scalability
1. The Challenge (The Pain Points)

Paying 200+ vendors per week through digital banking portals traps the treasury team in "Portal Hell" โ€” manually clicking Pay, typing account numbers, and verifying amounts hundreds of times under deadline pressure, where a single fat-finger typo can misroute millions. Bulk payment templates solve the throughput problem but introduce a worse one: there is no audit trail, no bill aging, and no way to spot an overpayment before the file hits the bank. Building 200 verification ledgers manually in Excel collapses under its own weight โ€” by sheet 50 the file is crashing and the data is already stale.

2. The Solution (How the Office Scripts Engine Works)
  • Virtual DOM Batching: Ingests the raw ERP general ledger into an in-memory array matrix and processes filtering + aging buckets (0โ€“30 / 31โ€“60 / 61+ days) before rendering a single cell โ€” no line-by-line writes, no UI flicker.
  • Programmatic Sheet Factory: Uses the ExcelScript.Workbook API to provision or refresh per-vendor sheets dynamically, with strict string sanitization to strip illegal characters (:, \, /) and clip names to Excel's 31-char tab limit.
  • Bi-Directional Hyperlink Matrix: Captures each vendor's exact cell coordinate on the Master Summary and binds a deep link to cell A4 of the new ledger sheet, while injecting a "โฌ…๏ธ Back to Master Dashboard" anchor at A1 of the destination โ€” eliminating the friction of hunting through 200 tabs.
  • Async Cloud Execution: Runs on Office Scripts' V8 engine instead of legacy desktop VBA, so the workbook never freezes the user's machine and the routine can be chained into Power Automate flows.
3. Optimized Engine Blueprint
TypeScript
async function main(workbook: ExcelScript.Workbook) {
    let summarySheet = workbook.getWorksheet("Master Summary");
    let glData = workbook.getWorksheet("Raw GL Data").getUsedRange().getValues();

    // Systems Engineering Rule: Batch-filter in memory to protect system threads
    let activePayments = glData.filter(row => Number(row[3]) > 500);

    activePayments.forEach((vendor) => {
        let cleanName = sanitizeVendorName(vendor[1].toString());

        // Asynchronous Workspace Provisioning
        let targetSheet = workbook.getWorksheet(cleanName)
            ?? workbook.addWorksheet(cleanName);
        targetSheet.getRange("A4").setValues([/* Filtered Ledger Array Block */]);

        // Injecting the Bi-Directional Navigation Pointer Matrix
        bindDeepLink(summarySheet, targetSheet, "Audit Ledger");
        bindDeepLink(targetSheet, summarySheet, "โฌ…๏ธ Back to Dashboard");
    });
}
4. Impact & Results
โšก Warp Speed Execution: Days of error-prone copy-paste collapsed into a sub-10-second one-click run. ๐Ÿ›ก๏ธ Absolute Capital Security: Finance can teleport into any vendor ledger, verify 60-day aging, and approve the master payment block with full audit lineage. โ™พ๏ธ Infinite Scalability: 200 vendors this week or 2,000 next month โ€” the operator workload stays at one click.
View Implementation Details
Excel / VBA / Workbook Hardening

Power Query & Connection Stripper โ€” Table-Safe Workbook Freezer

Engineered a one-shot VBA hardening macro that strips every Power Query and workbook connection from a live Excel file, freezes table bodies and totals rows into static values, and preserves every ListObject โ€” name, structure, headers โ€” so the deliverable workbook is portable, dependency-free, and audit-stable.

๐Ÿ›ก๏ธ100%Reliability
๐ŸŽฏ98%Accuracy
๐Ÿ”95%Automation
1. The Story โ€” The Workbook Hands Off, the Query Doesn't

The deliverable is a clean Excel workbook for the auditor, or the regional manager, or the bank. The reality on the analyst's machine is a chain of Power Queries pulling from a network folder, three workbook connections to legacy CSVs, and a totals row whose formula references a query column. The receiver opens it, sees the "External data refresh failed" toast, watches every table go blank, and assumes the analyst sent broken work. The macro fixes this at the source: freeze every value, preserve every table, then strip every query and connection so what ships is exactly what the analyst saw.

2. The Architecture โ€” Freeze First, Strip Second
  • Order matters: the macro freezes DataBodyRange and TotalsRowRange values before deleting queries โ€” so when the underlying query disappears, the table cells already hold their evaluated values instead of #REF!.
  • Tables stay tables: every ListObject is preserved as a real Excel Table โ€” not converted to a plain range โ€” so structured references, banded formatting, and table names continue to work after the strip.
  • Name fidelity: the original lo.Name is captured into a local variable and re-asserted after the value freeze, defending against Excel auto-renaming on refresh-state changes.
  • QueryTable defanged, not destroyed: instead of deleting the QueryTable behind a table (which would void the ListObject), the macro disables every refresh trigger โ€” EnableRefresh, RefreshOnFileOpen, BackgroundQuery โ€” and forces SaveData = True.
  • Reverse-iteration delete: Power Queries and workbook connections are deleted from Count down to 1 โ€” the only safe way to walk a collection that shrinks as you delete from it.
  • Performance + safety envelope: wraps the run in ScreenUpdating = False, DisplayAlerts = False, EnableEvents = False, and a labeled error handler that restores all three before surfacing any failure to the user.
3. The Freeze Step โ€” Why the Order of Two Lines Matters

Every cell in the table body is reassigned to itself โ€” the classic VBA idiom that evaluates each formula and writes back its result. Same for the totals row. After this runs, every cell is a literal value:

VBA ยท Value Freeze (excerpt)
If Not lo.DataBodyRange Is Nothing Then
    lo.DataBodyRange.Value = lo.DataBodyRange.Value   ' formulas โ†’ values
End If

If lo.ShowTotals Then
    lo.TotalsRowRange.Value = lo.TotalsRowRange.Value  ' totals โ†’ values
End If

' Defang the QueryTable instead of deleting it (keeps the ListObject intact)
On Error Resume Next
lo.QueryTable.EnableRefresh       = False
lo.QueryTable.RefreshOnFileOpen   = False
lo.QueryTable.BackgroundQuery     = False
lo.QueryTable.SaveData            = True
On Error GoTo CleanFail

lo.Name = tblName   ' re-assert original name
4. The Strip Step โ€” Walking the Collection Backwards

Iterating For Each q In wb.Queries and deleting inside the loop is the textbook way to skip half the items as the collection re-indexes. The macro counts down instead:

VBA ยท Reverse-Iteration Strip (excerpt)
' Power Queries
For i = wb.Queries.Count To 1 Step -1
    wb.Queries(i).Delete
Next i

' Workbook Connections
For i = wb.Connections.Count To 1 Step -1
    wb.Connections(i).Delete
Next i
5. The Discipline โ€” Three Rules That Make This Audit-Safe
  • Confirmation gate: a vbYesNo MsgBox blocks accidental runs โ€” the operation is permanent and irreversible by design.
  • State restoration on failure: the CleanFail handler restores ScreenUpdating, DisplayAlerts, and EnableEvents before showing the error, so Excel never gets left in a half-disabled state.
  • Final save as .xlsx: documented post-step โ€” convert from .xlsm so the deliverable contains no VBA storage at all, exactly matching the "no macros, no queries, no connections" promise.
6. Impact & Results
๐Ÿ“ฆ Portable Deliverable: workbook opens cleanly on any machine โ€” no refresh errors, no broken connections, no missing source paths. ๐Ÿงพ Audit-Stable: every value is literal at the moment of hand-off, so the receiver sees exactly what the analyst certified. ๐Ÿ›ก๏ธ Tables Preserved: ListObjects, names, headers, and totals rows all survive โ€” structured references and downstream lookups keep working.
View Implementation Details
Excel + Power Query / Settlement ETL

Outdoor Exchange Mela Incentive & Additional-Valuation Settlement Engine

Architected a hybrid Excel + Power Query settlement workbook that ingests SharePoint retail-sales feeds, dynamically imports OneDrive mela files per Windows user, performs chassis-level reconciliation across four sources, applies a dynamic scheme-rate matrix, and emits dealer-wise incentive, credit-note, and additional-valuation outputs with management dashboards.

๐Ÿ”95%Automation
๐Ÿ“Š92%Effectiveness
๐ŸŽฏ94%Accuracy
1. The Story โ€” Three Data Sources, One Settlement Sheet

An Outdoor Exchange Mela ends, and within days finance needs a dealer-wise credit note: how many bikes each dealer sold, how many were cash vs finance vs exchange, which ones qualify under the scheme window (including the extended 20-day grace period), and how much incentive plus additional valuation each dealer is owed. The data sits in three different homes โ€” retail sales on SharePoint, mela attendance in a per-user OneDrive folder, and the festive scheme/coupon master inside the workbook. The engine pulls all three, matches chassis numbers across them, runs the dynamic rate matrix, and produces a credit-note-ready output plus a management dashboard in one refresh.

2. The Architecture โ€” 21 Power Queries on Three Source Tiers
  • Tier 1 ยท SharePoint Excel: Retail Sales FY 25โ€“26 + 26โ€“27, Dealer Master / System mapping, Bike Item lookup โ€” pulled live so the model never goes stale on the source side.
  • Tier 2 ยท Local OneDrive Folder: the mela files ("Additional Valuation Outdoor Exchangeโ€ฆ") imported dynamically from the user's machine โ€” folder path built from the Tbl_User control table so the same workbook ports across machines.
  • Tier 3 ยท In-Workbook Controls: scheme dates, dealer whitelist, extended-days parameter, and the rate matrix (Cash / Finance / Exchange / Additional Valuation) all live in the Criteria sheet for non-technical operators.
  • Performance discipline: Table.Buffer and Binary.Buffer deployed at the hot spots โ€” folder enumeration, sales joins, the matched-chassis output โ€” so each refresh stays sub-second on a normal laptop.
3. The Settlement Brain โ€” Dynamic Scheme Column & Unpivot-Then-Join

The single cleverest move in the workbook: the Additional Valuation Settlement query reads the third column of the rate-matrix table as the active scheme column by index, not by hard-coded name. Whatever the next scheme is called โ€” "Festive Scheme", "Dashain Bonanza", "New Year Mela" โ€” the engine reuses without code changes. The matrix is then unpivoted into a long lookup table and joined back against matched chassis records to pull the correct per-mode rate:

Power Query ยท Dynamic Scheme Column (excerpt)
// Identify the active scheme column by position, not name
SchemeColName = Table.ColumnNames(Extra){2},

// Long-form lookup matrix
Unpivoted = Table.UnpivotOtherColumns(
                Extra, {"Target"}, "Mode", "Rate"),

// Per-row TargetRow resolution
TargetRow =
    if [ACTUALLY EXCHANGED] = "yes"           then "Exchange"
    else if [Mode of Purchase] = "Cash"       then "Cash"
    else if [Mode of Purchase] = "Finance"    then "Finance"
    else                                            "Additional Valuation"
4. The Excel Layer โ€” Dynamic Arrays, Not Static Reports
  • Spilled dealer summary: the Summary sheet's dealer performance table is one LET expression at A7 that spills via UNIQUE + FILTER + VSTACK + HSTACK โ€” add a dealer, the table grows itself.
  • Named formulas as primitives: AddSumDealerWise, Incentive_Criteria, and Remarks behave like functions โ€” invoked across sheets so the same logic never duplicates.
  • Credit-note grouping: CrNoteFormat aggregates dealer ร— item ร— cash/finance qty into the exact shape an SAP credit-note batch expects.
5. The Reconciliation Net โ€” Chassis Matched vs Unmatched

Two parallel queries โ€” Matched Chasis (inner join on DistNumber = Chassis No) and Unmatched Chasis (left join, anti-match) โ€” give finance a built-in reconciliation: every sales-team row should land in exactly one bucket. The Insights sheet asserts Sales = Matched + Unmatched on every refresh, flagging mismatches as FAIL before anyone trusts the output.

6. Impact & Results
๐Ÿ“ฆ Three Sources โ†’ One Workbook: SharePoint sales + OneDrive mela files + in-book controls all refresh into one credit-note-ready output. ๐Ÿ” Scheme-Reusable: dynamic third-column lookup means the next mela / festive scheme drops in without M-code changes. ๐Ÿ›ก๏ธ Built-In Reconciliation: Matched + Unmatched must equal Sales on every refresh โ€” the workbook polices itself before finance signs off.
View Implementation Details
Power Query / Portable Folder Importer Pattern

Username-Driven Dynamic OneDrive Folder Importer (Reusable PQ Pattern)

Engineered a reusable Power Query pattern that builds its own OneDrive folder path from a Tbl_User control cell, scans the resolved folder, filters files by a contains-token rule, and invokes a sample-file transform โ€” so the same workbook works on any analyst's machine without re-pointing the data source.

๐Ÿ”100%Automation
๐Ÿ“ˆ96%Scalability
๐Ÿ›ก๏ธ94%Reliability
1. The Story โ€” "It Worked on My Machine"

The most common Excel automation failure isn't logic โ€” it's a hard-coded folder path like C:\Users\aabhash.adhikari.GOLCHHAGROUP\OneDriveโ€ฆ that breaks the moment the workbook lands on a colleague's laptop. The fix isn't to share less; it's to make the path itself a parameter. This pattern lifts the Windows username into a one-cell control table, lets Power Query rebuild the OneDrive path on every refresh, and applies a token-based filter so only the relevant files are pulled.

2. The Architecture โ€” Six Queries That Plug Into Anything
  • Tbl_User โ€” single-row Excel table holding the Windows username. The only thing a new operator changes when adopting the workbook.
  • Parameter1 โ€” concatenates the username into the full OneDrive folder path. Returns a string the rest of the queries consume.
  • Sample File โ€” pulls one file from the folder so Power Query can infer schema and let the user build a Transform Sample File visually.
  • Transform Sample File โ€” the per-file transformation, designed once against the sample and reused as a function.
  • Transform File โ€” the function wrapper Power Query auto-generates to apply Transform Sample File to every file in the folder.
  • The consumer query (e.g., Outdoor Exchange Mela) โ€” does Folder.Files, filters by a token (Text.Contains), calls Transform File, expands, buffers.
3. The Path Rebuilder โ€” Why Parameter1 Is the Whole Trick

One line of M-code is the entire pattern. The username becomes a variable; the rest of the path is a literal that surrounds it:

Power Query ยท Path Rebuilder (excerpt)
// Tbl_User holds one row, one column: [User]
User      = Record.Field(Tbl_User{0}, "User"),

// Rebuild the full OneDrive folder path per-machine
FolderUrl =
    "C:\Users\" & User &
    "\OneDrive - Golchha Group\โ€ฆ\Outdoor Exchange Mela\",

// Filter the folder to just the files we want
Files     = Folder.Files(FolderUrl),
Relevant  = Table.SelectRows(Files, each
              Text.Contains([Name], "Additional Valuation Outdoor Exchange"))
4. The Discipline โ€” Three Rules That Make This Reusable
  • One control cell, not one control sheet: Tbl_User is intentionally minimal โ€” one row, one column โ€” so adoption is "change this value, refresh". No training required.
  • Token filter, not full-path filter: Text.Contains([Name], "Additional Valuation Outdoor Exchange") means filenames can drift (date suffixes, version markers) without breaking the import.
  • Buffer at the join boundary: Table.Buffer and Binary.Buffer sit right after the folder scan and right before the join โ€” so the disk is touched once per refresh, not once per row.
5. Impact & Results
๐Ÿ’ป Machine-Portable: change one cell, the workbook resolves the new operator's full OneDrive path automatically. ๐Ÿชถ Pattern, Not Project: lift this six-query block into any folder-driven Excel model โ€” schemes, branch imports, monthly bank dumps โ€” without rewrite. โšก Buffered for Speed: folder enumeration and per-file transforms cached so refresh stays snappy on a normal laptop.
View Implementation Details
Excel + Power Query / Settlement Decision Engine

Dealer Cash Discount ร— Interest Settlement Engine (Multi-Window Credit-Day Model)

Architected a monthly dealer settlement engine that fuses raw ledger ingestion, dealer-master mapping, exchange-sales adjustments, and four parallel credit-day pipelines (30/45/60/90-day) to compute cash discount, compare it against 12% interest, apply 15% TDS, and emit a single credit-or-debit verdict per dealer โ€” covering 23,600+ ledger rows and ~444k formula cells in one refresh.

๐Ÿ“Š95%Effectiveness
๐ŸŽฏ96%Accuracy
โš–๏ธ97%Compliance
1. The Story โ€” Discount or Interest? Pick One Per Dealer

At month-end the same accounting question arrives 100+ times โ€” once per dealer: did they pay early enough to earn a cash discount, or did they sit on the balance long enough to owe interest? Both can never be true at once. The legacy answer was to hand-build 30/45/60-day windows in pivot tables, eyeball running balances, and pray nobody mis-keyed an exchange entry. The engine collapses all of that into one Excel workbook with a single deterministic verdict: Amount to be Credited if cash discount wins, Amount to be Debited if interest wins, never both.

2. The Architecture โ€” 36 Power Queries Feeding 21 Excel Tables
  • Source layer: FilesLocation reads the SharePoint folder URL from a one-cell control table, appends Raw Data for Cash Dis.xlsx, and pulls the raw ledger binary โ€” month-rollover is a path edit, not a query rewrite.
  • Dealer master split: three forked queries โ€” DealerNameCode, ExchangeDealerNameCode, DealerNameCodewithoutExchange โ€” encode the eligibility logic at the master-data level instead of polluting downstream calc with conditionals.
  • Four parallel credit-day pipelines: ***A/r Incoive (3) (30-day), (4) (45-day), (5) (0-day / same-day), (6) (90-day) โ€” each pipeline classifies invoices by descriptor tokens (Sports, Commuter, Credit Memo) and routes them to the right window.
  • Exchange-side adjustments: ExchangeDateToDecreaseSales and siblings isolate exchange entries, swap debit/credit columns where required, set offset account 4119999, and tag rows with synthetic offset names so the sales base used for discount is exchange-corrected.
  • Final aggregates: Final (2) through Final (6) stitch the streams into the loaded tables โ€” TD_Final (30 Days), FFcalc (45 Days), SDcalc (60 Days), Int (Interest) โ€” that the Excel formula layer consumes.
3. The Settlement Brain โ€” Discount vs Interest, One Verdict

The Summary sheet is where the verdict gets sealed. Three discount rates (0.75% ยท 0.25% ยท 0.50%) are applied across the three windows; interest accrues at 12% on running balance ร— days. Then a single comparison decides which side wins:

Excel ยท Settlement Verdict (concept excerpt)
=LET(
   cd,    SUMIFS(_30Days) + SUMIFS(_45Days) + SUMIFS(_60Days),
   int_,  XLOOKUP(dealer, Int[Dealer], Int[Interest12]),
   tds,   ROUND(cd * 0.15, 2),

   IF( cd > int_,
       cd - tds,           // Amount to be Credited
       -(int_ - cd) ))     // Amount to be Debited

Three discount windows in, one interest figure in, one TDS deduction applied โ€” and the sign of the result tells finance which side of the credit-note batch the dealer lands on.

4. The Audit Layer โ€” The Check Sheet Polices the Workbook
  • Source-to-output tie-out: SUMPRODUCT and SUMIFS stacks confirm that the raw ledger sales total reconciles back to the per-dealer settlement total โ€” divergence flags a routing bug before anyone signs off.
  • Cross-window non-overlap check: a dealer's transactions should appear in exactly one credit-day window per invoice; the Check sheet asserts no double-counting between 30/45/60/90-day pipelines.
  • Exchange offset trace: every adjustment posted to account 4119999 is summed back against the exchange-dealer subset of the raw ledger.
  • Bank receipt vs discount sanity: dealer-wise SUMPRODUCT compares bank receipts to calculated cash discount, surfacing the rare case where a discount is being credited to a dealer who never paid.
5. The Output Stack โ€” Five Settlement Artifacts From One Refresh
  • Main Summary โ€” dealer-wise credit/debit verdict, TDS, net cash discount, and interest comparison.
  • Challlan CD โ€” CHL dealer challan summary with earned CD and net-of-TDS amount.
  • CD Cr ยท IntRebate ยท Allocation Billing โ€” manual freeze, interest rebate, and allocation adjustments โ€” kept as standalone tables so audit can trace overrides without hunting through formula trees.
  • Per-window calc sheets (30 Days ยท 45 Days ยท 60 Days ยท Interest) โ€” full transparency on how each verdict was reached.
6. Impact & Results
โš–๏ธ One Verdict Per Dealer: cash discount vs 12% interest reduced to a single signed number per dealer โ€” credit or debit, never both. ๐Ÿงฎ 23,600+ Rows Per Refresh: the full month's ledger collapses through four credit-day pipelines and a TDS layer in one click. ๐Ÿ›ก๏ธ Self-Policing: the Check sheet ties source ledger to settlement output before finance signs the credit-note batch.
View Implementation Details
Power Query / Reusable Ledger Normalizer Pattern

Reversal-Aware Raw Ledger Normalizer (Composite-Key Pairing Pattern)

Engineered a reusable Power Query pattern that ingests raw SAP-style accounting ledgers, builds composite transaction keys, detects mirrored reverse entries, labels them so downstream calculations can ignore the pair as a unit, and buffers the result โ€” turning a noisy ledger into a clean, reversal-tagged base table any settlement model can join against.

๐Ÿ›ก๏ธ99%Reliability
๐ŸŽฏ97%Accuracy
โšก94%Performance
1. The Story โ€” The Phantom Sale That Wasn't

Every raw accounting ledger carries a hidden trap: reversed entries. The original invoice posts. A correction follows that posts the exact opposite โ€” same dealer, same amount, opposite sign. If a settlement calculation treats both rows as real, the dealer either gets paid twice or paid for nothing. The Excel formula layer can't see this; it just sees rows. The normalizer fixes it inside Power Query by detecting reversal pairs deterministically and tagging them at the source โ€” so every downstream calc can choose to exclude them with a single filter.

2. The Pattern โ€” Six Steps, One Clean Base Table
  • Column projection & type coercion: select only the ledger columns settlement actually needs; force every numeric to a number, every date to a date โ€” so silent type drift can't corrupt later math.
  • Uppercase normalization: dealer names, references, narrations all upper-cased โ€” defends against the trailing-space + case-drift bug that produces phantom duplicates.
  • Composite key construction: a synthetic key concatenates Date + Account + |Amount| + Dealer so an entry and its mirror reversal land on the same key value regardless of sign.
  • Reverse-transaction detection: Table.Group on the composite key with a row counter โ€” keys with count > 1 where debit/credit signs flip are flagged as reversal pairs.
  • Reversal labeling: a new IsReversalPair column carries forward into the output, so any downstream query can filter with one line of M.
  • Buffer + cleanup: Table.Buffer at the end so the join boundary touches RAM, not disk; helper key columns dropped to keep the schema lean.
3. The Composite Key โ€” The Trick That Catches Reversal Pairs

The single line that defines the pattern. Take the absolute value of the amount before concatenating โ€” so the +1,000 invoice and the โˆ’1,000 correction share one key:

Power Query ยท Composite Key (excerpt)
// Sign-blind composite key
AddedKey = Table.AddColumn(Source, "PairKey", each
    Text.From([Date]) & "|" &
    [Account]         & "|" &
    Text.From(Number.Abs([Debit] - [Credit])) & "|" &
    Text.Upper(Text.Trim([Dealer])) ),

// Count how many rows share the key
WithCount = Table.Group(AddedKey, {"PairKey"},
    {{"PairCount", each Table.RowCount(_), Int64.Type},
     {"Rows",      each _, type table}}),

// Flag >1 as reversal pair candidates
Flagged = Table.AddColumn(WithCount, "IsReversalPair",
    each [PairCount] > 1, Logical.Type)
4. The Discipline โ€” Three Rules That Make This Trustworthy
  • Detect, don't delete: reversal pairs stay in the output table โ€” they're flagged, not removed. The settlement layer decides whether to exclude them; audit can still see what happened.
  • Buffer once, at the join boundary: Table.Buffer sits exactly where the next query will join โ€” not earlier (wastes RAM), not later (touches disk twice).
  • Sign-blind, type-strict: the key is sign-blind so reversal mirrors collide; column types are strict so a stray text in an amount column fails loudly instead of silently.
5. Impact & Results
๐Ÿšซ No Phantom Doubles: reversal pairs are tagged at the source โ€” downstream settlement / interest / discount calcs filter them out with one line. ๐Ÿชถ Drop-In Reusable: lift this six-step normalizer into any SAP-style ledger model โ€” cash discount, interest, TDS, BP exposure โ€” without rewrite. โšก Buffer-Right: Table.Buffer placed at the join boundary so a 23,000-row ledger normalizes in seconds, not minutes.
View Implementation Details
Excel + Power Query / SAP Journal-Entry Generator

Target Incentive Journal-Entry Generator (One Input Row โ†’ Balanced SAP Posting)

Engineered a Power Queryโ€“driven posting template that takes a single dealer incentive / cash-discount input row, enriches it via SharePoint dealer + TDS + department masters, applies a configurable incentive-vs-payable split from a control Clause table, and emits a balanced three-line SAP-ready journal entry (Expense Dr / TDS Cr / Dealer Cr) with Series, Remark, and Project fields auto-populated.

๐ŸŽฏ100%Accuracy
โš–๏ธ98%Compliance
๐Ÿ”95%Automation
1. The Story โ€” One Row In, A Balanced Voucher Out

Every month accounts types the same three lines for every dealer incentive: debit the expense ledger, credit the TDS account at 15%, credit the dealer BP for the net. Same shape, different numbers, multiplied by however many dealers earned an incentive that period. The generator collapses that ritual to a single input row โ€” Reg Code, Dealer Name, Net, TDS, Amount to be Credited, Month, Remark โ€” and emits the full three-line voucher already balanced, already enriched with ledger codes, cost centers, departments, series, and project tags, ready to paste into SAP.

2. The Architecture โ€” 19 Queries, Three Master Sources, One Output
  • Input layer: the Data sheet's Table1 holds one row per dealer entry โ€” Reg Code, Net, TDS, Net Credit, Month, Remark. Nothing else needed.
  • Master-data layer (SharePoint): LC REG F.xlsx provides dealer name, TDS code, TDS party name, tax type, and the incentive Dr/Cr mapping. Business Partner with Cost Center.xlsx provides department + cost-center codes.
  • Control layer: the Ledger Use sheet hosts the Clause table (incentive % vs payable %), month selector (resolves to EXP 126-style sub-ledger codes), Dept mapping, and incentive/payable ledger lookups (53213001 / 2240020).
  • Output layer: Main Entry for the standard balanced JE, New All for the extended SAP-upload format with Series (HO82/83), Remark, and Project (KTM) appended.
3. The Split โ€” How One Row Becomes Three Posting Lines

Three sibling queries each project the same input into one accounting side, then a Final query appends them:

  • Expenses Dr(Ledger) โ€” Net ร— (1 โˆ’ Payable %) โ†’ Debit on the incentive expense ledger (53213001), tagged with month sub-ledger + department code.
  • TDS โ€” TDS amount โ†’ Credit on the TDS account (2232300), joined against the master so the TDS Party Name and Tax Type travel with the line.
  • Dealer Name โ€” Amount-to-be-Credited โ†’ Credit posted directly to the Reg Code as the BP code; Remark becomes the line narration.
  • Combine Final Dr โ€” appends Ledger-side debit and Payable-side debit; with Payable % at 0, the full Net rides as a single expense debit.
  • Final โ€” appends the three sides, duplicates Remarks into Narration, and lands in Main Entry as the balanced output.
4. The Balance Math โ€” Why It Always Ties

The generator never asks Excel to balance the voucher. It derives both sides from the same single Net value, so the debit total and credit total are mathematically forced to match by construction:

Power Query ยท Balanced Posting Concept (excerpt)
// Three sides derived from the SAME Net value
ExpenseDr  = [Net] * (1 - [PayablePct]),     // โ†’ Dr 53213001
TdsCr      = [TDS],                          // โ†’ Cr 2232300
DealerCr   = [Net] - [TDS],                  // โ†’ Cr REG-code

// Invariant by construction:
//   ExpenseDr โ‰ก TdsCr + DealerCr
//   ( Net * 1 )  โ‰ก  TDS + (Net - TDS)

Current cached example: Net 4,565.40 = TDS 684.81 (15%) + Dealer Credit 3,880.59. Debit total 4,565.40 = Credit total 4,565.40. Balanced before anyone opens SAP.

5. The Configurability โ€” The Clause Table Is the Whole Knob
  • Incentive % vs Payable %: a 2-row Clause table determines whether the expense rides through the incentive ledger now or sits as a year-end payable accrual. Changing one cell reroutes the posting.
  • Month โ†’ Sub-Ledger: the month selector cascades into EXP 126-style cost-center codes, so the same workbook reposts cleanly every month without M-code edits.
  • TDS rate is master-driven: the 15% TDS isn't hard-coded โ€” it comes from the SharePoint dealer/TDS master, so a rate change in IRD circulars flows through automatically on next refresh.
  • SAP-upload extension: New All adds Series, Remark, and Project so the same balanced JE drops straight into the SAP DI import format without a manual reshape.
6. Impact & Results
โš–๏ธ Balanced By Construction: Debit โ‰ก Credit holds mathematically โ€” no formula needed to enforce it, no chance of an off-by-paisa entry. ๐Ÿ“‹ SAP-Upload Ready: New All output carries Series, Remark, and Project so the same balanced JE pastes straight into the SAP import format. ๐Ÿ” One-Row Reusable: change Reg Code + Net + Month โ€” the same template regenerates a clean voucher for any dealer, any month, any incentive driver.
View Implementation Details
Excel + Power Query / Weekly Payment Workflow

Weekly Vendor Payment Preparation System (Summary + Per-Vendor Detail Sheets)

Architected a weekly vendor payment workflow that ingests SAP BP master + vendor bank master via Power Query, resolves bank accounts through PAN matching, splits vendors into Everest-Bank vs non-Everest-Bank payment lanes (bank code 1001 routing), and auto-generates 56 per-vendor transaction detail sheets that reconcile exactly to the master Summary total of NPR 23.49M.

๐ŸŽฏ100%Accuracy
๐Ÿ“Š94%Effectiveness
โš–๏ธ96%Compliance
1. The Story โ€” 56 Vendors, Two Banks, One Weekly Cycle

Every Monday morning the accounts team has the same call from finance: "Send me this week's vendor payment list, split by bank, with backup detail for each line." Done by hand, that's three hours of XLOOKUP, copy-paste, and the recurring risk that the Summary total doesn't tie to the per-vendor sheets stapled behind it. The workbook collapses that ritual into a Power Query refresh + a dynamic spilled summary: one approved master list, two bank lanes (Everest vs non-Everest), 56 per-vendor backup sheets generated automatically โ€” and a hard reconciliation guarantee that the per-vendor sheets sum exactly to the Summary total.

2. The Architecture โ€” Four Layers, Two External Sources
  • Master-data layer (SharePoint): Business Partner with Cost Center brings SAP BP code, balance, PAN, and IPS bank code mapping. Vendor Account Details brings PAN, bank name, account number, branch, and approval status โ€” but only "Checked" rows survive into the working set.
  • Power Query layer (5 queries): IPS Code, Wo_PAN, Bp Code, BankAccount, BpName โ€” each query has a single responsibility; BpName is the final composer that joins SAP BP to bank account on PAN, expanding bank name + code + branch + account.
  • Working layer (hidden): SAP Data (~53,900 rows of joined BP ร— bank) and Payment List (892 BPs with computed due balances, 96 positive-due vendors) โ€” all formula-resolved, not pasted values.
  • Output layer (visible): the Summary sheet with the bank-split payment list, plus 56 auto-generated vendor-code sheets (BJC01541, BRA00215, BJC01345 โ€ฆ) each carrying posting date, due date, JE remarks, references, debit/credit, and a cumulative balance.
3. The PaymentReport โ€” One Named Formula That Builds the Whole Summary

The Summary isn't a static paste โ€” it's the spilled result of a named LET formula that filters, splits, and stacks the working list in one pass:

Excel ยท PaymentReport Named Formula (excerpt)
=LET(
    src,       PaymentList,
    eligible,  FILTER( src,
                  (src[Due] > 500) *
                  (src[BankAcctName] <> "") ),
    nonEbl,    FILTER( eligible, eligible[BankCode] <> 1001 ),
    ebl,       FILTER( eligible, eligible[BankCode]  = 1001 ),

    VSTACK(
       "Non-Everest Bank",
       nonEbl,                       HSTACK("Subtotal", SUM(nonEbl[Due])),
       "",
       "Everest Bank",
       ebl,                          HSTACK("Subtotal", SUM(ebl[Due])),
       HSTACK("Grand Total", SUM(eligible[Due]))
    ) )
4. The Bank-Lane Split โ€” Why Bank Code 1001 Gets Its Own Section

Everest Bank vendors flow through a separate payment processing route than the rest of the banking ecosystem, so they need to ship as a separate batch even within the same weekly cycle. Bank code 1001 in the IPS master is the canonical Everest marker โ€” the named formula uses it as the lane separator rather than matching on bank name strings (which drift: "Everest Bank Limited" vs "Everest Bank Ltd" vs "EBL"). Result: 9 Everest vendors at NPR 4.44M vs 47 non-Everest vendors at NPR 19.05M, ready for two distinct payment file uploads.

5. The Reconciliation Net โ€” 56 Sheets That Must Tie
  • One sheet per BP code: every vendor in Summary gets its own backup sheet, tab-named to the BP code (BJC01541, BRA00215, โ€ฆ) so review reviewers can flip straight to a vendor by code.
  • Cumulative-balance closure: each detail sheet ends with a running cumulative balance whose final value equals the Summary due (with opposite sign โ€” the detail sheet sees it from the ledger side).
  • Reconciliation guarantee: 232 transaction rows across 56 sheets sum to NPR 23,491,572.01 โ€” exact match against the Summary total. Mismatch = zero.
  • Backup-trace ready: every line carries Posting Date, Due Date, JE No, Reference, and LineMemo so audit can trace any rupee back to its originating voucher.
6. Impact & Results
๐Ÿฆ Two-Lane Bank Routing: bank code 1001 splits Everest-Bank vendors into their own batch automatically โ€” no hand-filtering before payment upload. ๐Ÿ“‘ Audit-Stapled: every vendor in Summary has a code-named backup sheet that ties to the penny โ€” reviewers don't go hunting for support. ๐Ÿ” Weekly Rerun: change the as-on date, refresh, and the entire Summary + bank split + per-vendor sheets regenerate in one cycle.
View Implementation Details
Power Query / Reusable Master-Data Bridge Pattern

PAN-as-Soft-Foreign-Key Vendor-Bank Resolver (with Fallback Master)

Engineered a reusable Power Query pattern that bridges SAP BP master to a separately-owned vendor bank master using PAN number as a soft foreign key โ€” with a fallback PAN master to repair blanks in the source, and an approval-status filter that quietly drops unapproved bank records before they ever touch the payment file.

๐Ÿ›ก๏ธ98%Reliability
๐ŸŽฏ96%Accuracy
โš–๏ธ95%Compliance
1. The Story โ€” Two Masters That Don't Know Each Other

SAP owns the Business Partner master: BP code, name, balance, PAN. The accounts team owns the vendor bank master: vendor name, PAN, bank, account number, IFSC/IPS, approval status. There is no shared key. BP code doesn't appear in the bank master. Vendor name drifts between the two ("Tejman Enterprises" vs "Tejman Enterprises Pvt"). The only thing both records share โ€” when they share anything โ€” is the PAN number. The pattern turns PAN into a soft foreign key, repairs the blanks before they bite, and gates the join on approval status.

2. The Architecture โ€” Five Queries, One Bridge
  • IPS Code โ€” bank name โ†’ bank code lookup master. Pulled once, used everywhere a payment instrument needs to be tagged.
  • Wo_PAN โ€” the fallback PAN master. A separately maintained list of BP code โ†’ PAN for vendors whose SAP master has a blank PAN field (master-data hygiene catches up later; the workbook works today).
  • Bp Code โ€” projects SAP BP master to {BP, Name, Balance, PAN}, then left-joins against Wo_PAN and uses List.First({BP.PAN, WoPAN.No})-style coalesce so a blank SAP PAN gets filled from the fallback before the bridge fires.
  • BankAccount โ€” vendor bank master filtered to approved records only (the workbook's "Checked" status gate); also resolves the dual-source bank name column ambiguity and joins the IPS code.
  • BpName โ€” the bridge composer: Table.Buffer(BankAccount) first, then join SAP-side PAN to bank-side PAN, expand bank fields, land in SAP Data. The whole pattern is the join order and the buffer placement.
3. The PAN Coalesce โ€” Where Blanks Get Repaired

The pattern's first defense: SAP's PAN field is often blank because vendor masters were created before PAN became mandatory. Instead of accepting the blank, the query coalesces against a dedicated fallback master:

Power Query ยท PAN Fallback Coalesce (excerpt)
// SAP BP master left-joined with the fallback PAN master
WithFallback = Table.NestedJoin(
    SapBp, {"BP Code"},
    WoPAN, {"BP Code"},
    "WO", JoinKind.LeftOuter ),

// Coalesce: prefer SAP PAN, fall back to Wo_PAN.No when blank
ResolvedPAN = Table.AddColumn(WithFallback, "PAN", each
    if [PAN No.] = null or [PAN No.] = ""
    then Record.Field(Table.First([WO]) ?? [No=null], "No")
    else [PAN No.],
    type text )
4. The Approval Gate โ€” Why "Checked" Sits Inside the Query

The BankAccount query filters approval status to "Checked" before the bridge runs. This means unapproved bank account records โ€” pending verification, flagged for review, or under dispute โ€” physically cannot reach the payment file. The filter is a structural barrier, not a downstream check. If the master data is wrong, the payment is blocked at the source, not caught at audit. (Worth noting: the current implementation only accepts "Checked" and "cHECKED" verbatim โ€” a Text.Upper(Text.Trim(...)) normalization would harden this further; see the strengthening note below.)

5. The Discipline โ€” Three Rules That Make This Reusable
  • PAN is the bridge, name is decoration: never join on vendor name (string drift); always join on PAN (regulated identifier).
  • Repair before bridge: the fallback PAN coalesce runs on the SAP side before the bank join โ€” so a single blank PAN doesn't disqualify a vendor from getting paid.
  • Buffer the inner side: Table.Buffer(BankAccount) sits exactly at the join boundary โ€” the bank master is small, the SAP side is large; buffering the small side once turns N row scans into one.
6. Impact & Results
๐Ÿชช PAN Foreign Key, Across Systems: SAP BP master and a separately-owned vendor bank master joined without changing either source schema. ๐Ÿ›ก๏ธ Approval-Gated: only "Checked" bank records reach the payment file โ€” unapproved data is structurally blocked, not just flagged. ๐Ÿชถ Drop-In Reusable: lift this five-query bridge into any payment / KYC / vendor-onboarding model where two masters share only a regulated identifier.
View Implementation Details
Power BI / DAX Layers

Macro Target Performance Matrix

Designed scalable performance modeling hubs tracking metrics against a 45 Cr fiscal baseline target layout, using refined DAX calculation metrics for distribution monitoring.

๐Ÿ“Š92%Effectiveness
โšก88%Performance
๐ŸŽฏ96%Accuracy
Technical Execution Details
  • ">Dimensional Modeling: Constructed a star schema framework organizing transaction logs and dealer hierarchies.
  • ">Advanced DAX: Developed complex time-intelligence formulas to process rolling fiscal year performance run rates.
  • ">Distribution Insights: Programmed target allocation visual rules alerting management of territory deviations.
Open Dashboard Sandbox
View Implementation Details
Python / Data Pulling & Simulation

FIFA World Cup 2026 Analytics Architecture

Developed an algorithmic script infrastructure engineered to programmatically pull global tournament metrics and simulate structured, predictive competitive group-stage and knockout mechanics.

โšก95%Performance
๐Ÿ”100%Automation
๐ŸŽฏ98%Accuracy
1. The Challenge (The Pain Points)

Tracking dynamic international championship configurations requires scalable handling of fluid parameters. Hardcoded statistics break down when scheduling anomalies, shifting timezones, or localized match loads disrupt traditional relational data warehouses. Automated data ingestion and automated parsing matrices are critical to normalizing nested response patterns before performing exploratory operations.

2. The Solution (How the Python Code Works)
  • Data Extraction: Utilized the requests engine to query public GitHub JSON endpoints, retrieving match arrays dynamically.
  • Data Structuring: Processed raw response schemas via pandas.json_normalize() to reconstruct structured 104-row match metrics dataframes.
  • Transformation Engineering: Enforced datatype normalizations converting date strings via pd.to_datetime() and engineered match category indicators.
  • Exploratory Visualizations: Leveraged matplotlib.pyplot to map operational matrices including Match Load by Week, Venues by Match Counts, and Match Schedules.
3. Optimized Script Architecture Blueprint
Python
import requests
import pandas as pd
import matplotlib.pyplot as plt

# 1. Extraction: Connect to public JSON endpoints dynamically
url = "https://raw.githubusercontent.com/jokecamp/FootballData/master/FIFA-World-Cups/2026/2026-fixtures.json"
response = requests.get(url)
raw_data = response.json()

# 2. Ingestion & Flattening: Reconstruct multi-tiered nested tables
matches_df = pd.json_normalize(raw_data['matches'])

# 3. Engineering: Normalizing timestamps and categorizing operational metrics
matches_df['parsed_date'] = pd.to_datetime(matches_df['date'])
matches_df['match_week'] = matches_df['parsed_date'].dt.isocalendar().week

# 4. Analysis Validation Output Pipeline
print(f"Ingested {len(matches_df)} operational records successfully.")

# 5. Visualizing structural performance trends
plt.figure(figsize=(10, 5))
matches_df['venue'].value_counts().plot(kind='bar', color='#4c7dff')
plt.title('Match Density Vectors across Venues')
plt.ylabel('Total Matches Hosted')
plt.tight_layout()
# View simulated output graphs locally
4. Impact & Results
๐Ÿ“Š Execution Speed: Replaced manual CSV assembly pipelines with a single-second endpoint scraper execution step. ๐Ÿ›ก๏ธ Architecture Integrity: Standardized 100% of unstructured match loads into analytical schemas instantly ready for visualization tools.
Review Kaggle Notebook
View Implementation Details
SQL / Relational Databases

SAP Business One Custom Data Pipeline: Automated TDS Reconciliation & Validation Engine

Architected an advanced SQL structure optimized for relational database instances to seamlessly aggregate isolated general ledgers and validate business partner allocations on the fly.

๐Ÿ›ก๏ธ99%Reliability
๐ŸŽฏ100%Accuracy
โšก95%Efficiency
1. The Story โ€” TDS Hidden Inside Every Voucher

In our SAP Business One setup, TDS is never its own document. It's an extra line appended to A/P Invoices, Outgoing Payments, or Journal Entries โ€” a TDS ledger code on one side, a Cost Center (OcrCode2) on the other carrying the actual party identity. Standard SAP reports can't reconcile this across nine TDS heads simultaneously, and they can't catch the silent killer: the cost-center PAN drifting away from the BP master PAN. The engine was built to surface every TDS line as its own audit row โ€” with party identity, expense origin, rate, cumulative aging, and two integrity flags on the same record.

2. The Architecture โ€” Four Apply Blocks Stacked on One Join Chain
  • Expense Origin (OUTER APPLY): For each TDS line, a prioritized lookup walks the same journal entry and picks the source expense account using a deliberate priority matrix โ€” 53%/52% first, then 117%, 224%, 11%, 12% โ€” so the auditor sees which expense the TDS was deducted against.
  • Net & Rate Math (CROSS APPLY): A compact ratio block computes NetTDS and TDSPer with NULLIF guards so a zero gross never blows the query up.
  • Helper Key (CROSS APPLY): Concatenates AcctName + OcrCode2 + TDSPer into a stable grouping key โ€” used downstream by the window function so aging is partitioned correctly even when the same vendor appears across multiple expense heads.
  • Cumulative Aging (SUM() OVER): Running totals partitioned by that helper key, ordered chronologically, expose how TDS exposure stacks up over the date window.
  • Integrity Flags (PANMatch & GVCheck): Two case-insensitive, trim-safe boolean columns that compare BP-master PAN vs cost-center PAN, and TDS gross vs reconstructed entry gross (ex-VAT) โ€” surfacing the two anomaly classes that cause TDS-return rejections.
3. The Priority Matrix โ€” Choosing the Right Expense Origin

A single voucher may touch several expense heads. The OUTER APPLY uses a deterministic priority ordering โ€” never random tie-breaks โ€” so the same input always returns the same expense origin:

SQL ยท Expense Priority (excerpt)
ORDER BY
    CASE
        WHEN O2.AcctCode LIKE '53%'
          OR O2.AcctCode LIKE '52%'  THEN 0   -- direct expense
        WHEN O2.AcctCode LIKE '117%' THEN 1   -- prepaid
        WHEN O2.AcctCode LIKE '224%' THEN 2   -- liability
        WHEN O2.AcctCode LIKE '11%'  THEN 3   -- current asset
        WHEN O2.AcctCode LIKE '12%'  THEN 4   -- fixed asset
        ELSE 5
    END,
    O2.AcctCode                              -- deterministic tie-break
4. The Integrity Layer โ€” PANMatch & GVCheck

The two flags every TDS-return reviewer wants. Both are trim-safe and case-insensitive so a stray space in a vendor master never produces a false positive:

SQL ยท Integrity Flags (excerpt)
CASE WHEN DR2.U_PANNO IS NOT NULL
      AND UPPER(LTRIM(RTRIM(BP.U_PANNo)))
        = UPPER(LTRIM(RTRIM(DR2.U_PANNO)))
     THEN 'Y' ELSE 'N' END                                AS PANMatch,

CASE WHEN T1.TransType = 18                              -- A/P Invoice only
      AND ROUND(T1.U_TDSGrossAmt, 4) = EG.EntryGrossValue
     THEN 'Y'
     WHEN T1.TransType = 18 THEN 'N'
     ELSE NULL END                                       AS GVCheck
5. The Sentinel โ€” Why VAT Is Excluded From EntryGrossValue

GVCheck only works if the reconstructed gross excludes VAT lines. The fourth APPLY block sums journal lines on the same voucher but explicitly skips VALUE ADDED TAX and VAT PROVISION A/C โ€” otherwise the comparison against U_TDSGrossAmt always fails and every A/P Invoice gets a false GV mismatch.

6. Impact & Results
โšก Audit Automation: nine TDS heads reconciled in a single query โ€” ledger reviews collapse from days to seconds. ๐Ÿ›ก๏ธ Two-Flag Safety Net: PANMatch + GVCheck surface the exact two anomaly classes that cause TDS-return rejections, before filing. ๐Ÿงฎ Deterministic Output: priority-ordered expense lookup + helper-keyed window function mean the same inputs always reconcile to the same numbers.
View Implementation Details
SQL / Dealer Credit Intelligence

Dealer AR Turnover & Credit Risk Intelligence Engine

Architected a year-on-year dealer performance lens that fuses sales, gross margin, average outstanding, and credit utilization into a single risk variance score โ€” exposing dealers whose collection days are growing faster than their sales.

๐Ÿ“Š93%Effectiveness
๐Ÿ”90%Insight
๐ŸŽฏ96%Accuracy
1. The Story โ€” A Dealer Review Meeting at 10 AM

The credit committee is staring at a printed dealer list. Sales is happy โ€” "growth is up 22%". Finance is uneasy โ€” "but receivables are heavier than last year". Somewhere in that 600-dealer book sits the real story: dealers whose collection days are climbing faster than their sales are growing. By the time anyone manually cross-references invoice ledgers, journal balances, credit limits, and PAN masters in SAP B1, the meeting is over and the risk has aged another quarter. The brief was simple: one query, one click, one variance number that tells me who to call today.

2. The Architecture โ€” Two Subqueries, One Verdict

The engine pivots on two pre-aggregated subqueries โ€” a Sales CTE-style block pulling net invoice value (DocTotal โˆ’ VatSum) from OINV for FY 2024/25 (Y1) and FY 2025/26 (Y2), and a Balance block reconstructing opening + closing dealer outstanding from JDT1 journal lines. Both feed an OCRD/OCRG dealer master joined only where CardType = 'C' and a PAN number actually exists. Everything downstream is pure ratio math โ€” and the math is where the story lives.

3. The Core Ratios (How They Talk to Each Other)
  • AR Turnover โ€” Sales รท Avg Outstanding. How many times receivables flip into sales in a year. Higher = healthier velocity.
  • Collection Days โ€” Avg Outstanding ร— 365 รท Sales. The truth-teller. Translates rupees into days the dealer is sitting on your cash.
  • Credit Utilization % โ€” Avg Outstanding Y2 ร— 100 รท DebtLine. Flags dealers brushing or breaching their approved credit ceiling.
  • Margin Per Day โ€” Gross Profit Y2 รท Collection Days Y2. The unforgiving metric: a fat-margin dealer who pays in 180 days can still be worse than a thin-margin dealer paying in 30.
4. The Punchline Metric โ€” Sales vs. Collection Variance

Every ratio above feeds the single number the committee actually reads. The engine compares Net Sales Growth against Collection Days Growth and subtracts one from the other. The sign of the result is the verdict:

SQL ยท Variance Logic (excerpt)
-- Net Sales Growth %
(S.SalesY2 - S.SalesY1) * 100.0 / NULLIF(S.SalesY1, 0)

-- Collection Days Growth %
((B.AvgOut2 * 365.0 / NULLIF(S.SalesY2, 0))
 - (B.AvgOut1 * 365.0 / NULLIF(S.SalesY1, 0)))
 * 100.0 / NULLIF(B.AvgOut1 * 365.0 / NULLIF(S.SalesY1, 0), 0)

-- The Verdict
[Net Sales Growth] - [Collection Days Growth]
        AS [Sales vs. Collection Variance]

Positive variance โ†’ the dealer is growing faster than their collection is slipping. Healthy. Negative variance โ†’ collection is decaying faster than they're buying. That's the call sheet for tomorrow morning.

5. The Trick That Makes Avg Outstanding Honest

A naive query would just pull the closing balance from JDT1. But a dealer who paid down to zero on March 31st would look like they owed nothing all year. So the balance subquery reconstructs an opening + closing average per FY using two conditional sums on RefDate:

SQL ยท Avg Outstanding (excerpt)
(
   SUM(CASE WHEN J.RefDate < '2025-04-01'
            THEN J.Debit - J.Credit ELSE 0 END)    -- Opening
 + SUM(CASE WHEN J.RefDate <= '2026-03-31'
            THEN J.Debit - J.Credit ELSE 0 END)    -- Closing
) / 2.0 AS AvgOut2
6. Impact & Results
๐ŸŽฏ One Variance Number: replaces a 600-row dealer-by-dealer review with a single sortable risk column. ๐Ÿ“‰ Hidden Risk Surfaced: dealers with positive sales growth but negative variance โ€” invisible in normal sales reports โ€” now jump to the top. โš™๏ธ Parameter-Driven: [%0] group filter lets the committee zoom from "all dealers" to "Wholesale" without rewriting the query.
View Implementation Details
SQL / BP Ledger Extraction

EXC Business Partner Ledger Tracer

Built a surgical SAP B1 ledger probe that pulls every EXC-coded Business Partner's journal activity from a fixed start date to today, decodes cryptic TransType numbers into readable labels, and quietly drops reversal-linked entries so reconciliation never double-counts a storno.

โšก95%Performance
๐ŸŽฏ100%Accuracy
๐Ÿ”90%Automation
1. The Story โ€” "Just Send Me the EXC Ledger"

Every reconciliation cycle, the same Slack message arrives: "Can you pull the EXC dealer ledger from July?" In SAP Business One the answer lives across three tables and a wall of numeric type codes. Pull JDT1 directly and you get rows labeled TransType = 13 or 46 โ€” meaningless to anyone outside accounting. Forget to filter storno-linked headers and your debit/credit totals tie out to a number that's already been reversed. The brief: one query, one paste, a clean readable ledger the receiver can open without asking a single follow-up question.

2. The Probe โ€” Three Tables, One Verdict

The probe anchors on JDT1 (journal line detail), pulls BP names from OCRD, and joins to OJDT only so it can interrogate the header's StornoToTr field. The shape of the join chain is deliberate โ€” INNER JOIN on OCRD ensures pure G/L-only lines (with no BP linkage) are silently dropped, which is exactly what a BP ledger should do.

3. The Decoder โ€” TransType Numbers โ†’ Human Words

SAP stores transaction origin as a single integer. The probe maps the eight types that account for ~99% of BP traffic and falls through to the raw number for anything exotic, so the reader never sees an unexplained blank:

SQL ยท TransType Decoder (excerpt)
CASE J.TransType
    WHEN 13  THEN 'A/R Invoice'
    WHEN 14  THEN 'A/R Credit Memo'
    WHEN 24  THEN 'Incoming Payment'
    WHEN 46  THEN 'Outgoing Payment'
    WHEN 30  THEN 'Journal Entry'
    WHEN 18  THEN 'A/P Invoice'
    WHEN 19  THEN 'A/P Credit Memo'
    WHEN 203 THEN 'A/R Down Payment'
    ELSE CAST(J.TransType AS VARCHAR(10))
END AS [Txn Type]
4. The Quiet Filter โ€” Why Storno Is the Real Bug

The non-obvious line is this one โ€” the difference between a ledger that ties out and one that doesn't:

SQL ยท Storno Exclusion (excerpt)
INNER JOIN OJDT H
    ON H.TransId = J.TransId
WHERE J.ShortName LIKE 'EXC%'
  AND J.RefDate >= '2025-07-17'
  AND J.RefDate <= GETDATE()
  AND ISNULL(H.StornoToTr, 0) = 0;

StornoToTr is SAP's pointer from a reversal entry back to the entry it reversed. When non-zero, the row is a deliberate cancellation. Without this guard, every reversed invoice appears twice in the ledger โ€” once as the original and once as its negation โ€” and balances reconcile to a phantom number. GETDATE() on the end-date means the receiver always gets data live up to the moment they run the query, no rolling-window maintenance.

5. Impact & Results
๐Ÿ“œ Readable Ledger: TransType codes become human labels โ€” no accounting glossary needed by the reader. โœ… Reconciliation-Safe: storno-linked headers excluded by default so debit/credit totals don't double-count reversals. ๐Ÿ•’ Always Current: GETDATE() end date means the same saved query stays fresh every cycle without manual edits.
View Implementation Details
SQL / Consolidated Exposure Engine

Dealer 360ยฐ Exposure Consolidator (Main + CHL + Support + Exchange)

Built a single-row-per-dealer exposure lens that stitches together four legally-separate Business Partner codes โ€” the main dealer, their Challan account, their Support (frozen) account, and their Exchange account โ€” using PAN + name + city fingerprinting, then rolls them into one true Total Outstanding as of any cutoff date.

๐Ÿ”95%Coverage
๐Ÿ›ก๏ธ98%Reliability
๐ŸŽฏ92%Accuracy
1. The Story โ€” One Dealer, Four Hidden Ledgers

On paper "ABC Motors" looks like one customer. Inside SAP it's actually four separate Business Partner codes โ€” the main dealer, an ABC Motors CHL for challan-routed billing, an ABC Motors Support holding the frozen / disputed amount, and an ABC Motors Exchange for trade-in adjustments. Each carries its own outstanding. A naive customer-aging report shows only the main BP and quietly understates real exposure by 20โ€“40%. The credit committee keeps asking the same question: "What's our actual total exposure to this dealer as of last Friday?"

2. The Engineering Problem โ€” There Is No Foreign Key

SAP B1 doesn't link these four BPs to each other in any system field. The only thing they share is the dealer's PAN number, a fragment of the name, and the city. The consolidator treats that triple as a soft foreign key and runs four scoped correlated subqueries โ€” one per ledger flavor โ€” each filtering OCRD for matching customers and summing their JDT1.Debit โˆ’ Credit up to the cutoff date.

3. The Fingerprint โ€” How a Related BP Is Recognized

Each of the three sibling subqueries (CHL, Support, Exchange) reuses the same identity pattern, varying only the name token. This is the fragment that does the matching:

SQL ยท Sibling-BP Fingerprint (excerpt)
INNER JOIN OCRD BPS ON BPS.CardCode = J2.ShortName
WHERE BPS.CardType  = 'C'
  AND BPS.U_PANNo   = T0.U_PANNo              -- same PAN
  AND BPS.CardName  LIKE '%' + T0.CardName + '%CHL%'   -- name + token
  AND BPS.City      LIKE '%' + T2.City + '%'           -- same city
  AND J2.RefDate   <= '[%0]'                  -- as-of cutoff

Swap '%CHL%' for '%Support%' or '%Exchange%' and you have the other two probes. PAN does the hard identity work; name token tells you which sibling; city defends against the rare collision where the same group operates a dealer under the same PAN in two regions.

4. The Roll-Up โ€” Four Balances Become One Number

Every subquery is wrapped in ISNULL(..., 0) so a missing sibling never poisons the sum with a NULL. The Total Outstanding column is just the four sums stacked:

SQL ยท Total Exposure (excerpt)
(
    ISNULL(MainOutstanding,     0)   -- T0.CardCode itself
  + ISNULL(ChallanBalance,      0)   -- '%CHL%' sibling
  + ISNULL(FrozenSupport,       0)   -- '%Support%' sibling
  + ISNULL(ExchangeOutstanding, 0)   -- '%Exchange%' sibling
) AS [Total Outstanding]
5. Guard Rails Built Into the WHERE Clause
  • Customers only: T0.CardType = 'C' โ€” vendors never enter the consolidation.
  • PAN required: ISNULL(T0.U_PANNo, '') <> '' โ€” without PAN the fingerprint collapses, so blanks are dropped at the source.
  • Group-scoped: T1.GroupName = '[%1]' โ€” the committee can run the report for "Wholesale", "Retail", or any BP group without touching the SQL.
  • As-of date: Every balance subquery uses RefDate <= '[%0]' so the same query produces Friday's number, month-end's number, or quarter-end's number on demand.
6. Impact & Results
๐Ÿ” True Exposure Surfaced: dealer exposure that was previously understated by 20โ€“40% now reconciles to a single defensible number. ๐Ÿชช Soft Foreign Key: PAN + name token + city replaces a missing system relationship โ€” no schema change to SAP required. ๐Ÿ“… Time-Travel Ready: any cutoff date [%0] reproduces that day's exposure exactly, ideal for audit-trail and historical credit reviews.
View Implementation Details
SQL / TDS Movement Ledger

TDS Account ร— Cost Center Opening-Movement-Closing Engine

Architected a four-bucket TDS ledger lens that pivots every Nepal-applicable TDS account by Dim-2 cost center + PAN into a clean Opening / Debit / Credit / Closing matrix, using a single date-window parameter pair โ€” the exact shape an auditor wants to see during a TDS return review.

๐ŸŽฏ99%Accuracy
๐Ÿ“Š94%Effectiveness
โšก92%Performance
1. The Story โ€” "Show Me What Moved This Quarter"

Every TDS filing window, the auditor asks the same question in four pieces: what was the opening balance, what got debited, what got credited, and where did it close? Per account. Per cost center. Per PAN. SAP B1's standard reports give you a transaction dump or a single trial balance number โ€” never the four-bucket matrix in one row. The engine collapses that into a single grouped query: nine TDS account heads, dimension-2 cost center pivot, PAN attached, four movement columns side-by-side.

2. The Engineering โ€” Four Conditional Sums, One Row

Instead of running four queries (or four sub-reports), the engine uses four conditional SUM(CASE...) aggregates over the same JDT1 scan โ€” one for Opening (everything strictly before [%0]), one each for in-window Debit and Credit, and one for Closing (everything up to and including [%1]). Single table scan, single GROUP BY, four buckets emitted simultaneously.

SQL ยท Four-Bucket Aggregator (excerpt)
SUM(CASE WHEN T0.RefDate < [%0]
         THEN T0.Debit - T0.Credit ELSE 0 END)  AS [Opening],

SUM(CASE WHEN T0.RefDate >= [%0]
          AND T0.RefDate <= [%1]
         THEN T0.Debit  ELSE 0 END)             AS [Debit],

SUM(CASE WHEN T0.RefDate >= [%0]
          AND T0.RefDate <= [%1]
         THEN T0.Credit ELSE 0 END)             AS [Credit],

SUM(CASE WHEN T0.RefDate <= [%1]
         THEN T0.Debit - T0.Credit ELSE 0 END)  AS [Closing]
3. The Scope โ€” Nine TDS Heads That Cover ~99% of Nepal Payroll & Vendor Withholding
  • Staff Income Tax & Staff Social Security Tax (1%) โ€” payroll-side withholding.
  • TDS [11111] Individual ยท TDS [11123] Pvt. Ltd ยท TDS (11122) Public Ltd ยท TDS Other Entities (11124) โ€” entity-classified vendor withholding.
  • TDS [11131] Rent ยท TDS [11133] Dividend ยท TDS (11115) Wind Fall โ€” Gain โ€” special-rate buckets (10% / 5% / 25% respectively under Nepal IRD).
  • The RTRIM on AcctName defends against trailing-space matching bugs in the SAP master โ€” a quiet but lethal foot-gun if omitted.
4. The Dim-2 Pivot โ€” Why Cost Center Matters Here

OcrCode2 is the company's per-vendor / per-party dimension. Pairing it with OOCR.U_PANNO means each row of output is genuinely one vendor ร— one TDS head โ€” exactly the granularity the IRD return needs. The LEFT JOIN on OOCR preserves rows that don't have a cost center attached (rare but real for some JEs), so the totals still tie out to the trial balance.

5. Impact & Results
๐Ÿงฎ One Row, Four Movements: opening โ†’ debit โ†’ credit โ†’ closing emitted in a single grouped query โ€” no four-query gymnastics. ๐ŸŽฏ Return-Ready Shape: output already matches the per-vendor ร— per-head structure auditors and TDS returns expect. ๐Ÿ›ก๏ธ Trim-Safe Account Match: RTRIM on AcctName kills the silent-mismatch bug from master-data trailing spaces.
View Implementation Details
SQL / VAT Reconciliation Engine

AR + AP VAT Reconciliation Engine (Output โˆ’ Input = Net VAT)

Built a four-stream VAT reconciliation lens that fuses AR invoices, AR credit memos, AP invoices, and AP credit memos into a single per-PAN view โ€” SalesNet, SalesVAT, PurchaseNet, PurchaseVAT, and NetVAT payable โ€” sign-corrected, cancellation-aware, and ready to tally against the SAP B1 Tax Report.

๐ŸŽฏ99%Accuracy
โš–๏ธ97%Compliance
โšก93%Performance
1. The Story โ€” VAT Return Eve

VAT filing day arrives with the same uncomfortable shuffle every month: pull AR invoices, pull AP invoices, then remember the credit memos, then remember to flip their signs, then remember to drop the canceled documents, then tally output VAT minus input VAT and pray it matches the SAP Tax Report. Four document tables, four sign conventions, one filing deadline. The engine collapses that ritual into a single CTE-driven query where every stream is normalized, signed correctly, and aggregated per PAN โ€” so the only thing left to do is paste the NetVAT into the return.

2. The Architecture โ€” Four CTEs, One UNION ALL, One Verdict
  • ar_inv โ€” AR invoices from OINV, contributing positive NetAmt and positive VatAmt.
  • ar_cm โ€” AR credit memos from ORIN, signs pre-flipped inside the CTE so downstream math never has to remember the convention.
  • ap_inv โ€” AP invoices from OPCH, mirroring the AR side for purchases.
  • ap_cm โ€” AP credit memos from ORPC, also pre-flipped negative.
  • all_txns โ€” a UNION ALL stack tagged with 'Sales' or 'Purchase' so the final aggregate is one tidy GROUP BY PAN, CardCode, CardName.
3. The Sign Convention โ€” Where Credit Memos Get Flipped

The single most common VAT-reconciliation bug is forgetting to negate credit-memo VAT. The engine fixes this at the source, not at the aggregation โ€” so no consumer of the CTE can re-introduce the bug:

SQL ยท Credit-Memo Sign Flip (excerpt)
-- AR Credit Memo (sales return)
SELECT
    c.U_PANNo,
    c.CardCode,
    c.CardName,
   -(r.DocTotal - r.VatSum)  AS NetAmt,   -- negative net
   -r.VatSum                  AS VatAmt   -- negative output VAT
FROM ORIN r
JOIN OCRD c ON c.CardCode = r.CardCode
WHERE r.CANCELED = 'N'
  AND r.DocDate BETWEEN '[%0]' AND '[%1]'
4. The Verdict โ€” Conditional Aggregation Into Five Columns

With every row in all_txns already correctly signed, the final SELECT pivots the four streams into five reportable columns using conditional sums โ€” and computes NetVAT inline as Output VAT minus Input VAT:

SQL ยท Final Aggregation (excerpt)
SUM(CASE WHEN Type='Sales'    THEN VatAmt ELSE 0 END) AS SalesVAT,
SUM(CASE WHEN Type='Purchase' THEN VatAmt ELSE 0 END) AS PurchaseVAT,

-- Net VAT: payable if positive, refundable if negative
  SUM(CASE WHEN Type='Sales'    THEN VatAmt ELSE 0 END)
- SUM(CASE WHEN Type='Purchase' THEN VatAmt ELSE 0 END) AS NetVAT
5. The Guard Rails Inside Every CTE
  • Cancellation-aware: every CTE filters CANCELED = 'N' โ€” voided documents never reach aggregation.
  • PAN-anchored grouping: the final GROUP BY PANNo, CardCode, CardName rolls up to the level the VAT return actually requires.
  • Net = DocTotal โˆ’ VatSum: the engine never trusts a "before tax" column from the source โ€” it derives the taxable base from the canonical header fields so currency-format drift can't corrupt the math.
  • Date-window driven: BETWEEN '[%0]' AND '[%1]' on every stream โ€” change the parameter pair, reproduce any prior period exactly.
6. Impact & Results
๐Ÿงพ One-Query VAT Return Prep: four document streams collapsed into one signed, aggregated, PAN-keyed table. ๐Ÿ›ก๏ธ Sign-Bug Proof: credit memos pre-negated inside their CTEs โ€” downstream consumers can't accidentally double-add a return. ๐Ÿ“ Tax-Report Tally-Ready: SalesVAT & PurchaseVAT designed to reconcile directly against the SAP B1 official Tax Report column for the same period.
View Implementation Details
SQL / Project-Scoped VAT Input Register

Project-Wise VAT Input Register with Bill-Number Splitter & Expense Lookup

Architected a project-scoped VAT input register that walks every JDT1 line on the input-VAT account, recomputes the AP base via a 53%-account aggregate, parses bill number and bill date out of a hyphen-delimited Ref2 field, and pins each row to the expense ledger that actually drove the deduction.

๐ŸŽฏ98%Accuracy
โš–๏ธ96%Compliance
๐Ÿ”93%Insight
1. The Story โ€” "What VAT Did This Project Eat?"

Output VAT lives at the company level. Input VAT lives inside a thousand vendor invoices โ€” each one tagged to a project, an expense ledger, and a bill number that was typed by a busy clerk in a "BILL-NO-2025-04-17" mashup field. The finance team needs to slice input VAT by project, with the bill number and bill date separated, and with the originating expense ledger attached โ€” so a project manager can defend every rupee of reclaimed VAT. The register collapses that requirement into one parameterized query: date window, single VAT input account, single project filter, four document types, fully decoded.

2. The Architecture โ€” One Scan, Three Enrichments
  • Anchor on JDT1: the journal-line table is the only place where input VAT, project, and contra-account converge โ€” header tables don't carry the project dimension at line level.
  • AP Base Lookup (Derived Subquery): a pre-aggregated JX subquery sums every Account LIKE '53%' debit per TransId, giving the true AP base behind each VAT line โ€” used only when TransType = 18 (A/P Invoice), with BaseSum as fallback for JEs and payments.
  • Expense Ledger Pinpoint (OUTER APPLY): for each VAT line, walks the same voucher and picks the first matching expense / inventory / WIP account (53% ยท 11% ยท 13%), so the register names which ledger drove the deduction.
  • Calculated Base Reconstruction: independently computes VAT ร— 100 / 13 as a cross-check against the AP base โ€” a quick sanity column that flags vouchers where the 13% VAT math doesn't square with the declared base.
  • Project Filter as the Hard Boundary: the WHERE clause pins Project = '[%2]' at line level โ€” not header level โ€” so a multi-project voucher only contributes the lines that actually belong to the project being reported.
3. The Bill-Number Splitter โ€” Cleaning Up Free-Text Ref2

Ref2 is a free-text field where users routinely type "INV-2025-04-17" โ€” bill number and date jammed together with a hyphen. The register parses both out without a UDF or a post-process step:

SQL ยท Ref2 Splitter (excerpt)
CASE WHEN CHARINDEX('-', T0.Ref2) > 0
     THEN LTRIM(RTRIM(LEFT(T0.Ref2, CHARINDEX('-', T0.Ref2) - 1)))
     ELSE T0.Ref2
END AS [Bill],

CASE WHEN CHARINDEX('-', T0.Ref2) > 0
     THEN LTRIM(RTRIM(SUBSTRING(T0.Ref2,
                                CHARINDEX('-', T0.Ref2) + 1, 8000)))
     ELSE NULL
END AS [Bill Date]
4. The AP Base Lookup โ€” Why a Subquery, Not a Join

Joining directly on JDT1 for the 53% lines would multiply the row count whenever a voucher hit multiple expense accounts. Pre-aggregating into a single row per TransId keeps the register one-row-per-VAT-line and makes the join a clean left-anchor:

SQL ยท Pre-Aggregated AP Base (excerpt)
LEFT JOIN (
    SELECT J1.TransId, SUM(J1.Debit) AS APBaseAmt
    FROM JDT1 J1
    WHERE J1.Account LIKE '53%'
    GROUP BY J1.TransId
) JX ON JX.TransId = T0.TransId

-- Used only for A/P Invoice rows; JEs & payments fall back to BaseSum
CASE WHEN T0.TransType = 18 THEN ISNULL(JX.APBaseAmt, 0)
     ELSE T0.BaseSum
END AS [AP Base Amount]
5. The Guard Rails
  • Single VAT account scope: T0.Account = '2230002' โ€” only the input-VAT GL participates, no output or other tax accounts contaminate the totals.
  • Document-type whitelist: TransType IN (18, 19, 30, 46) โ€” A/P Invoice, A/P Credit Memo, Journal Entry, Outgoing Payment only. AR-side traffic can never sneak in.
  • Sign-aware VAT amount: CASE WHEN Debit = 0 THEN -Credit ELSE Debit END โ€” credit-side reversals come through as negatives so net VAT stays honest.
  • Project-pinned at line level: the project filter sits on JDT1.Project, not on the document header, so per-project totals are line-accurate.
6. Impact & Results
๐Ÿงพ Project-Defensible Input VAT: every reclaimed rupee is traced to a bill number, bill date, vendor PAN, and expense ledger โ€” auditor-ready. ๐Ÿ” Self-Checking Base: the calculated base (VAT ร— 100 / 13) sits beside the AP base, surfacing voucher-math anomalies on read instead of in a separate reconciliation pass. โš™๏ธ Three-Parameter Flex: start date, end date, project โ€” the same query reproduces any prior period for any project without code changes.
View Implementation Details
Tableau Desktop

Territory Penetration & Distribution Models

Engineered comprehensive spatial mapping sheets visualizing regional distribution depth, tracking dealer footprint layout matrices across key zones.

๐Ÿ“Š88%Effectiveness
๐Ÿ—บ๏ธ100%Coverage
โšก85%Performance
Technical Execution Details
  • Geospatial Integration: Integrated custom regional geographic datasets to map precise business location boundaries.
  • Interactive Parameters: Crafted dynamic filters allowing operations managers to simulate dealer territory allocations.
  • Data Storytelling: Designed executive dashboards mapping market share density directly alongside route logistics.
Launch Interactive Story
View Implementation Details
AI Agent / Nepal Tax Compliance

SAP TDS Ledger AI Auditor โ€” Nepal Compliance

Engineered an AI review agent that ingests a raw SAP-extracted TDS ledger, cross-references every row against Nepal Income Tax Act rates and party-entity ledger mapping, flags red/yellow exceptions inline, and emits a tied-out First Summary workbook with full sources, rule matrix, and PASS/FAIL reconciliation.

๐Ÿค–100%Automation
โš–๏ธ98%Compliance
๐ŸŽฏ95%Accuracy
1. The Story โ€” A Tax Auditor That Never Sleeps

Every quarter, somebody on the finance team opens a multi-thousand-row SAP TDS ledger, sets their coffee down, and starts hand-checking whether each row was deducted at the right rate, against the right account, for the right kind of party โ€” Individual vs Pvt. Ltd vs Public Ltd. By row 300 they're tired. By row 800 they're guessing. The AI agent replaces that fatigue with a deterministic ruleset wired into Nepal Income Tax Act guidance, IRD circulars, and the company's own treatment exceptions โ€” and it produces a tied-out workbook the next reviewer can defend to an external auditor.

2. What the Agent Actually Does
  • Schema Pre-Flight: Validates the source sheet has all 29 expected columns (Transaction Number โ†’ GVCheck). Missing columns halt execution with a precise gap list โ€” no silent failures.
  • Rate Mapping Engine: Encodes the full Nepal TDS rate schedule โ€” Staff Income Tax (payroll-slab variable), SST 1%, Windfall 25%, Rent 10%, Freight 2.5%, Service/Commission 15%, Contract/VAT 1.5% โ€” and tests every row against it.
  • Party-Entity Classifier: Infers Individual / Pvt. Ltd / Public Ltd from BPName suffix tokens (Pvt, Pvt.Ltd, P.Ltd, Limited, etc.), excluding placeholders like Reversed or Transfer, then verifies the booked TDS ledger (11111 / 11122 / 11123) matches.
  • Exception-Aware: Suppresses PANMatch checks on Journal Entries and on TDS Other Entities (11124); suppresses GVCheck on JEs, Nepal Custom Clearing, and Repair & Maint. Pool-C. Hard-coded user-confirmed carve-outs, not heuristics.
  • Inline Flagging: Writes a new Possible Mistake / Correction Measure column at AE, fills red for likely-incorrect rows, yellow for review rows, blank when clean. Multiple findings concatenate with | in the same cell.
  • Tied-Out Summary: Generates a First Summary sheet with title, overview, rule matrix, classification table, findings by treatment, exception bucket detail, sources/limitations, and a final tie-out row that must PASS on rows, gross, and NetTDS โ€” otherwise nothing finalizes.
3. The Decision Layer โ€” Excerpt of the Classification Logic

Each row collapses into one of four statuses with strict precedence (red > yellow > clean):

Agent Logic ยท Status Resolution (excerpt)
def classify(row, rules):
    findings = []

    # Party-entity vs TDS ledger
    party_type = infer_party_type(row.BPName or row.TDSPartyName)
    expected_ledger = LEDGER_MAP[party_type]
    if expected_ledger and row.AccountName != expected_ledger:
        findings.append(("RED", f"TDS ledger mismatch: party "
                                f"appears {party_type} but booked "
                                f"under {row.AccountName}; "
                                f"reclass to {expected_ledger}."))

    # Rate band tests (only after exception carve-outs)
    expected_rate = rules.expected_rate(row)
    if expected_rate and not approx_equal(row.TDSPer, expected_rate):
        severity = "RED" if rules.is_hard_rate(row) else "YELLOW"
        findings.append((severity, rules.message_for(row, expected_rate)))

    # PAN / GV checks โ€” A/P Invoice only, with carve-outs
    if row.DocTypeName == "A/P Invoice":
        if row.PANMatch != "Y" and row.AccountName != "TDS Other Entities (11124)":
            findings.append(("YELLOW", "PAN mismatch in A/P Invoiceโ€ฆ"))
        if row.GVCheck != "Y" and row.ExpenseName not in GV_EXEMPT:
            findings.append(("YELLOW", "Gross value mismatch in A/P Invoiceโ€ฆ"))

    return resolve_status(findings)   # RED > YELLOW > CLEAN
4. The Tie-Out โ€” Why This Is Audit-Defensible

Before the agent declares done, three sums must reconcile exactly between the source ledger and the classification table: row count, F_GrossValue, and NetTDS. If any one of them drifts, the agent refuses to finalize โ€” no PASS, no summary, no green check. This single guard is what separates "AI suggestion" from "audit-defensible review".

5. Impact & Results
โš–๏ธ Compliance-First: every flag traces to a specific Nepal Income Tax Act rule or company-confirmed exception, not model intuition. ๐Ÿšซ Zero False Carve-Out Noise: JE rows, TDS Other Entities, and the two exempt expense heads are never flagged for PAN/GV โ€” eliminating the noise that buried earlier manual reviews. ๐Ÿงพ Audit-Defensible Output: the First Summary sheet ships with sources, rule matrix, classification, exception detail, and a tie-out row that must PASS โ€” ready for external review.
View Implementation Details
AI Agent / Payroll Consolidation

Multi-Sheet Payroll Consolidation Specialist

Engineered an AI data-consolidation agent that crawls scattered payroll, HR, and banking sheets, normalizes 19 employee fields into one master table โ€” codes, joining dates, wage components, PF, gratuity, SST, PAN, bank โ€” with standardized date and decimal formats, duplicate suppression, and gap-aware "N/A" handling.

๐Ÿค–100%Automation
๐Ÿงฉ95%Consistency
๐ŸŽฏ98%Accuracy
1. The Story โ€” Payroll Day, Twelve Tabs Open

It's the 28th of the month. HR has the joining-date sheet. Finance has the basic-salary sheet. Branch ops has the daily-wage register. Banking has half the account numbers in one workbook and the other half pasted into an email. Twelve tabs, three formats, two date conventions, and one looming payroll cycle. The brief: hand the agent the messy stack, get back one clean master table โ€” every employee, every required field, in the exact order the payroll system expects.

2. What the Agent Actually Does
  • Multi-Source Discovery: Scans every provided sheet and source, identifies unique employee entries by code + name pairing, and ignores duplicate rows that drift in from copy-paste handoffs.
  • 19-Column Normalization: Projects every record into the exact target schema โ€” S.N ยท Code ยท Name ยท Date of Joining ยท Designation ยท Location ยท Basic ยท DA ยท Wages/Daily ยท Present Days ยท Total Wages ยท PF ยท Gratuity ยท Gross Total ยท SST ยท Net Payable ยท PAN No ยท Account No ยท Bank Name.
  • Derived-Field Computation: Recomputes Total Wages = Basic + DA + Daily Wages, Gross Total as all earnings, and Net Payable = Gross Total โˆ’ Deductions from the canonical inputs โ€” never trusting precomputed values that might be stale.
  • Format Discipline: Coerces all dates into YYYY-MM-DD, all monetary values into two-decimal numerics, strips special characters that would break Markdown table rendering, and resequences S.N as a contiguous 1..N counter.
  • Gap Handling: Missing critical fields get N/A; truly empty optional fields stay blank โ€” and the agent surfaces a per-employee "missing fields" note instead of silently guessing values.
  • Markdown-First Output: Emits one consolidated Markdown table sorted by S.N, with consistent header casing and column alignment โ€” pasteable straight into a payroll handoff doc or review thread.
3. The Normalization Layer โ€” Excerpt of the Schema Contract

Every source row, regardless of which sheet it came from, gets mapped through one canonical projection before it's allowed into the output table:

Agent Logic ยท Schema Projection (excerpt)
def normalize(record, idx):
    return {
        "S.N":             idx + 1,
        "Code":            record.get("emp_code") or "N/A",
        "Name":            clean_name(record.get("name")),
        "Date of Joining": to_iso_date(record.get("doj")),       # YYYY-MM-DD
        "Designation":     record.get("designation") or "N/A",
        "Location":        record.get("location") or "N/A",
        "Basic":           to_decimal2(record.get("basic")),     # 0.00
        "DA":              to_decimal2(record.get("da")),
        "Wages/Daily":     to_decimal2(record.get("daily_wage")),
        "Present Days":    to_int(record.get("present_days")),
        "Total Wages":     compute_total_wages(record),          # Basic + DA + Daily
        "PF":              to_decimal2(record.get("pf")),
        "Gratuity":        to_decimal2(record.get("gratuity")),
        "Gross Total":     compute_gross(record),
        "SST":             to_decimal2(record.get("sst")),
        "Net Payable":     compute_net(record),                  # Gross - Deductions
        "PAN No":          strip_special(record.get("pan")),
        "Account No":      strip_special(record.get("acct")),
        "Bank Name":       record.get("bank") or "N/A",
    }
4. The Discipline โ€” Three Rules That Make This Trustworthy
  • Never invent a value: if a field is genuinely missing, it stays N/A or blank. The agent does not infer a "probable" salary from a peer record.
  • Always recompute the math: Total Wages, Gross Total, and Net Payable are derived inside the agent, not copied from the source โ€” so stale numbers can't survive the consolidation.
  • Surface gaps explicitly: employees with incomplete data are flagged in a notes column, so the payroll runner sees exactly what needs chasing before the bank cutoff.
5. Impact & Results
โšก Twelve Tabs โ†’ One Table: an entire payroll-cycle reconciliation collapses into a single deterministic pass. ๐Ÿงพ Bank-Ready Format: dates in ISO, money at 2 decimals, special characters stripped โ€” the output drops straight into payroll/bank upload formats. ๐Ÿšจ Gap-Aware: missing fields are surfaced, not guessed โ€” the runner knows exactly which employees need a follow-up before processing.
View Implementation Details