Strategic Finance Models & Pipelines

FP&A & Decision Support.

A systematic breakdown of driver-based forecasting models, margin sensitivity engines, automated auditing pipelines, and interactive financial dashboards. Click any card to inspect the implementation architecture.

FP&A / Driver-Based Revenue Forecasting

Driver-Based Annual Revenue Forecast โ€” Bajaj Dealer Network (FY 26-27)

Built a forward-looking revenue planning model that translates operational drivers โ€” active showroom count, units per showroom per month, dealer-tier mix, model-line ASP โ€” into a defensible top-line forecast with attached sensitivity bands, replacing the legacy "+12% on last year" extrapolation with a plan leadership can actually steer.

๐Ÿ“ˆ94%Forecast Accuracy
โฑ๏ธ-70%Planning Cycle Time
๐ŸŽฏยฑ3%Variance Confidence
1. Business Context โ€” Why the Old Plan Stopped Working

Every fiscal year the revenue plan was built the same way: take last year's actual, multiply by leadership's growth ambition, allocate proportionally across districts. It worked when the network grew uniformly. It broke the moment the Bajaj dealer footprint started behaving asymmetrically โ€” premium tiers expanding, commuter tiers contracting, exchange-purchase mix shifting by region. The plan stopped predicting; it just rolled forward. By Q2, variance against actuals routinely cleared ยฑ18%, and the CFO had no analytical handle on which lever to pull.

2. The "So What" โ€” Why It Mattered to the Business
  • Working capital exposure: overstated revenue meant overstocked districts, slower receivable conversion, and an estimated NPR 8-12 Cr in extra inventory drag per quarter.
  • Incentive miscalibration: dealer schemes priced against an unreliable plan paid out misaligned with actual margin contribution.
  • Leadership credibility: repeated mid-year re-forecasts eroded confidence in the FP&A function as a strategic partner.
3. The Solution โ€” A Driver Stack, Not a Number

The model replaces the single growth-rate input with a stack of operational drivers that each leadership stakeholder owns. Sales owns the showroom count and per-showroom units; product owns the model-line mix and ASP; commercial owns the exchange-vs-cash-vs-finance split. The forecast falls out as a deterministic multiplication of those inputs โ€” and when leadership wants to test a scenario, they change the driver, not the number.

Forecast ยท Driver Stack (concept excerpt)
Revenue[district, month] =
   ActiveShowrooms[district, month]
 ร— UnitsPerShowroomPerMonth[district, tier, month]
 ร— MixWeight[tier, model_line]
 ร— ASP[model_line, month]
 ร— ( 1 - ExchangeDiscountRate[district] )

PlannedRevenue   = SUM over (district, month)
SensitivityBand  = SUMPRODUCT( ฮ”Driver ร— Elasticity )
                                  // ยฑ3% at the 80% confidence interval
4. The Sensitivity Layer โ€” Defending the Plan Before It's Challenged

For every driver, the model ships with a documented elasticity range. When the CFO asks "What if showroom count slips by 4 in Province 2?" the answer is on screen in seconds: NPR X Cr revenue, NPR Y Cr margin, Z% impact on EBITDA. The same machinery answers "What if import cost rises 5% and we pass through 2%?" โ€” a question that previously took two weeks of side-modeling.

5. Financial Impact & Outcome
๐Ÿ’ผ Working Capital Released: improved forecast accuracy enabled inventory rebalancing worth ~NPR 6 Cr in freed cash per quarter. ๐Ÿ“Š Variance Capture: monthly Plan-vs-Actual variance narrowed from ยฑ18% to ยฑ3% on the rolling 12-month average. โฑ๏ธ Planning Cycle: budgeting cycle compressed from ~6 weeks of consolidation to under 2 weeks, freeing 70% of FP&A capacity for commercial analysis. ๐ŸŽฏ Decision Velocity: scenario answers ("what if X moves Y%") delivered in-meeting instead of week-later, restoring FP&A's seat at the strategy table.
View Implementation Details
FP&A / Sensitivity & What-If Modeling

Cost-Pass-Through Sensitivity Model โ€” Import Cost vs Pricing Strategy

Built a sensitivity engine that translates volatile macro variables โ€” import cost inflation, currency drift, dealer-discount pressure โ€” into a defensible price-pass-through recommendation, protecting NPR 2.5 Cr in annualized gross margin during a 5% import-cost spike by giving leadership a live "what-if" answer instead of a delayed reactive markdown.

๐Ÿ’ฐNPR 2.5CrMargin Defended
โฑ๏ธLiveIn-Meeting Answer
๐Ÿ“Š6Lever Variables
1. Business Context โ€” The Commercial Question Nobody Could Answer Fast Enough

Import costs move. Currency drifts. The competitor discounts. The CEO asks the FP&A team a deceptively simple question in a Friday meeting: "If import cost rises 5% and we pass through 2%, what happens to EBITDA โ€” and which dealer tier absorbs it?" Historically that question went into a Monday-morning side-modeling exercise, came back Wednesday with a number nobody fully trusted, and by then the pricing window had closed. The sensitivity model exists so the answer is on the screen during the meeting.

2. The "So What" โ€” Why Speed Equals Margin
  • Pricing windows are short: a delayed pass-through decision means the absorbed cost compounds for every week the model isn't live.
  • Dealer-tier asymmetry: a flat 2% pass-through hides the truth โ€” premium dealers can swallow more, commuter dealers cannot. Without tier-level sensitivity, the wrong dealers bear the cost.
  • Margin defense is FP&A's job: a CFO who can simulate three scenarios in a meeting earns the right to influence the pricing decision.
3. The Solution โ€” Six Levers, One Output Surface

The model exposes six independent levers โ€” import cost %, FX rate, ASP pass-through %, dealer-discount pressure, mix shift, volume elasticity โ€” each wired into a single EBITDA output cell via a transparent formula chain. Changing any lever recalculates margin contribution per dealer tier, per model line, and per district in under a second.

Excel ยท Sensitivity Spine (concept excerpt)
=LET(
   landed_cost,   BaseCost * (1 + ImportCostShift) * FX_Multiplier,
   net_asp,       BaseASP   * (1 + PassThroughPct) * (1 - DealerPressure),
   unit_margin,   net_asp - landed_cost,
   volume,        BaseVolume * (1 + Elasticity * PassThroughPct),
   gross_margin,  unit_margin * volume,

   gross_margin                              // single EBITDA-feed surface
)
4. The Variance Commentary Layer

Every scenario output ships with a one-line commentary: "At 5% cost / 2% pass-through, premium tier absorbs 60% of impact; commuter tier requires ฮ” โˆ’1.2% volume to break even." The numbers don't speak for themselves; the model speaks for them. That's the FP&A craft โ€” translating math into a sentence the CEO can act on.

5. Financial Impact & Outcome
๐Ÿ’ฐ Margin Defended: protected ~NPR 2.5 Cr of annualized gross margin during a 5% import-cost shock by enabling a tier-differentiated pass-through within 48 hours. โšก Decision Latency Collapsed: sensitivity answers delivered live in pricing meetings instead of a 3-day side-modeling cycle โ€” pricing windows no longer close before the math arrives. ๐Ÿ“Š Commentary as Output: every scenario ships with a one-line tier-level narrative, not just a number โ€” leadership acts on the answer instead of asking a follow-up. ๐ŸŽฏ Re-Useable Across Categories: the same spine answers tire-pricing, lubricant-margin, and accessory-mix questions โ€” one model, many commercial conversations.
View Implementation Details
FP&A / Annual Budgeting Cycle Architecture

Streamlined Annual Budgeting Workflow (FY 26-27 Cycle Redesign)

Redesigned the annual budgeting cycle from a 6-week, eight-spreadsheet consolidation marathon into a 12-day driver-anchored workflow with a single source of truth for assumptions, accountable owners per driver, and a built-in variance-commentary layer โ€” turning budgeting from an administrative ritual into the strategic conversation it was meant to be.

โฑ๏ธ-65%Cycle Time
๐Ÿ“Š100%Driver Ownership
๐ŸŽฏ1Source of Truth
1. Business Context โ€” Budgeting as Bureaucracy

The legacy budgeting cycle ran 6 weeks. Eight parallel spreadsheets โ€” one per department head โ€” funneled through three rounds of consolidation by a single analyst who became the bottleneck. By the time the board approved the plan, half the assumptions were already stale. Worse: nobody owned the drivers. Sales blamed product for ASP; product blamed sales for volume. The plan landed, the variance started immediately, and accountability dissolved into a blame loop by Q2.

2. The "So What" โ€” Why a Budgeting Cycle Is a Strategic Asset
  • A defensible plan compounds: every quarter spent re-forecasting is a quarter not spent executing.
  • Driver ownership = accountability: if Sales owns showroom count and Product owns ASP, variance has a name attached the moment it appears.
  • Speed is strategy: a 12-day budgeting cycle frees 4 weeks of FP&A capacity for commercial analysis, scenario work, and decision support.
3. The Redesign โ€” Five Architectural Choices
  • Driver-first, not P&L-first: the budget starts from operational drivers (showrooms, units, ASP, mix), not from last year's P&L lines. Numbers fall out of the drivers, not the other way around.
  • One source of truth: a single shared workbook (Power Query + structured tables) replaces the eight parallel files. Department heads input drivers into their sheet; consolidation is a refresh, not a copy-paste.
  • Owner per driver, not per department: every driver row carries a named owner. Variance flows to the owner, not the function.
  • Embedded variance commentary: each driver cell ships with a "rationale" field. When the variance hits in Q1, the original logic is on screen โ€” no email archaeology required.
  • Pre-budget sanity loop: a 3-day sensitivity pass before board submission catches the 80% of issues that previously surfaced in board review.
4. The Workflow โ€” From Day 0 to Board Submission

Day 1-3: driver kickoff โ€” each owner submits their input range with rationale. Day 4-6: automated consolidation + first-cut P&L view. Day 7-8: sensitivity pass on top 5 risk drivers. Day 9-10: leadership review with three scenarios on the table. Day 11-12: board pack assembled, narrative written, plan locked.

5. Financial Impact & Outcome
โฑ๏ธ Cycle Time -65%: budgeting collapsed from 6 weeks to 12 working days โ€” freeing ~4 weeks of FP&A capacity per cycle for forward-looking commercial work. ๐Ÿ“Š Variance Accountability: every Q1 variance has a named owner attached at the driver level, ending the "Sales vs Product" blame loop on ASP and volume. ๐ŸŽฏ Plan Credibility Restored: leadership now treats the plan as a steering document, not a ceremonial number โ€” re-forecast frequency dropped from quarterly to once at half-year. ๐Ÿ’ผ FP&A Repositioned: the function shifted from "spreadsheet consolidator" to "scenario partner" โ€” exactly the FP&A maturity arc this redesign was built for.
View Implementation Details
Excel / Power Query / VBA

Financial Incentive Reconciliation โ€” Multi-District Margin Audit

Recovered ~NPR 4 Cr annually in mis-allocated incentive expense across 12+ districts by replacing manual logistics-balance reconciliation with an audited Power Query + VBA pipeline โ€” giving commercial leadership a clean view of true per-district cost-to-serve instead of a blended average that hid the worst-performing routes.

๐Ÿ’ฐNPR 4CrMis-Allocation Recovered
โฑ๏ธ-85%Reconciliation Effort
๐Ÿ“Š12+Districts Visible
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

Treasury Verification Dashboard โ€” Strategic Vendor Payment Control

Transformed the weekly 200-vendor payment cycle from a "trust the spreadsheet" gamble into an auditable treasury control surface โ€” letting the finance director verify dealer-level aging, bank-route exposure, and overpayment risk before a single rupee leaves the bank, while accelerating cycle time enough to capture early-payment supplier discounts the old workflow used to miss.

๐Ÿ’ฐNPR 3M+Early-Pay Discount Captured
๐Ÿ›ก๏ธ100%Audit Trail Coverage
โฑ๏ธDaysโ†’SecTreasury Cycle Time
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

Board-Pack Freezer โ€” Audit-Stable Reporting Handoff

Eliminated the recurring "refresh failed" credibility hit on board packs and external audit deliverables by hardening every live Power Query workbook into a frozen, dependency-free artifact โ€” so what the CFO certifies is what the recipient sees, with zero risk of downstream value drift undermining the FP&A function's reliability score.

๐Ÿ›ก๏ธ100%Handoff Reliability
๐ŸงพZeroRefresh-Fail Incidents
โฑ๏ธ1-ClickPack-Ready Cycle
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 Settlement โ€” Dealer Payout Optimization

Compressed dealer incentive settlement from a 5-day reconciliation marathon into a single refresh, defending NPR 70K+ per scheme cycle against payout leakage and freeing the commercial team to act on scheme performance while the campaign is still live โ€” instead of post-mortem in the following month.

๐Ÿ’ฐNPR 70K+Payout Leakage Defended
โฑ๏ธ-80%Settlement Cycle Time
๐ŸŽฏ100%Audit-Trail Coverage
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
๐Ÿ’ฐ Payout Defended: chassis-level reconciliation prevented ~NPR 70K of double-paid or unsupported incentives per scheme cycle โ€” recovered margin that previously leaked silently. โฑ๏ธ Cycle Time -80%: dealer credit-note batches that took finance 5 days of manual cross-check now ship the same afternoon a scheme closes, accelerating dealer cash flow and goodwill. ๐Ÿ“Š Decision Velocity: commercial leadership now sees scheme effectiveness during the window โ€” not in next month's review โ€” enabling mid-campaign tactical adjustments. ๐Ÿ›ก๏ธ Audit-Defensible: every payout traces to a chassis number with full lineage; the workbook polices itself before finance signs the batch.
View Implementation Details
Power Query / Portable Folder Importer Pattern

Portable FP&A Workbook Pattern โ€” Cross-Analyst Continuity

Solved the "it worked on my machine" tax that costs FP&A teams ~3 days per analyst handover by lifting the file-path dependency into a single control cell โ€” so reporting models survive analyst turnover, vacation coverage, and laptop swaps without a single re-pointing exercise, protecting the continuity of monthly close and management reporting.

๐Ÿ”„ZeroHandover Friction
โฑ๏ธ~3 DaysSaved Per Handover
๐Ÿ›ก๏ธ100%Reporting Continuity
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 โ€” Receivables Margin Defense

Built a receivables-side decision engine that recovered NPR 6M+ of interest income previously written off through under-policed cash discount payouts, while sharpening commercial leverage by surfacing dealer credit behavior โ€” who pays early, who drifts, who silently consumes working capital โ€” at the point of monthly settlement instead of quarterly post-mortem.

๐Ÿ’ฐNPR 6M+Interest Income Defended
๐Ÿ“‰-12 DaysDSO Improvement
๐Ÿ“Š100%Dealer Coverage
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
๐Ÿ’ฐ Margin Recovery: ~NPR 6M+ of interest income that previously leaked through misclassified cash-discount payouts is now defended by the engine on every monthly close. ๐Ÿ“‰ Working Capital Lift: DSO trimmed by ~12 days on the dealer book through visibility into who actually earns the discount vs who simply asks for it. ๐ŸŽฏ Commercial Leverage: dealer credit behavior surfaced at month-end, not quarter-end โ€” the credit committee now intervenes before exposure ages. ๐Ÿ›ก๏ธ Audit-Defensible: the Check sheet ties source ledger to settlement output before any credit-note batch is released.
View Implementation Details
Power Query / Reusable Ledger Normalizer Pattern

Reversal-Aware Ledger Normalizer โ€” Defending Reporting Integrity

Killed the class of double-counted-reversal bugs that historically inflated dealer settlements, interest accruals, and TDS payouts by 2โ€“4% โ€” protecting an estimated NPR 1.8M+ per quarter in payout integrity by tagging mirror reversals at the source, before any downstream FP&A model has a chance to re-introduce the error.

๐Ÿ’ฐNPR 1.8M+Payout Integrity / Qtr
๐Ÿ›ก๏ธZeroPhantom Doubles
๐Ÿ”Drop-InReusable Across Models
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

Incentive Posting Generator โ€” Month-End Close Acceleration

Trimmed an estimated 6 hours from every month-end close by replacing manual incentive voucher typing with a balanced-by-construction posting generator โ€” eliminating the off-by-paisa errors that previously cost ~NPR 250K/year in retrospective adjustments and freeing senior accountants to focus on variance commentary instead of data entry.

๐Ÿ’ฐNPR 250KAdjustment Errors Eliminated
โฑ๏ธ-6 HrsMonth-End Close
โš–๏ธAlwaysBalanced By Math
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 Payment Decision Pack โ€” Treasury & Working-Capital Control

Converted the weekly NPR 23.49M vendor payment cycle from a "trust and release" routine into a controllable treasury lever โ€” letting finance leadership prioritize early-pay discount captures, defer non-critical lines, and route Everest-Bank vs non-Everest exposure through the right channel, while every released rupee carries a per-vendor audit sheet that ties to the penny.

๐Ÿ’ฐNPR 23.49MWeekly Cycle Controlled
๐Ÿฆ2-LaneBank Routing Discipline
๐Ÿงพ100%Per-Vendor Audit Trail
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-Bridged Vendor-Bank Resolver โ€” Payment-Error Risk Defense

Eliminated the misrouted-payment risk class โ€” the kind that costs companies millions when a payment hits the wrong vendor's bank account โ€” by bridging SAP BP master to vendor bank master through PAN identity, with an approval-gate that structurally blocks unapproved records from ever reaching the payment file. The fix saved an estimated NPR 1.2M+ per year in averted misrouted-payment incidents and recovery costs.

๐Ÿ’ฐNPR 1.2M+Misroute Risk Defended
๐Ÿ›ก๏ธGatedApproved-Only Payments
๐Ÿ”Drop-InKYC/Onboarding Reusable
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

NPR 45 Cr Target Performance Matrix โ€” Plan-vs-Actual Variance Cockpit

Gave leadership a live cockpit for NPR 45 Cr in fiscal target performance โ€” converting month-end "we missed by X%" surprises into mid-month "Province 2 is trending -8% on commuter mix" early warnings, enabling tactical interventions that recovered an estimated NPR 3.2 Cr of at-risk revenue across the FY through earlier territory-level course corrections.

๐Ÿ’ฐNPR 3.2CrAt-Risk Revenue Recovered
๐Ÿ“‰Mid-MonthVariance Visibility
๐Ÿ“Š45 CrTarget Surface Steered
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 2026 Scenario Engine โ€” Probabilistic Forecasting Showcase

A public showcase project that demonstrates the same probabilistic-forecasting muscle FP&A uses for revenue scenario modeling โ€” pulling structured competitive data, normalizing it into a clean fact table, and simulating group-stage and knockout outcomes the same way a driver-based revenue model simulates volume ร— ASP ร— mix scenarios in a corporate plan.

๐ŸŽฒ104Scenarios Simulated
๐Ÿ“Š100%Reproducible Pipeline
โšก<1sRe-Forecast Latency
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 B1 TDS Reconciliation Engine โ€” Tax-Filing Risk Defense

Eliminated the two anomaly classes (PAN mismatch + gross-value drift) that historically caused TDS return rejections and reassessment notices โ€” defending an estimated NPR 5M+ in annualized penalty and interest exposure while compressing the pre-filing audit window from days of ledger-head review to a single one-pass query that flags every problem line before it leaves the building.

๐Ÿ’ฐNPR 5M+Penalty Exposure Defended
โฑ๏ธDaysโ†’SecPre-Filing Audit Cycle
๐Ÿ›ก๏ธ9 HeadsTDS Ledger Coverage
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 Credit Risk Intelligence โ€” Receivables Early-Warning System

Surfaced silently-deteriorating dealers a full quarter earlier than the legacy aging report by fusing sales growth, collection days, credit utilization, and margin-per-day into a single variance score โ€” converting passive month-end review into proactive credit-committee action and reducing bad-debt write-offs by an estimated NPR 4 Cr+ annually on the 600-dealer book.

๐Ÿ’ฐNPR 4Cr+Bad-Debt Avoided
๐Ÿ“‰1 QtrEarlier Risk Detection
๐ŸŽฏ600Dealers Scored
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 Dealer Ledger Tracer โ€” Reconciliation-Safe Audit Output

Replaced the recurring "send me the EXC dealer ledger" Slack request with a one-paste reconciliation-safe report โ€” saving an estimated 4โ€“6 analyst hours per cycle while eliminating the storno-double-counting class of errors that historically distorted ad-hoc dealer balance asks by 2โ€“8%, with every line decoded into language the receiver can act on without a follow-up question.

โฑ๏ธ~5 HrsSaved Per Request
๐Ÿ›ก๏ธStorno-SafeNo Double-Count Risk
๐Ÿ“œHumanReceiver-Ready Output
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ยฐ True-Exposure Consolidator โ€” Credit-Limit Defense

Closed the 20โ€“40% under-reporting gap that historically let dealers breach effective credit limits unnoticed โ€” by stitching their main, CHL, Support, and Exchange BP codes into one true exposure number. The fix surfaced ~NPR 8 Cr of previously-invisible receivables overhang on the active dealer book, enabling the credit committee to renegotiate three high-risk dealer terms before exposure compounded.

๐Ÿ’ฐNPR 8CrHidden Exposure Surfaced
๐Ÿ“Š4-in-1BP Codes Unified
๐Ÿ“…Any DateAudit-Trail Ready
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 Movement Engine โ€” IRD Return-Ready Audit Surface

Cut TDS return preparation from a two-day per-vendor reconstruction exercise to a single grouped query that lands in the exact shape IRD reviewers expect โ€” saving an estimated 40+ analyst hours per filing cycle and eliminating the trailing-space master-data class of mismatches that previously caused 6โ€“8% of TDS lines to slip past quarterly review.

โฑ๏ธ40+ HrsSaved Per Filing
โš–๏ธIRD-ShapeReturn-Ready Output
๐Ÿ›ก๏ธTrim-SafeMaster-Data Defended
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

VAT Reconciliation Engine โ€” Monthly Return Defense

Killed the credit-memo sign-flip bug class that historically caused monthly VAT returns to under- or over-state net payable by ~NPR 1.5M+ per cycle โ€” by pre-correcting signs inside each CTE before any aggregation runs, so the return ships sign-safe, cancellation-safe, and tally-ready against the SAP B1 Tax Report from the first pass.

๐Ÿ’ฐNPR 1.5M+Return Error Avoided / Cycle
๐Ÿ›ก๏ธSign-ProofCredit-Memo Safe
๐Ÿ“Tax-TallySAP Report Match
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-Scoped VAT Input Register โ€” Reclaim Defense Per Project

Defended ~NPR 2 Cr in annualized VAT reclaim by giving each project manager a project-traceable input-VAT register โ€” bill number, bill date, vendor PAN, expense ledger, calculated base sanity check โ€” so every reclaimed rupee can be defended to an auditor without a side-investigation, eliminating the "unsupported" disallowance class that previously bit at quarterly review.

๐Ÿ’ฐNPR 2CrReclaim Defended / Year
๐Ÿ”Per-ProjectAuditor-Traceable
๐Ÿ“Self-CheckBase Cross-Validation
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 Map โ€” Distribution Strategy Lens

Reframed quarterly distribution review meetings around a geospatial penetration map that surfaced under-served micro-zones invisible in flat district tables โ€” informing two dealer-network expansion decisions that captured an estimated NPR 5.5 Cr in incremental revenue over the following FY by closing white-space gaps competitors were already filling.

๐Ÿ’ฐNPR 5.5CrWhite-Space Revenue Captured
๐Ÿ—บ๏ธ7+Zones Steered
๐ŸŽฏ2Network-Expansion Calls
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

AI TDS Auditor โ€” Pre-Filing Penalty Defense

Replaced the row-300-fatigue manual TDS review with an AI agent that polices every line against Nepal Income Tax Act rates and party-entity ledger mapping โ€” defending an estimated NPR 7M+ in annualized reassessment penalty exposure while shipping a tied-out First Summary workbook that is audit-defensible from row one, freeing senior tax staff from clerical review to handle the actual interpretive cases.

๐Ÿ’ฐNPR 7M+Penalty Exposure Defended
โš–๏ธAudit-ReadyTied-Out Output
โฑ๏ธHoursโ†’MinReview Cycle
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

AI Payroll Consolidator โ€” Bank-Cutoff Reliability Defense

Eliminated the recurring monthly risk of missed bank cutoffs and mis-keyed account numbers โ€” saving an estimated NPR 1M+ per year in penalty/interest from delayed disbursals plus the human cost of restart cycles โ€” by consolidating twelve scattered payroll sources into one bank-ready master table that surfaces gaps before submission instead of failing at the bank gateway.

๐Ÿ’ฐNPR 1M+Disbursal Penalty Avoided
โฑ๏ธ12โ†’1Tabs Consolidated
๐ŸšจPre-SubmitGap Detection
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