# MantriAPI: MySQL objects required by the PHP API

This is the work list for porting the SQL Server database objects to MySQL / MariaDB. The PHP code in `MantriAPIController.php` already calls every object below, using the exact name and parameter order shown.

Until an object exists, the endpoints that use it fail the same way the C# API did when a database call failed: HTTP 500, or the endpoint's own `catch` response. Those endpoints are not verified until then (see `03_Testing_and_Verification.md`).

Conventions:

- `CALL Name(?, ?, …)` is used with positional parameters, in the order given by the C# `EXEC` string or the C# `SqlParameter` `Add()` order.
- Parameter types are suggestions that mirror the C# values. Every date is passed as text, exactly as the C# code passed it.
- **TVP** means the SQL Server table-valued parameter has been replaced by **one `LONGTEXT` parameter holding a JSON array**, in the same position.
  - Each element is an object with the C# DataTable column names.
  - Types in the JSON: int becomes a number, decimal becomes a number, datetime becomes `"yyyy-MM-dd HH:mm:ss"`, string becomes a string, DBNull becomes `null`.
  - MariaDB 10.4 has no `JSON_TABLE`. Read the rows with `JSON_LENGTH` and `JSON_EXTRACT` / `JSON_UNQUOTE` in a `WHILE` loop (template in §4).
- **Result columns used by PHP** lists only the columns that the PHP code reads by name. Any other columns are passed through to the client unchanged.
- Only the **first** result set of a procedure is used (`SqlDataAdapter.Fill` semantics). Further result sets are read and discarded.

---

## 1. Scalar function

| Function | Parameters | Returns | Used by |
|---|---|---|---|
| `TPF_DateFormat` | `p_date VARCHAR(50)`, `p_locid INT` | **VARCHAR**. The C# code read it with `Field<string>`. The value must be a date parsable as `yyyy-MM-dd`, `dd-MM-yyyy` or `dd-MMM-yyyy`, because it is also parsed as a DateTime for TVP columns and for the `LeaveAppply` day count. | AttendanceApprovalInfo, ApproveAttendance, GetLeaveBal, LeaveAppply, LeaveApprovalInfo, LeaveDetailsInfo, ApproveLeave, GatePassApply, GatePassInfo, GatePassDetailsInfo, ApproveGatePass |

## 2. Stored procedures (47)

### 2.1 Read procedures

| Procedure | Parameters, in order | Result columns used by PHP | Called by |
|---|---|---|---|
| ~~`TPP_GetEmployees`~~ | **No longer needed (2026-11-27).** GetEmployees now runs an inline MySQL query on `pdv_emi`; see doc 06. | n/a | GetEmployees |
| `TPP_GetLeaveType` | empid INT, locid INT | `leavetype`, `leavetypeid`, `minleavedays`, `allowexcessleave` | GetLeaveType |
| `TPP_GetGatePassType` | empid INT, locid INT | `gatepasstype`, `gatepasstypeid` | GetGatePassType |
| `TPP_GetSMST` | locid INT, smstype INT (always 1) | `SMST_SQLText`, `SMST_SMSText`, `SMST_MapField` | SendOTP |
| `PDV_GetGlobalOptions` | none | n/a | GetGlobalOptions |
| `TPP_PushNotification` | loginid INT, title, body, urllink, bodytype, startdate, enddate VARCHAR, locid INT | `authtoken`, `notificationid`, `title`, `bodymessage`, `bodyurl`, `isLink`, `menucode`, `menuname`, `transactionid` | PushEmployeeNotification |
| `TPP_AutoPushNotification` | none | same as `TPP_PushNotification` | LeaveAppply, ApproveLeave, GatePassApply, ApproveGatePass |
| `TPP_GetModules` | empid INT, locid INT | `modulename` | ByModule |
| `TPP_GetOptionInfo` | locid INT | n/a | GetOption |
| `TPP_GetUserInfo` | loginid INT | n/a | GetUserInfo |
| ~~`TPP_GetRoleAccess`~~ | **No longer needed (2026-11-27).** Its SQL now runs inline in GetUserRoleAccess, against `PDV_FLIH` and `MSA_URAR`; see doc 07. | n/a | GetUserRoleAccess |
| `TPP_GetImageSlider` | empid INT, locid INT | n/a | GetDashboard |
| `TPP_GetNotifications` | loginid INT, locid INT | n/a | NotificationInfo |
| `TPP_MonthAndYear` | none | n/a | AttMonYear |
| `TPP_AttHashColor` | none | n/a | AttHashColor |
| `TPP_AttInfo` | loginid INT, locid INT, attmonth VARCHAR, attyear VARCHAR | n/a | AttendanceInfo |
| `TPP_GetAttAppPending` | loginid INT, locid INT, startdate VARCHAR, enddate VARCHAR | n/a | AttendanceApprovalInfo |
| `TPP_GetLeaveBal` | loginid INT, locid INT, leavetypeid INT, startdate VARCHAR, enddate VARCHAR | n/a | GetLeaveBal |
| `TPP_GetLeaveApplied` | empid INT, locid INT, leavedate VARCHAR | `leaveappno` | LeaveAppply |
| `TPP_CheckAttExists` | empid INT, locid INT, leavedate VARCHAR, halfaday VARCHAR, halfadaytype VARCHAR | `attinfo` | LeaveAppply |
| `TPP_GetLeaveAppPending` | loginid, locid INT, startdate, enddate VARCHAR | n/a | LeaveApprovalInfo |
| `TPP_GetLeaveAppDetails` | loginid, locid INT, startdate, enddate VARCHAR | n/a | LeaveDetailsInfo |
| `TPP_GetLeaveDetails` | loginid INT, locid INT, leaveid INT | n/a | LeaveDetails |
| `TPP_GetGatePassAppPending` | loginid, locid INT, startdate, enddate VARCHAR | n/a | GatePassInfo |
| `TPP_GetGatePassAppDetails` | loginid, locid INT, startdate, enddate VARCHAR | n/a | GatePassDetailsInfo |
| `TPP_GetGatepassDetails` | loginid INT, locid INT, gatepassid INT | n/a | GatepassDetails |
| `TPP_GetCanteenName` | empid INT, locid INT | `canteenname`, `canteennameid` | GetCanteenNameList |
| `TPP_CanteenPreorderMealList` | fromdate VARCHAR, todate VARCHAR, employeeid INT, canteenid INT, loginid INT, locid INT, preorderid INT | When preorderid = 0: `preorderid` and an `itemdetails` column. PHP overwrites `itemdetails` with the JSON of the preorderid > 0 call. | CanteenPreorderMealList |
| `TPP_CanteenPreorderMeal` | preorderid INT, mode INT (0 = header, 1 = items) | mode 0: `preorderid`, `itemdetails` | GetCanteenPreorderMeal |
| `TPP_CanteenGuestMealList` | same as `TPP_CanteenPreorderMealList` | same | CanteenGuestMealList |
| `TPP_CanteenGuestMeal` | preorderid INT, mode INT | same as `TPP_CanteenPreorderMeal` | GetCanteenGuestMeal |
| `TPP_CanteenBarcode` | barcode VARCHAR, locid INT | `CPOM_CtlId`, `CPOM_EmiId`, `EMI_DpiId`, `CPOD_CmiId`, `CPOD_CraiId`, `CPOD_Amount`, `CPOM_FlihId`, `CPOM_Id`, `CPOD_Id`, `CPOD_Qty`, `CPOD_Price`, `CPOD_Discount`, `CPOD_DiscountLevel` | SaveCanteenPos |

### 2.2 Write procedures

| Procedure | Parameters, in order | Called by |
|---|---|---|
| `SMSL_Save` | **TVP** `TVP_SMSL` | SendOTP |
| `TPP_ATTStatus` | **TVP** `TVP_ATA` | ApproveAttendance |
| `TPP_LeaveApply` | **TVP** `TVP_LAP` | LeaveAppply |
| `TPP_LeaveStatus` | **TVP** `TVP_LAA` | ApproveLeave |
| `TPP_GatePassApply` | **TVP** `TVP_GPP` | GatePassApply |
| `TPP_GatePassStatus` | **TVP** `TVP_GPA` | ApproveGatePass |
| `CPW_Save` | EmiId INT, Pw VARCHAR(40). PHP truncates the password to 40 characters, as ADO.NET did with `Size = 40`. | ChangePWD |
| `TPP_MSALogSave` | psdetails VARCHAR, errormsg VARCHAR | ErrorMessageSave helper. It is not called by any action in the C# source. |
| `TPP_SaveCanteenName` | canteenid INT, canteencode, canteenname, description VARCHAR, active INT, empid INT, locid INT | SaveCanteenName |
| `TPP_SaveCanteenItem` | itemid INT, itemcode, itemname, description VARCHAR, active INT, price VARCHAR, imagepath VARCHAR, image VARCHAR (the literal `System.Byte[]` or empty), isdiscount INT, levelamt1–5 VARCHAR (decimal text), empid INT, locid INT | SaveCanteenItem |
| `TPP_SaveCanteenMenu` | CMIId INT, CMICtlId INT, CMICode, CMIName, CMIDescription VARCHAR, CMIActive INT, **TVP** `TVP_CTMCMR`, LOGINId INT, CMICliId INT | SaveCanteenMenu |
| `TPP_SaveCanteenScheduleMenu` | CMSMId, CMSMCtlId, CMSMCmiId INT, CMSMEffFrom VARCHAR (NULL when empty), CMSMEffTo VARCHAR (NULL when empty), CMSMFromTime, CMSMToTime VARCHAR, CMSMMon–CMSMSun INT ×7, **TVP** `TVP_CTMCMSD`, LOGINId INT, CMSMCliId INT | SaveScheduleCanteenMenu |
| `TPP_SaveCanteenPreorderMeal` | CPOMNo, CPOMDate VARCHAR, CPOMCtlId, CPOMEmiId, CPOMDpiId INT, CPOMBarocde (sic), CCPOMRemark VARCHAR, **TVP** `TVP_CTRCPOD`, LOGINId, CPOMCliId, CPOMFlihId INT | SaveCanteenPreorderMeal |
| `TPP_SaveCanteenGuestMeal` | as `TPP_SaveCanteenPreorderMeal` up to CCPOMRemark, then CPOMPurpose, CPOMPersonName, CPOMPersonEmail, CPOMPersonPhNo VARCHAR, **TVP** `TVP_CTRCPOD`, LOGINId, CPOMCliId, CPOMFlihId INT | SaveCanteenGuestMeal |
| `TPP_SaveCanteenPos` | **TVP** `TVP_CTRCTRS`, LOGINId INT, CTRSCliId INT | SaveCanteenPos |

**Null parameters.** Where C# passed a `SqlParameter` whose value was `null` (for example a missing `menucode`), SQL Server treated the parameter as *not supplied*. It then used the procedure's default value, or raised an error if there was none. PHP sends `NULL` instead. The MySQL procedures must treat `NULL` the way the SQL Server defaults did.

## 3. TVP JSON schemas

Column names and types are exactly those of the C# DataTables.

| Parameter | Columns: int (i), decimal (d), datetime (dt), string (s) |
|---|---|
| `TVP_SMSL` | SMSL_EmiId s, SMSL_ToPhoneNo s, SMSL_Text s, SMSL_Delivered s, SMSL_TranNo s |
| `TVP_ATA` | empid i, locid i, loginid i, attid i, compname s, status s, remarks s, appdate dt |
| `TVP_LAP` | leaveno s, leavedate dt, reqdate dt, empid i, locid i, compname s, leavetypeid i, fromdate dt, todate dt, leavereason s, halfaday s, halfadaytype s |
| `TVP_LAA` | empid i, locid i, loginid i, lapid i, ladid i, compname s, status s, remarks s, appdate dt |
| `TVP_GPP` | gatepassno s, gatepassdate dt, reqdate dt, empid i, locid i, compname s, gatepasstypeid i, fromtime dt, totime dt, gatepassreason s |
| `TVP_GPA` | empid i, locid i, loginid i, gppid i, gpdid i, compname s, status s, remarks s, appdate dt |
| `TVP_CTMCMR` | TCMR_Id i, TCMR_CmiId i, TCMR_CraiId i |
| `TVP_CTMCMSD` | TCMSD_Id i, TCMSD_CmsmId i, TCMSD_CraiId i |
| `TVP_CTRCPOD` | TCPOD_CmiId i, TCPOD_CraiId i, TCPOD_Qty i, TCPOD_Price d, TCPOD_Discount d, TCPOD_DiscountLevel i |
| `TVP_CTRCTRS` | TCTRS_CtlId i, TCTRS_EmiId i, TCTRS_DpiId i, TCTRS_CmiId i, TCTRS_CraiId i, TCTRS_DrCr s, TCTRS_Amount d, TCTRS_Remark s, TCTRS_RefFlihId i, TCTRS_CpomId i, TCTRS_CpodId i, TCTRS_Qty d, TCTRS_Price d, TCTRS_Discount d, TCTRS_DiscountLevel i, TCTRS_FlihId i, TCTRS_CliId i, TCTRS_EntryEmiId i |

`fromtime` and `totime` in `TVP_GPP`: a time-only value such as `10:30` becomes today's date plus that time, exactly as `DataTable` did (`"2026-11-27 10:30:00"`).

Example of `TVP_ATA` as sent by PHP:

```json
[{"empid":12,"locid":1000,"loginid":5,"attid":881,"compname":"WEBSRV01","status":"Approved","remarks":"ok","appdate":"2024-01-31 00:00:00"}]
```

## 4. Reading a TVP in MariaDB 10.4 (template)

```sql
DELIMITER $$
CREATE PROCEDURE TPP_ATTStatus(IN TVP_ATA LONGTEXT)
BEGIN
  DECLARE i INT DEFAULT 0;
  DECLARE n INT DEFAULT JSON_LENGTH(TVP_ATA);
  WHILE i < n DO
    SET @empid   = JSON_EXTRACT(TVP_ATA, CONCAT('$[', i, '].empid'));
    SET @attid   = JSON_EXTRACT(TVP_ATA, CONCAT('$[', i, '].attid'));
    SET @status  = JSON_UNQUOTE(JSON_EXTRACT(TVP_ATA, CONCAT('$[', i, '].status')));
    SET @remarks = JSON_UNQUOTE(JSON_EXTRACT(TVP_ATA, CONCAT('$[', i, '].remarks')));
    SET @appdate = CAST(JSON_UNQUOTE(JSON_EXTRACT(TVP_ATA, CONCAT('$[', i, '].appdate'))) AS DATETIME);
    -- original T-SQL logic of TPP_ATTStatus, ported row by row
    SET i = i + 1;
  END WHILE;
END$$
DELIMITER ;
```

`JSON_UNQUOTE(JSON_EXTRACT(...))` on a JSON `null` returns the string `'null'`. Test with `JSON_TYPE(...) = 'NULL'` where DBNull matters.

## 5. Tables, views and columns used by inline SQL in the PHP code

| Object | Status in `pravashr_kirangroup` | Used by |
|---|---|---|
| `PDV_EMI` (view) | exists, but **missing `EMI_GPSReqd` and `EMI_REmiId`** | LoginCheck, LeaveAppply, GatePassApply, ChangePWD |
| `MA_EMI` | exists, but **missing `EMI_DeviceId` and `EMI_AuthToken`** | LoginCheck, EmployeeAuthToken |
| `MSA_URD` | **missing** (`URD_Id`, `URD_DeviceId`) | LoginCheck (users with id < -1) |
| `MSA_CMD` | exists, but **missing `CMD_Status`** | EmployeeNotificationCount, NotificationInfo, PushNotifications |
| `pdv_cli`, `MSA_UAC` | exist | GetUserCompanyAccess |
| `MSA_OPT` (`OPT_FCMServerKey`, `OPT_FCMSenderId`, `OPT_FCMUrl`, `OPT_CliId`) | exists, **0 rows** | PushNotifications |
| `MSA_OPTHR` (`OPTHR_PayslipGenerateURL`) | exists; URL empty in all 7 rows | PayslipGenerated |
| `MSA_SMSS`, `MSA_SMST` | exist; `MSA_SMST` has **0 rows** | SendOTP |
| `PDV_FLIM`, `PDV_FLI`, `PDV_UAR` | exist | ByModule |
| `PDV_LAP` (`LAP_No`, `LAP_CliId`) | **missing** (`hr_lap` / `pdv_hrlap` exist) | GenerateTrNo for leaves |
| `PDV_GPP` (`GPP_No`, `GPP_CliId`) | **missing** (`hr_gpp` / `pdv_hrgpp` exist) | GenerateTrNo for gate passes |
| `PDV_EMCAN` | **missing** | GetCanteenEmployee |
| `PDV_CTMCTL`, `CTM_CTL` | **missing** | canteen names |
| `PDV_CTMCRAI`, `CTM_CRAI` | **missing** | canteen items |
| `PDV_CTMCMI`, `PDV_CTMCMR`, `CTM_CMI`, `CTM_CMR` | **missing** | canteen menus |
| `PDV_CTMCMSM`, `PDV_CTMCMSD`, `CTM_CMSM`, `CTM_CMSD` | **missing** | schedule menus |
| `PDV_CTRCPOM`, `PDV_CTRCPOD`, `PDV_CTRCTRS` | **missing** | pre-order, guest meals, POS, GenerateTrNo for canteen meals |

**Bit columns.** SQL Server `bit` columns were returned to clients as `true`/`false`. With `MANTRI_TINYINT1_AS_BOOL = true`, PHP returns `TINYINT(1)` and `BIT(1)` columns the same way. Port `bit` to one of those two types to keep the JSON identical.

**`MSA_SMST.SMST_SQLText`.** This column holds SQL text that the API executes. It must be rewritten in MySQL syntax, and it must return `EMIId`, `LoginName`, `PhoneNo`, `OTPRandom` and `IsPhoneNo`. PHP escapes the user name before substituting `{{UserName}}`. Keep the placeholder inside quotes, e.g. `WHERE EMI_LoginName = '{{UserName}}'`.

## 6. Server setting

`table_definition_cache` is **400**, but the schema has 1,104 tables and views. Prepared statements over views then fail with error 1615, "Prepared statement needs to be re-prepared". This was reproduced on `pdv_cli`.

`helpers/db_helper.php` handles it: it retries once, then runs the same statement with escaped literals. To remove the need for the fallback, raise the setting in `my.ini`:

```ini
[mysqld]
table_definition_cache = 2000
```
