# MantriAPI PHP migration: testing, verification and deviations

## 1. How to call the API

| Item | Value |
|---|---|
| URL | `http://<host>/hrmkirangroupapp/MantriAPI/<Action>` (MVC route `{controller}/{action}/{id}`, case-insensitive). Without mod_rewrite, use `/MantriAPI/index.php/<Action>`. |
| Verbs | Actions marked `[HttpPost]` in C# accept only POST; other verbs return 404. These actions accept GET and POST: SendOTP, GetGlobalOptions, PushEmployeeNotification, EmployeeAuthToken, ByModule, NotificationInfo, PayslipGenerated, GetCanteenMenuItemList. |
| Input | JSON body (`Content-Type: application/json`), form fields, or query string, bound as MVC does (see §4). |
| Postman | `migration_docs/MantriAPI.postman_collection.json`: all 61 requests. Set `baseUrl`, `apikey` and `secretkey` in the collection variables. |

## 2. Test results (2026-11-27, local XAMPP: PHP 7.3.10, MariaDB 10.4.8)

The test scripts were run from a scratch folder; they are not part of the project.

For local DB testing, `DbConnect::clientconnect()` was pointed at `pravashr_kirangroup` through the in-memory `MANTRI_DB_OVERRIDE` constant. **No database object was created or changed.**

| Suite | Result | What it covers |
|---|---|---|
| Unit tests (CLI) | **45 / 45 pass** | JavaScriptSerializer output (field order, `<` escapes, `\/Date(ms)\/`, `{}` for NULL, decimal scale, byte[]), the C# details-string splitter (including its comma-truncation quirk), MVC binding (case-insensitive keys, `""` → null, bad int → 0, base64 → byte[]), `itemdata` deserialization, `Convert.*` semantics, TVP JSON building and reading it back with MariaDB `JSON_LENGTH`/`JSON_EXTRACT`, typed rows from MariaDB, CALL with result-set cleanup on a shared connection |
| HTTP tests (built-in server) | **29 / 29 pass** | 404 on wrong verb, unknown action and the C# helper routes; credential failures; real data from `pdv_cli`; form, JSON, query-string and `{id}` binding; SQL-injection input; the C# catch contracts (GetOption returns granted with error text, canteen saves return notgranted); HTTP 500 where C# had no catch; invalid JSON gives 500 |
| Route sweep | **61 / 61 pass** | Every action with wrong keys returns its exact response class and messages. The four endpoints that call `TPF_DateFormat` before the key check, and ByModule (no check), return 500 as C# did when that call failed. |
| Through Apache (`.htaccess`, real `DbConnect::connect()`) | pass | Routing works; `config/`, `helpers/` and `logs/` return 403. When `pdvs_client` is unreachable, clients get `Unable to connect to the database server.` and the details go only to `logs/api_error.log`. |

**Defects found and fixed during testing:**

1. **Prepared statements over views failed with MariaDB error 1615.** The DB helper now retries once, then runs the statement with escaped literals. The server setting that removes the cause is in doc 02 §6.
2. **Connection failures returned the DB user name and server paths** in the `error` field, because `DbConnect` echoes them. These are now logged only, and `display_errors` is off for the API entry point.

## 3. Endpoint verification status

**Verification levels:**

- **V1**: fully verified against the real MySQL data.
- **V2**: every branch that the current database allows has been verified.
- **V3**: routing, binding, credential branch and response class are verified. The database branch is implemented but **cannot run until the objects in doc 02 exist**.

| # | Action | Level | Blocking object(s) |
|---|---|---|---|
| 5 | GetUserCompanyAccess | **V1** | none |
| 1 | GetEmployees | **V1** (2026-11-27) | none. It now uses an inline MySQL query; `empid` is not used (doc 06). |
| 14 | GetUserRoleAccess | **V2** (2026-11-27) | none. The procedure SQL now runs inline (doc 07). Every branch was verified with seed data in a rolled-back transaction. The local tables have no rows that would return data (`msa_urar` is empty, and no `PDV_FLIH` menu has `FLIH_App = 1`). |
| 33 | PayslipGenerated | **V2** | The outbound POST was not exercised: `OPTHR_PayslipGenerateURL` is empty in all rows. |
| 34 | ChangePWD | **V2** | `CPW_Save` (the "Check your old password" path is verified) |
| 4 | LoginCheck | V3 | `EMI_GPSReqd`, `EMI_DeviceId`, `MSA_URD` |
| 8 | EmployeeNotificationCount | V3 | `CMD_Status` |
| 10 | EmployeeAuthToken | V3 | `EMI_AuthToken` |
| 11 | ByModule | V3 | `TPP_GetModules` |
| 2, 3, 6, 7, 9, 12, 13, 15–32 | all other HR endpoints | V3 | `TPP_*` procedures, `TPF_DateFormat`, `PDV_LAP`, `PDV_GPP` |
| 35–61 | all canteen endpoints | V3 | all canteen tables and `TPP_*Canteen*` procedures |

**After the DBA creates the objects, re-run per endpoint:**

1. Run the Postman request.
2. Compare the response byte-for-byte with the C# API for the same input (same `cpermission`/`cresponse`/`error`, same keys, same value types).
3. Repeat with: valid input; missing parameters; empty values; no rows; multiple rows; and a deliberately failing procedure.
4. Mark the endpoint V1 here.

## 4. Behaviour reproduced from the C# API

**Request binding (MVC DefaultModelBinder):**

- Input precedence is form > JSON > route `{id}` > query string.
- Keys are case-insensitive.
- A missing or unparseable int becomes 0, and `""` becomes `null`.
- A byte[] binds only from a base64 string.
- An invalid JSON body returns HTTP 500.

**Response serialization (JavaScriptSerializer):**

- Public fields come before properties, e.g. `ListDetails` before `cpermission`.
- Dates are `"\/Date(ms)\/"`, converted from `MANTRI_TIMEZONE`.
- Decimals keep their database scale. `<`, `>`, `&`, `'` are escaped as `<`, `>`, `&`, `'`.
- NULL is `{}` (switch with `MANTRI_NULL_AS_EMPTY_OBJECT`).
- `Content-Type: application/json; charset=utf-8`.

**Original C# behaviour kept on purpose (do not "fix" without a business decision):**

- **LoginCheck.** The key check is `apikey≠K || (secret≠S && (user or password empty))`. A wrong secret key passes when username and password are supplied.
- **SendOTP.** The request fails only when **both** keys are wrong.
- **ByModule.** It has no credential check.
- **Database calls before the key check.** AttendanceApprovalInfo, LeaveApprovalInfo, LeaveDetailsInfo and GatePassDetailsInfo query the DB before checking keys. AttendanceApprovalInfo also returns its rows when the keys are wrong.
- **Errors reported as success.** GetOption, GetUserInfo and GetUserRoleAccess report `granted`/`Success` when an exception occurs.
- **Details-string parsing.** `attappdetails`, `leaveappdetails` and `gatepassappdetails` use the hand-written splitter. A value containing `,` or `:` is truncated, and keys with leading spaces are ignored.
- **LeaveAppply day check.** The duplicate-leave and attendance check advances the date cumulatively (+0, +1, +3, +6, …), so some days in a range are not checked.
- **SaveCanteenItem.**
  - It sends the literal text `System.Byte[]` as the image parameter.
  - It stores the server's **physical folder path** as `imagepath` when an image is uploaded.
- **Canteen save procedures.** Their result sets are read and discarded; `ListDetails` is `[]`.
- **GenerateTrNo.** It reads `MAX+1`, which is not safe under concurrent requests.
- **Saves followed by push notifications.** LeaveAppply, ApproveLeave, GatePassApply and ApproveGatePass call `AutoPushNotification` **after** saving. If `MSA_OPT` has no row for the location, or FCM rejects the call, the request returns HTTP 500 even though the data was saved.
- **ChangePWD.** The new password is truncated to 40 characters (`SqlParameter.Size = 40`).

## 5. Intentional deviations

| Area | C# | PHP | Reason |
|---|---|---|---|
| Helper methods as actions | `fnReturnDt`, `fnReturnString` (run any SQL from the URL), `GenerateTrNo`, `GenerateDateFormat`, `PushNotifications`, `AutoPushNotification`, `GetTableRows`, `RandomNumber` were HTTP-routable | Private; return 404 | Critical security hole in the original |
| SQL values | Concatenated into SQL text | Prepared-statement parameters with the same values (`null` → `''` where C# concatenated) | SQL injection; required by the brief |
| SendOTP template | `{{UserName}}` substituted raw | Value escaped before substitution | SQL injection |
| Exception text in `error` | `ex.ToString()` (.NET stack trace) | Exception type and message; trace only when `MANTRI_DEBUG` is on; always logged | Brief: no stack traces in production |
| HTTP 500 / 404 bodies | IIS/ASP.NET HTML page | Minimal HTML page; details only in the log | Same status codes, no internals exposed |
| DB connection errors | n/a | Generic message; details logged | `DbConnect` output contains the user name and paths |
| Table-valued parameters | `SqlDbType.Structured` | One JSON array string in the same position | MySQL has no TVPs (your decision) |
| ByModule | `FOR JSON PATH` read with `ExecuteScalar` | Same JSON built in PHP from the same query | MariaDB 10.4 lacks FOR JSON. SQL Server splits FOR JSON output into ~2,033-character rows and `ExecuteScalar` read only the first, so large C# responses were **truncated**; PHP returns the complete object. |
| Error 1615 | n/a | Retry, then escaped-literal fallback | MariaDB view and prepared-statement issue (doc 02 §6) |
| SaveCanteenItem folder | Checked/created `\CanteenImage\` at the **drive root**, wrote to `~/CanteenImage/` | Creates and writes `<app>/CanteenImage/` | The original created the wrong folder |
| SMS gateway TLS | Forced SSL 3.0 | curl negotiates TLS with certificate verification | SSL 3.0 is disabled everywhere |
| Inline SQL dialect | `TOP`, `LEN`, `+`, `GetDate()`, `CAST AS NVARCHAR`, `TIME(0)`, `CONVERT(…,120)` | `LIMIT`, `CHAR_LENGTH`, `CONCAT`, `CURDATE()`, `CAST AS CHAR`, `TIME_FORMAT`, `DATE_FORMAT` | Same results, with these exceptions: `LEN` ignored trailing spaces, `CHAR_LENGTH` counts them; `CAST(date AS NVARCHAR)` formatting depends on the SQL Server column type; division by zero in CanteenItemList returns NULL (`{}`) instead of an error |
| Null `SqlParameter` values | Treated as "not supplied" | Sent as `NULL` | MySQL has no "not supplied" (doc 02 §2) |
| `Index` action | Returned a Razor view | Not routed (404) | Not part of the API |

## 6. Functionality that could not be migrated directly

1. **The database layer.** None of the 47 procedures, the `TPF_DateFormat` function, the canteen tables, `PDV_LAP`, `PDV_GPP`, `MSA_URD`, `PDV_EMCAN`, or the missing columns exist in MySQL. Doc 02 is the porting contract. 57 of 61 endpoints depend on at least one of them. Only GetUserCompanyAccess, PayslipGenerated, GetEmployees and GetUserRoleAccess run on the current schema; GetEmployees uses the MySQL query in doc 06, and GetUserRoleAccess the inline SQL in doc 07.
2. **Push notifications (FCM).** The code reproduces the legacy FCM API call (`Authorization: key=<server key>`). Google shut that API down in 2024, so real pushes now fail and, as in C#, the calling request returns 500. Moving to FCM HTTP v1 (OAuth service account) would change behaviour and needs your decision.
3. **SMS template SQL.** `MSA_SMST.SMST_SQLText` is SQL stored as data and was written for SQL Server. It must be rewritten in MySQL syntax; the table is currently empty.
4. **Connection target.** `DbConnect::connect()` uses database `pdvs_client`, which does not exist on this machine. On the server where the API will run, confirm that `pdvs_client` holds the HR tables.
5. **Environment assumptions** (both are config values):
   - The original server time zone is assumed to be **Asia/Kolkata** (`MANTRI_TIMEZONE`). It affects `\/Date()\/` values, transaction numbers and barcodes.
   - The server culture is assumed to be **day-first** when date strings are parsed, as `en-IN` does.
