==================================================
 STORYGEN AI — STORY EXPORT
==================================================
Story ID:           18
Title:              Agentic Accounts Payable for Microsoft Dynamics 365 Business Central
Owner:              Salil Mhatre - Associate Director <salil@lithan.com>
App Type:           Agentic AI App
Input Type:         text
Status:             features_generated
Created:            2026-04-27 10:53:02 UTC
Updated:            2026-04-27 11:13:45 UTC
Features Generated: 2026-04-27 11:13:45 UTC
Total Clusters:     6
Total Features:     18

--- ORIGINAL INPUT ---
# Agentic Accounts Payable for Microsoft Dynamics 365 Business Central

## Overview
Finance teams using Microsoft Dynamics 365 Business Central spend significant time manually processing vendor invoices, matching them to purchase orders, routing approvals, and posting entries. This initiative introduces an agentic AI-powered Accounts Payable (AP) solution that integrates directly with Business Central to autonomously capture, validate, match, approve, and post invoices with human oversight only when exceptions arise.

## Actors
- **AP Clerk**: Monitors the AI agent's work, handles exceptions, and reviews flagged invoices.
- **AP Manager**: Configures approval policies, reviews agent performance, and approves high-value or exception invoices.
- **Approver / Budget Owner**: Reviews and approves invoices routed to them based on policy.
- **Vendor**: Submits invoices via email, portal, or EDI (indirect actor).
- **AI AP Agent**: Autonomous system actor that ingests, interprets, matches, and processes invoices.
- **System Administrator**: Manages the integration with Business Central, user roles, and agent configuration.

## Goals
- Reduce manual invoice processing effort by automating capture, coding, matching, and posting in Business Central.
- Shorten invoice cycle time and capture early-payment discounts.
- Improve accuracy and reduce duplicate or fraudulent payments through AI validation.
- Maintain a full, auditable trail of all agent decisions and human interventions.
- Provide real-time visibility into AP status, exceptions, and cash outflow forecasts.

## User Story
As an **AP Manager** using Microsoft Dynamics 365 Business Central, I want **an AI agent that autonomously handles the accounts payable lifecycle—from invoice intake to posting and payment scheduling**, so that **my team can focus on exception handling and strategic vendor management instead of repetitive data entry, and invoices are processed faster and more accurately**.

## Detailed Workflow
1. **Invoice Intake**: The AI agent monitors configured channels (AP inbox, vendor portal uploads, EDI feeds, scanned documents) and ingests incoming invoices in PDF, image, or structured formats.
2. **Data Extraction**: The agent uses OCR and LLM-based parsing to extract header and line-level fields (vendor, invoice number, date, PO reference, line items, taxes, totals, payment terms).
3. **Vendor Resolution**: The agent matches the invoice to an existing vendor master record in Business Central; if no match is found, it flags the invoice for vendor onboarding.
4. **Duplicate & Fraud Check**: The agent checks against historical invoices in Business Central to detect duplicates, tampered amounts, or suspicious vendor bank-detail changes.
5. **PO & Receipt Matching**: For PO-based invoices, the agent performs 2-way or 3-way matching against Purchase Orders and Posted Receipts in Business Central, within configured tolerances.
6. **GL Coding**: For non-PO invoices, the agent suggests GL account, dimension, and cost-center coding based on historical patterns and vendor category.
7. **Approval Routing**: The agent applies the configured approval matrix (amount thresholds, department, project) and routes the invoice to the correct approver via Business Central workflow or Teams/email notification.
8. **Exception Handling**: Any invoice that fails validation, matching, or policy checks is placed in an exception queue with the agent's explanation and suggested remediation for the AP Clerk.
9. **Posting**: Once approved and validated, the agent posts the purchase invoice in Business Central, creating the appropriate vendor ledger entry.
10. **Payment Proposal**: The agent generates payment proposals based on due dates, early-payment discounts, and cash availability, and submits them to the AP Manager for review.
11. **Audit Trail & Learning**: Every action, decision, and human override is logged. The agent learns from corrections to improve future coding, matching, and routing accuracy.
12. **Reporting**: The agent provides dashboards showing invoice volume, cycle time, exception rate, agent accuracy, and upcoming cash outflows.

## Acceptance Criteria
- The agent connects to Business Central via official APIs (e.g., Business Central REST API / OData) using OAuth 2.0 and respects BC permission sets.
- Invoices from email, file upload, and at least one structured channel (e.g., EDI or vendor portal) can be ingested automatically.
- Field extraction achieves ≥ 95% accuracy on header fields and ≥ 90% on line items for typical invoice formats after initial tuning.
- 2-way and 3-way PO matching is supported with configurable tolerance rules (amount and quantity).
- Duplicate invoice detection prevents posting when vendor + invoice number already exist in BC.
- Approval workflows are fully configurable by the AP Manager without code changes.
- Exceptions are clearly presented with the agent's reasoning, extracted data, and recommended action.
- AP Clerks can approve, edit, reject, or override any agent action; overrides feed back into the learning loop.
- All posted invoices appear in Business Central identically to manually entered invoices, including dimensions and audit fields.
- A complete audit log is available showing who (human or agent) did what, when, and why.
- Role-based access control restricts sensitive actions (e.g., vendor bank detail changes, payment approval) to authorized users.
- The solution supports multi-entity / multi-company setups within a single Business Central tenant.
- Dashboards display KPIs (cycle time, touchless rate, exception rate, on-time payment rate) in near real time.

## Assumptions & Constraints
- Customers are running Microsoft Dynamics 365 Business Central (cloud SaaS is primary; on-prem is out of scope for the initial release).
- Integration uses supported Business Central APIs; no direct database access.
- Vendor master data, PO data, and chart of accounts are maintained in Business Central as the system of record.
- The AI agent requires a ramp-up period during which human oversight is higher before reaching target autonomy levels.
- The solution must comply with relevant data privacy regulations (e.g., GDPR) and financial controls (e.g., SOX audit trail requirements).
- Initial release focuses on English-language invoices; multilingual support is a future enhancement.
- Payment execution itself (bank file generation / ACH) is handled by existing Business Central functionality or an integrated payment provider; the agent proposes but does not directly move funds.

--- USER STORY ---
# Agentic Accounts Payable for Microsoft Dynamics 365 Business Central

## Overview
This is an **Agentic AI App** that augments Microsoft Dynamics 365 Business Central with an autonomous Accounts Payable (AP) agent. The agent perceives incoming invoices across multiple channels, reasons about their validity and coding, and acts by matching, routing, posting, and proposing payments in Business Central — escalating to humans only when exceptions, policy thresholds, or low-confidence decisions require oversight. The result is a largely touchless AP process with finance staff redirected to exception handling and strategic work.

## Actors
- **AP Clerk**: Monitors the agent's queue, resolves exceptions, validates flagged extractions, and provides corrections that feed the agent's learning loop.
- **AP Manager**: Configures approval policies and tolerance rules, reviews agent performance dashboards, and approves high-value or exception invoices and payment proposals.
- **Approver / Budget Owner**: Reviews and approves invoices routed to them by the agent based on the configured approval matrix.
- **System Administrator**: Manages the Business Central integration, OAuth credentials, user roles, agent configuration, and channel connections.
- **Vendor** (indirect): Submits invoices via email, vendor portal, or EDI.
- **AI AP Agent** (autonomous system actor): Ingests invoices, extracts fields, resolves vendors, performs duplicate/fraud checks, executes 2-way/3-way matching, suggests GL coding, routes approvals, posts invoices to Business Central, generates payment proposals, and learns from human overrides.

## Goals
- Achieve a high touchless-processing rate for vendor invoices entering Business Central.
- Reduce manual data entry, coding, and matching effort across the AP team.
- Shorten invoice cycle time to capture early-payment discounts and improve on-time payment rates.
- Improve accuracy and reduce duplicate, fraudulent, or out-of-policy payments via AI validation.
- Maintain a complete, auditable record of every agent decision and human intervention to satisfy SOX and similar controls.
- Provide AP leadership with real-time visibility into invoice status, exceptions, agent accuracy, and cash outflow forecasts.

## User Story
As an **AP Manager** using Microsoft Dynamics 365 Business Central, I want **an AI agent that autonomously handles the accounts payable lifecycle — from invoice intake through posting and payment proposal — escalating to my team only on exceptions**, so that **my staff can focus on exception handling and vendor strategy while invoices are processed faster, more accurately, and with a complete audit trail**.

## Detailed Workflow
1. **Invoice Intake (Agent perceives)**: The AP Agent continuously monitors configured channels — AP inbox, vendor portal uploads, EDI feeds, and scanned documents — and ingests new invoices in PDF, image, or structured formats.
2. **Data Extraction (Agent reasons)**: Using OCR and LLM-based parsing, the agent extracts header and line-level fields (vendor, invoice number, date, PO reference, line items, taxes, totals, payment terms) and assigns a confidence score to each field.
3. **Vendor Resolution (Tool call: BC Vendor API)**: The agent looks up the vendor in the Business Central vendor master. If no confident match exists, the invoice is routed to the AP Clerk for vendor onboarding rather than guessing.
4. **Duplicate & Fraud Check (Guardrail)**: The agent queries historical invoices in BC to detect duplicates (vendor + invoice number), tampered amounts, or suspicious bank-detail changes. Any suspected fraud is automatically halted and escalated — the agent does not post under any circumstance.
5. **PO & Receipt Matching (Tool call: BC PO/Receipt API)**: For PO-based invoices, the agent performs 2-way or 3-way matching against Purchase Orders and Posted Receipts within configured tolerances. Variances inside tolerance proceed; out-of-tolerance variances become exceptions.
6. **GL Coding (Agent reasons from history)**: For non-PO invoices, the agent proposes GL account, dimension, and cost-center coding based on historical posting patterns, vendor category, and line description. If confidence is below threshold, the agent defers coding to the AP Clerk.
7. **Approval Routing (Hand-off to humans)**: The agent applies the configured approval matrix (amount thresholds, department, project) and routes the invoice to the correct approver via BC workflow, Teams, or email — including its extracted data, matching results, and a plain-language rationale.
8. **Exception Handling**: Any invoice failing validation, matching, fraud, or policy checks is placed in an exception queue with the agent's explanation, evidence, and recommended remediation. The AP Clerk can accept, edit, reject, or override.
9. **Posting (Agent acts)**: Once approved and validated, the agent posts the purchase invoice in Business Central, creating the appropriate vendor ledger entry, dimensions, and audit fields.
10. **Payment Proposal**: The agent generates payment proposals optimized for due dates, early-payment discounts, and cash availability, and submits them to the AP Manager for review. The agent does **not** execute payment itself.
11. **Audit Trail & Learning**: Every perception, decision, tool call, and human override is logged with timestamp, actor, and rationale. The agent incorporates corrections into its coding, matching, and routing models over time.
12. **Reporting**: The agent surfaces dashboards showing invoice volume, cycle time, touchless rate, exception rate, agent accuracy, override rate, and upcoming cash outflows.

## Acceptance Criteria
- The agent connects to Business Central exclusively via official APIs (REST/OData) using OAuth 2.0 and respects BC permission sets — no direct database access.
- Invoices can be ingested automatically from email, file upload, and at least one structured channel (EDI or vendor portal).
- Field-extraction accuracy is ≥ 95% on header fields and ≥ 90% on line items for typical invoice formats after initial tuning, measured against AP Clerk corrections.
- 2-way and 3-way PO matching is supported with AP Manager–configurable amount and quantity tolerances.
- Duplicate detection blocks posting whenever a vendor + invoice number combination already exists in BC, regardless of agent confidence.
- Approval workflows and matrices are fully configurable by the AP Manager without code changes.
- Exceptions are presented with the agent's extracted data, reasoning, confidence scores, and recommended action.
- AP Clerks and Managers can approve, edit, reject, or override any agent action; all overrides feed back into the learning loop.
- Posted invoices appear in Business Central identically to manually entered invoices, including dimensions, attachments, and audit fields.
- A complete, immutable audit log records who (human or agent) did what, when, and why, sufficient for SOX-style review.
- Role-based access control restricts sensitive actions (vendor bank detail changes, payment approval, agent configuration) to authorized users.
- Multi-entity / multi-company setups within a single Business Central tenant are supported.
- Dashboards display KPIs (cycle time, touchless rate, exception rate, on-time payment rate, agent accuracy) in near real time.

### Agent Guardrails & Stop Conditions
- **Defer to human** when extraction confidence on any required field falls below a configurable threshold.
- **Defer to human** when no confident vendor match exists — the agent never creates a vendor record on its own.
- **Hard stop** on suspected fraud signals (e.g., recently changed vendor bank details, anomalous totals, mismatched remit-to addresses) — the invoice is quarantined and the AP Manager is notified.
- **Hard stop** on detected duplicates — the agent will not post under any circumstance.
- **Hard stop** on PO/receipt mismatches outside configured tolerance.
- **Boundary**: The agent may propose payments but must never execute fund movement; payment runs remain a human-authorized action in BC or the integrated payment provider.
- **Escalation**: Any invoice exceeding a configurable monetary threshold is routed to the AP Manager regardless of other checks.
- **Ramp-up mode**: During an initial configurable period, the agent operates in "suggest only" mode for posting, requiring human confirmation before write-back to BC.

## Assumptions & Constraints
- Customers are running Microsoft Dynamics 365 Business Central cloud SaaS; on-prem deployments are out of scope for the initial release.
- Integration uses supported Business Central APIs only; no direct database access.
- Vendor master data, purchase orders, posted receipts, and the chart of accounts are maintained in Business Central as the system of record.
- The agent requires a ramp-up period with elevated human oversight before reaching target autonomy and accuracy levels.
- The solution must comply with applicable data privacy regulations (e.g., GDPR) and financial controls (e.g., SOX audit trail requirements).
- Initial release supports English-language invoices; multilingual support is planned as a future enhancement.
- Payment execution (bank file generation, ACH, etc.) is handled by existing Business Central functionality or an integrated payment provider — the agent proposes but does not move funds.

--- FEATURE LIST SUMMARY ---
This solution enables Microsoft Dynamics 365 Business Central customers to run a largely touchless Accounts Payable process via an autonomous AI agent that perceives invoices, reasons about validity and coding, and acts within Business Central while escalating exceptions. Primary actors include the AP Clerk, AP Manager, Approver/Budget Owner, System Administrator, and the AI AP Agent itself, with vendors as indirect contributors. The flow runs from configuration through invoice intake, extraction, vendor resolution, fraud and duplicate checks, PO matching, GL coding, approval routing, posting, payment proposal, and analytics. The Master Data Configuration cluster centralizes users, roles, vendors, tolerance and approval policies, channels, and agent configuration. The 18 features deliver autonomous AP processing, configurable guardrails, and full audit and learning loops.

Feature Clusters & Features:
• Master Data Configuration
  - 1. User, Role & Permission Management — Central registry of finance users, roles, and BC permission sets that govern who can approve, override, or configure the agent.
  - 2. Company & Multi-Entity Setup — Stores legal entities and company-specific settings so the agent can process invoices correctly across multi-company BC tenants.
  - 3. Vendor Master Reference — Synchronizes the Business Central vendor master so the agent can resolve incoming invoices to known vendors without creating records itself.
  - 4. Approval Matrix & Tolerance Policies — Configurable thresholds, approver hierarchies, and 2-way/3-way matching tolerances applied during routing and validation.
  - 5. Channel & Integration Configuration — Manages OAuth credentials, BC API endpoints, AP inbox, vendor portal, and EDI feed connections used by the agent.
  - 6. Agent Configuration & Guardrails — Defines confidence thresholds, ramp-up mode, monetary escalation limits, and stop conditions that constrain agent autonomy.
• Invoice Intake
  - 7. Multi-Channel Invoice Ingestion — Continuously pulls invoices from email, vendor portal uploads, EDI feeds, and scanned files into a unified processing queue.
  - 8. OCR & LLM Field Extraction — Extracts header and line-level invoice fields with per-field confidence scores using OCR and LLM-based parsing.
• Validation & Matching
  - 9. Vendor Resolution — Matches extracted vendor details to the BC vendor master and defers unknown vendors to AP Clerks for onboarding.
  - 10. Duplicate & Fraud Detection — Screens invoices for duplicate vendor/invoice numbers, tampered amounts, and suspicious bank-detail changes, hard-stopping risky items.
  - 11. PO & Receipt Matching — Performs 2-way and 3-way matching of invoices against Business Central POs and posted receipts within configured tolerances.
  - 12. GL Coding Suggestion — Proposes GL accounts, dimensions, and cost centers for non-PO invoices based on history, vendor category, and line context.
• Approval & Exception Handling
  - 13. Approval Routing & Notifications — Routes invoices to the correct approver via BC workflow, Teams, or email with extracted data and agent rationale.
  - 14. Exception Queue & Human Review — Surfaces failed or low-confidence invoices to AP Clerks with evidence and recommended remediation actions.
• Posting & Payment
  - 15. Invoice Posting to Business Central — Posts approved invoices to BC via official APIs, creating vendor ledger entries, dimensions, and attachments.
  - 16. Payment Proposal Generation — Generates optimized payment proposals balancing due dates, discounts, and cash availability for AP Manager approval.
• Agent Orchestration & Learning
  - 17. Audit Trail & Learning Loop — Immutable log of every agent perception, decision, tool call, and human override that also feeds model improvement.
  - 18. AP Performance Dashboards — Real-time KPIs covering cycle time, touchless rate, exception rate, agent accuracy, and upcoming cash outflows.

--- FEATURE LIST (18 features across 6 clusters) ---

#1 | Cluster: Master Data Configuration | Feature: User, Role & Permission Management
  Description: Central authority for user identities, roles, and permissions that govern who can configure the agent, approve invoices, or override decisions. Aligns with Business Central permission sets to enforce least-privilege access.
  Workflow:
    1. Administrator creates user accounts and links them to BC identities.
    2. Assigns roles (AP Clerk, AP Manager, Approver, Admin) with associated permission sets.
    3. Configures sensitive-action restrictions (vendor bank changes, payment approval, agent config).
    4. Reviews and audits role assignments periodically.
  Table:       ap_users_roles
  Columns:     id (bigint, pk), bc_user_id (varchar 100), email (varchar 255), role_code (varchar 50), permission_set (varchar 100), company_id (bigint, fk), is_active (boolean), created_at (timestamp)
  Actor:       System Administrator
  AI Agent:    None
  ----
#2 | Cluster: Master Data Configuration | Feature: Company & Multi-Entity Setup
  Description: Defines each Business Central company within the tenant so the agent can correctly scope invoices, posting, and approvals. Supports multi-entity organizations sharing one AP agent deployment.
  Workflow:
    1. Admin registers each BC company/legal entity in the tenant.
    2. Maps company-specific settings (currency, fiscal calendar, VAT setup).
    3. Associates channels and approval matrices per entity.
    4. Validates connectivity per company.
  Table:       ap_companies
  Columns:     id (bigint, pk), bc_company_id (varchar 100), company_name (varchar 255), base_currency (varchar 10), fiscal_calendar_id (bigint), is_active (boolean), created_at (timestamp)
  Actor:       System Administrator
  AI Agent:    None
  ----
#3 | Cluster: Master Data Configuration | Feature: Vendor Master Reference
  Description: Synchronized snapshot of the BC vendor master used by the agent for vendor resolution and fraud detection. Vendor records are never created by the agent — only referenced.
  Workflow:
    1. Sync vendor master from BC via OData on schedule.
    2. Cache vendor identifiers, tax IDs, bank details, and remit-to addresses.
    3. Track changes (especially bank-detail changes) for fraud signals.
    4. Expose vendor lookup to the agent.
  Table:       ap_vendor_cache
  Columns:     id (bigint, pk), bc_vendor_id (varchar 100), company_id (bigint, fk), vendor_name (varchar 255), tax_id (varchar 50), bank_account (varchar 100), bank_changed_at (timestamp), last_synced_at (timestamp)
  Actor:       System Administrator
  AI Agent:    Vendor Resolution Agent
  ----
#4 | Cluster: Master Data Configuration | Feature: Approval Matrix & Tolerance Policies
  Description: Configurable rules engine for approval routing, tolerance bands, and escalation thresholds used by the agent during validation and routing. Fully editable by the AP Manager without code changes.
  Workflow:
    1. AP Manager defines approval thresholds by amount, department, and project.
    2. Configures 2-way/3-way matching tolerances (amount %, quantity %).
    3. Sets escalation thresholds for AP Manager review.
    4. Activates and versions the policy.
  Table:       ap_approval_policies
  Columns:     id (bigint, pk), company_id (bigint, fk), rule_type (varchar 50), amount_min (decimal 18,2), amount_max (decimal 18,2), tolerance_pct (decimal 5,2), approver_role (varchar 50), version (int), is_active (boolean)
  Actor:       AP Manager
  AI Agent:    None
  ----
#5 | Cluster: Master Data Configuration | Feature: Channel & Integration Configuration
  Description: Manages the agent's connections to Business Central APIs and invoice intake channels. Stores OAuth credentials, endpoints, and channel-specific settings securely.
  Workflow:
    1. Admin registers BC OAuth 2.0 credentials and API endpoints.
    2. Configures AP email inbox, vendor portal, and EDI connections.
    3. Tests connectivity and permissions.
    4. Schedules polling intervals and retries.
  Table:       ap_channels
  Columns:     id (bigint, pk), company_id (bigint, fk), channel_type (varchar 50), endpoint_url (varchar 500), oauth_client_id (varchar 255), credential_secret_ref (varchar 255), poll_interval_sec (int), is_active (boolean)
  Actor:       System Administrator
  AI Agent:    None
  ----
#6 | Cluster: Master Data Configuration | Feature: Agent Configuration & Guardrails
  Description: Controls the agent's autonomy boundaries, confidence thresholds, ramp-up mode, and stop conditions. Ensures the agent defers to humans whenever guardrails are triggered.
  Workflow:
    1. AP Manager sets confidence thresholds for extraction and coding.
    2. Toggles ramp-up (suggest-only) mode and its duration.
    3. Defines hard-stop conditions and escalation monetary thresholds.
    4. Saves versioned configuration with audit trail.
  Table:       ap_agent_config
  Columns:     id (bigint, pk), company_id (bigint, fk), header_confidence_min (decimal 5,2), line_confidence_min (decimal 5,2), ramp_up_until (date), escalation_amount (decimal 18,2), suggest_only (boolean), version (int)
  Actor:       AP Manager
  AI Agent:    AI AP Agent
  ----
#7 | Cluster: Invoice Intake | Feature: Multi-Channel Invoice Ingestion
  Description: Continuously ingests vendor invoices from email, portal, EDI, and uploads into a unified processing pipeline. Each invoice gets an immutable intake record with original source.
  Workflow:
    1. Agent polls AP inbox, vendor portal, EDI, and uploaded files.
    2. Downloads new invoice documents and metadata.
    3. Deduplicates by source ID and assigns intake ID.
    4. Persists raw document and queues for extraction.
  Table:       ap_invoice_intake
  Columns:     id (bigint, pk), company_id (bigint, fk), channel_id (bigint, fk), source_ref (varchar 255), file_path (varchar 500), received_at (timestamp), status (varchar 30), intake_hash (varchar 128)
  Actor:       Invoice Intake Agent
  AI Agent:    Invoice Intake Agent
  ----
#8 | Cluster: Invoice Intake | Feature: OCR & LLM Field Extraction
  Description: Uses OCR and LLM-based parsing to extract header and line-level invoice fields with per-field confidence scoring. Low-confidence extractions trigger AP Clerk validation.
  Workflow:
    1. Agent runs OCR on PDFs/images and parses structured formats.
    2. LLM extracts header fields (vendor, invoice no, date, totals) and lines.
    3. Confidence score assigned per field.
    4. Low-confidence fields flagged for human review.
    5. Extracted payload stored alongside intake record.
  Table:       ap_invoice_extraction
  Columns:     id (bigint, pk), intake_id (bigint, fk), field_name (varchar 100), field_value (text), confidence (decimal 5,2), is_line (boolean), line_no (int), extracted_at (timestamp)
  Actor:       Extraction Agent
  AI Agent:    Invoice Extraction Agent
  ----
#9 | Cluster: Validation & Matching | Feature: Vendor Resolution
  Description: Matches extracted vendor details against the Business Central vendor master with confidence scoring. The agent never creates vendor records, deferring unknown vendors to AP Clerks.
  Workflow:
    1. Agent looks up vendor by tax ID, name, and remit-to.
    2. Computes match confidence against vendor cache.
    3. Resolves to BC vendor or marks as unknown.
    4. Unknown vendors routed to AP Clerk for onboarding in BC.
  Table:       ap_vendor_match
  Columns:     id (bigint, pk), intake_id (bigint, fk), bc_vendor_id (varchar 100), match_confidence (decimal 5,2), match_method (varchar 50), status (varchar 30), resolved_at (timestamp)
  Actor:       Vendor Resolution Agent
  AI Agent:    Vendor Resolution Agent
  ----
#10 | Cluster: Validation & Matching | Feature: Duplicate & Fraud Detection
  Description: Guardrail layer that blocks duplicate invoices and quarantines suspected fraud cases regardless of agent confidence. Ensures the agent never posts risky invoices.
  Workflow:
    1. Agent checks vendor + invoice number against BC history.
    2. Scans for tampered totals, anomalies, and recent vendor bank changes.
    3. Compares remit-to with vendor master.
    4. Hard-stops and quarantines on any duplicate or fraud signal.
    5. Notifies AP Manager.
  Table:       ap_fraud_checks
  Columns:     id (bigint, pk), intake_id (bigint, fk), check_type (varchar 50), result (varchar 30), evidence (text), severity (varchar 20), checked_at (timestamp)
  Actor:       Fraud Detection Agent
  AI Agent:    Fraud Detection Agent
  ----
#11 | Cluster: Validation & Matching | Feature: PO & Receipt Matching
  Description: Performs 2-way and 3-way matching between invoices, purchase orders, and receipts within AP Manager-configured tolerances. Out-of-tolerance variances become exceptions for human review.
  Workflow:
    1. Agent retrieves PO and posted receipts via BC API.
    2. Performs 2-way (PO/invoice) or 3-way (PO/receipt/invoice) match.
    3. Compares against configured tolerances.
    4. Within tolerance: proceed. Out of tolerance: exception.
    5. Records match results.
  Table:       ap_po_match
  Columns:     id (bigint, pk), intake_id (bigint, fk), bc_po_id (varchar 100), bc_receipt_id (varchar 100), match_type (varchar 20), variance_amount (decimal 18,2), variance_qty (decimal 18,4), within_tolerance (boolean), matched_at (timestamp)
  Actor:       Matching Agent
  AI Agent:    PO Matching Agent
  ----
#12 | Cluster: Validation & Matching | Feature: GL Coding Suggestion
  Description: Suggests GL accounts, dimensions, and cost centers for non-PO invoice lines based on historical posting patterns and vendor category. Low-confidence coding is deferred to AP Clerks.
  Workflow:
    1. For non-PO invoices, agent retrieves historical postings for the vendor.
    2. Predicts GL account, dimensions, and cost center per line.
    3. Assigns coding confidence per line.
    4. Below threshold: defer to AP Clerk for coding.
    5. Saves suggested coding for posting.
  Table:       ap_gl_coding
  Columns:     id (bigint, pk), intake_id (bigint, fk), line_no (int), gl_account (varchar 50), dimension_set (varchar 255), cost_center (varchar 50), confidence (decimal 5,2), suggested_at (timestamp)
  Actor:       GL Coding Agent
  AI Agent:    GL Coding Agent
  ----
#13 | Cluster: Approval & Exception Handling | Feature: Approval Routing & Notifications
  Description: Routes invoices to the correct approver based on the configured approval matrix using BC workflow, Teams, or email channels. Each routing includes the agent's extracted data and reasoning.
  Workflow:
    1. Agent applies approval matrix to determine approver(s).
    2. Sends invoice with rationale via BC workflow, Teams, or email.
    3. Tracks approver responses and reminders.
    4. Records decisions and proceeds to posting on approval.
  Table:       ap_approval_routing
  Columns:     id (bigint, pk), intake_id (bigint, fk), approver_user_id (bigint, fk), channel (varchar 30), routed_at (timestamp), decision (varchar 20), decided_at (timestamp), comments (text)
  Actor:       Approver / Budget Owner
  AI Agent:    Approval Routing Agent
  ----
#14 | Cluster: Approval & Exception Handling | Feature: Exception Queue & Human Review
  Description: Centralized queue for invoices that fail validation, matching, fraud, or confidence checks. Presents the agent's reasoning and recommended remediation to AP Clerks for resolution.
  Workflow:
    1. Failed checks place invoice in exception queue with reason and evidence.
    2. AP Clerk reviews agent rationale and confidence scores.
    3. Clerk accepts, edits, rejects, or overrides agent decision.
    4. Override fed back to learning loop.
    5. Resolved invoice resumes processing.
  Table:       ap_exceptions
  Columns:     id (bigint, pk), intake_id (bigint, fk), exception_type (varchar 50), reason (text), recommended_action (varchar 255), assigned_to (bigint, fk), status (varchar 30), resolved_at (timestamp)
  Actor:       AP Clerk
  AI Agent:    Exception Triage Agent
  ----
#15 | Cluster: Posting & Payment | Feature: Invoice Posting to Business Central
  Description: Posts approved purchase invoices to Business Central via official APIs, creating vendor ledger entries, dimensions, and attachments identical to manual entry. Honors ramp-up suggest-only mode.
  Workflow:
    1. Agent assembles posting payload (header, lines, dimensions, attachments).
    2. In ramp-up mode, requests human confirmation.
    3. Calls BC purchase invoice API to post.
    4. Captures resulting BC document number and ledger entry.
    5. Logs posting outcome.
  Table:       ap_postings
  Columns:     id (bigint, pk), intake_id (bigint, fk), bc_document_no (varchar 50), bc_ledger_entry_id (varchar 100), posted_at (timestamp), posted_by (varchar 100), status (varchar 30), error_message (text)
  Actor:       Posting Agent
  AI Agent:    Invoice Posting Agent
  ----
#16 | Cluster: Posting & Payment | Feature: Payment Proposal Generation
  Description: Generates optimized payment proposals balancing due dates, early-payment discounts, and cash availability. AP Manager approves; payment execution remains a human-authorized BC action.
  Workflow:
    1. Agent scans posted unpaid invoices for upcoming due dates and discounts.
    2. Optimizes selection against cash availability rules.
    3. Generates payment proposal with rationale.
    4. Submits to AP Manager for review and approval.
    5. Agent never executes the actual payment.
  Table:       ap_payment_proposals
  Columns:     id (bigint, pk), company_id (bigint, fk), proposal_date (date), total_amount (decimal 18,2), invoice_count (int), status (varchar 30), submitted_to (bigint, fk), approved_at (timestamp)
  Actor:       AP Manager
  AI Agent:    Payment Optimization Agent
  ----
#17 | Cluster: Agent Orchestration & Learning | Feature: Audit Trail & Learning Loop
  Description: Immutable audit log of all agent and human actions with rationale, supporting SOX-style review. Human overrides are routed back into agent learning to improve coding, matching, and routing accuracy.
  Workflow:
    1. Every agent perception, decision, tool call, and human override logged immutably.
    2. Records timestamp, actor, rationale, inputs, and outputs.
    3. Overrides feed model retraining/fine-tuning pipeline.
    4. Provides SOX-grade audit reports on demand.
  Table:       ap_audit_log
  Columns:     id (bigint, pk), intake_id (bigint, fk), actor_type (varchar 20), actor_id (varchar 100), action (varchar 100), rationale (text), payload_ref (varchar 255), created_at (timestamp)
  Actor:       AI AP Agent
  AI Agent:    Orchestration & Learning Agent
  ----
#18 | Cluster: Agent Orchestration & Learning | Feature: AP Performance Dashboards
  Description: Real-time KPI dashboards covering invoice volume, cycle time, touchless rate, exception rate, on-time payment rate, agent accuracy, and cash outflow forecasts. Supports AP leadership decisions.
  Workflow:
    1. Aggregate metrics on volume, cycle time, touchless rate, exceptions.
    2. Compute agent accuracy and override rate against clerk corrections.
    3. Forecast upcoming cash outflows from open invoices.
    4. Render real-time dashboards for AP Manager.
  Table:       ap_kpi_metrics
  Columns:     id (bigint, pk), company_id (bigint, fk), metric_name (varchar 100), metric_value (decimal 18,4), period_start (date), period_end (date), computed_at (timestamp)
  Actor:       AP Manager
  AI Agent:    Analytics Agent
  ----

==================================================
 END OF STORY EXPORT
==================================================
