# Hascol table mapping

## Direct functions for common questions

The current scope is dealers and dealer ledgers. User-account functions and
user-table mappings have been removed; user-account requests return a scope message.

- `lib/urdu-understanding.js`: Urdu/English vocabulary, speech variants, number
  normalization, intent matching and language preference. The original transcript is preserved.
- `lib/business-intents.js`: small routing entry point importing language understanding.
- `lib/dealer-functions.js`: named `getDealerCount`, `getDealerBySap` and
  `getDealerBalance` functions with fixed parameterized read-only queries.
- `lib/dealer-replies.js`: Urdu/English answer formatting and clarification messages.
- `lib/business-functions.js`: dispatch, session context and timing measurements.
- `lib/ledger-balance.js`: exact arithmetic for signed snapshot amounts.

Dealer lookups exclude credentials and contact details. Raw status values are not
given invented meanings. The SQL fallback can select only tables in the remaining
dealer business mappings, rather than every table in the database schema.

The JSON guide still supplies table knowledge to the fallback; editing it does
not create a new direct function. A new fast function requires an intent rule,
a fixed query, an answer formatter and tests covering ambiguous requests.

Direct requests log `route: database_function`, the function name,
`modelUsed: false`, and separate `routingMs`, `databaseMs`, `answerMs` timings.
Fallback database requests log routing, query-plus-database and answer timings.
Microphone/TTS time is outside these backend timings.

SAP clarification now remembers the pending lookup within the current session,
so a digits-only reply is accepted. A uniquely found dealer becomes the context
for simple ledger follow-ups, including the STT variant `لیجنڈ`. Context expires
after 10 minutes and is not shared between sessions. Unclear numbers are still
clarified rather than guessed.

`getDealerBalance` reads `dealers.acount` by exact `sap_no` and includes
`last_baldate` when present. The spelling is `acount`, not `account`. Preserve the
stored sign and decimal precision. Missing/invalid values are not zero balances;
duplicate SAP records require clarification. Dealer ledger snapshots are not the
source for this balance. Highest-balance fallback also uses `dealers.acount`.

Run regression checks with `node --test tests/business-functions.test.js`.
Restart your own terminal server to load code changes.

The app reads `database/business_guide.json` at server startup. This is business
configuration, not model training. Restart your terminal server after changes.
`database/schema.json` is generated from the live database; do not edit it manually.

Each entry in `entities` describes a real table:

- `table`: exact table name from the schema.
- `description`: what it stores, which columns answer which questions, join keys,
  status values, date rules, units and calculations. Confirm these with your business team.
- `aliases`: phrases users say in English, Roman Urdu or Urdu script.
- `relatedTables`: optional list of exact related table names needed for joins.
  Matched and related tables together are limited to five per question.
- `countColumn` / `listColumn`: optional existing fields for simple counts/lists;
  omit them when the mapping is only for details or joins.

Existing example: dealer balance uses `request_for_dealers_ledger`, with
`customer_sap` joined to `dealers.sap_no`. The signed AMOUNT values inside
`ledger_json` determine the snapshot balance. This rule is already configured.
If you need dealer names on ledger questions, add `"relatedTables": ["dealers"]`
to that ledger entity. Do not copy this relationship onto unrelated tables.

For a new subject, copy an entry and replace its table, aliases and description
with verified details. Include example questions as aliases only when they really
identify that subject. Do not add guessed joins or status meanings.

Workflow:
1. Identify the real source tables and fields in `schema.json`.
2. Add aliases and explain the business rules in `business_guide.json`.
3. Add related tables for questions requiring joins.
4. Restart with `npm.cmd start` in your terminal.
5. Ask a known question and compare with a trusted report. `logs/chat.log` shows
   the selected tables, query pattern, row count and errors.

Descriptions inform generated read-only SQL; they do not guarantee correctness.
Existing deterministic count/list and ledger handlers take precedence, so changing
those calculations also requires updating their handler in `server.js`.
Conversational instructions are not persisted as new mappings automatically.

## Dealer products and rates

`getDealerProducts` resolves SAP to the internal `dealers.id`, then queries
`dealers_products.dealer_id`. It returns product `name`, `indent_price`,
`nozel_price` and recorded `from`/`to` periods. It supports explicit SAP and
follow-ups after a dealer lookup, or asks for SAP when no dealer is selected.
The latest 20 saved records are shown, with a truncation notice if needed.
These are saved product assignments and rate periods; no active-status flag or
current-date filter is inferred. Mixed date formats exist in this table.
