# MantriAPI: C# to Core PHP Migration, Phase 1 Analysis

Source files analysed (read in full, not modified):

- `MantriAPIController.cs`: 4,433 lines, 61 API actions plus 10 public helper methods. `new 6.txt` is a byte-identical copy (same SHA-256).
- `MantirAPIModel.cs`: 683 lines, 71 classes.
- `dbConnect.php`: MySQLi, class `DbConnect`, with `connect()` (fixed DB `pdvs_client`) and `clientconnect()` (DB taken from `setclientdbdetail()`).

Target database inspected: local MariaDB **10.4.8**, schema `pravashr_kirangroup` (the only local schema containing `pdv_emi`, `ma_emi`, `msa_cmd`, `pdv_cli`). `lower_case_table_names = 1`.

---

## 1. Blocking findings

### 1.1 The database objects the C# API calls do not exist in MySQL

The C# API targets **SQL Server** through connection string `MANTRI`. None of its stored procedures or scalar functions exist in `pravashr_kirangroup`, which has 533 routines under different names (`pdhr_*`, `pdap_*`, `pdp_*`, `FnPdv*`).

| Object type | Referenced by C# | Present in MySQL |
|---|---|---|
| Stored procedures | 47 (`TPP_*`, `PDV_GetGlobalOptions`, `SMSL_Save`, `CPW_Save`); 46 are called by actions, and `TPP_MSALogSave` only by an unused helper | **0** |
| Scalar function | `[dbo].[TPF_DateFormat]` (used by 13 endpoints through `GenerateDateFormat`) | **No** (a different function, `FnPdvDateFormat`, exists) |
| Tables and views | 30 | 14 |

**Tables and views that exist:** `pdv_emi`, `ma_emi`, `pdv_cli`, `msa_uac`, `msa_cmd`, `msa_opt`, `msa_opthr`, `msa_smss`, `msa_smst` (0 rows), `msa_smsl`, `msa_log`, `pdv_fli`, `pdv_flim`, `pdv_uar`.

**Missing tables and views:**

- `PDV_LAP` (closest match: `hr_lap` / `pdv_hrlap`)
- `PDV_GPP` (closest match: `hr_gpp` / `pdv_hrgpp`)
- `MSA_URD`
- `PDV_EMCAN`
- Every canteen object: `CTM_CTL`, `CTM_CRAI`, `CTM_CMI`, `CTM_CMR`, `CTM_CMSM`, `CTM_CMSD`, `PDV_CTMCTL`, `PDV_CTMCRAI`, `PDV_CTMCMI`, `PDV_CTMCMR`, `PDV_CTMCMSM`, `PDV_CTMCMSD`, `PDV_CTRCPOM`, `PDV_CTRCPOD`, `PDV_CTRCTRS`

**Columns that are used but missing from existing tables:**

- `pdv_emi.EMI_GPSReqd`, `pdv_emi.EMI_REmiId`
- `ma_emi.EMI_DeviceId`, `ma_emi.EMI_AuthToken`
- `msa_cmd.CMD_Status` (the table has `CMD_Read` and `CMD_Send` instead)

### 1.2 SQL Server-only features with no direct MariaDB 10.4 equivalent

| Feature | Where | Notes |
|---|---|---|
| Table-valued parameters (`SqlDbType.Structured`) | 11 call sites: `TPP_ATTStatus`, `TPP_LeaveApply`, `TPP_LeaveStatus`, `TPP_GatePassApply`, `TPP_GatePassStatus`, `SMSL_Save`, `TPP_SaveCanteenMenu`, `TPP_SaveCanteenScheduleMenu`, `TPP_SaveCanteenPreorderMeal`, `TPP_SaveCanteenGuestMeal`, `TPP_SaveCanteenPos` | MySQL has no TVPs. `JSON_TABLE` would be the usual replacement, but MariaDB 10.4 lacks it (it arrived in 10.6). |
| `FOR JSON PATH`, `JSON_QUERY` | `ByModule` | MariaDB 10.4 also lacks `JSON_ARRAYAGG` (added in 10.5). The JSON must be built in PHP. |
| `TOP 1`, `Len()`, `Left()`/`Right()`, `+` string concatenation, `GetDate()`, `CAST(... AS NVARCHAR)`, `TIME(0)`, `CONVERT(VARCHAR, x, 120)`, `NUMERIC(18,2)` | Inline SQL | Mechanical translations: `LIMIT 1`, `CHAR_LENGTH`, `CONCAT`, `NOW()`/`CURDATE()`, `CAST(... AS CHAR)`, `TIME_FORMAT(x,'%H:%i')`, `DATE_FORMAT(x,'%Y-%m-%d %H:%i:%s')`, `DECIMAL(18,2)`. |
| Multiple statements in one command | `DeleteCanteenMenu`, `DeleteCanteenScheduleMenu` | Run as two prepared statements. |
| SQL stored as data | `SendOTP` runs `MSA_SMST.SMST_SQLText` | The stored text is presumably T-SQL. `msa_smst` is empty locally. |

### 1.3 Database connection

- `DbConnect::connect()` uses database `pdvs_client`, which **does not exist** on this server, and its credentials are rejected (`ERROR 1045`).
- The existing `api.php` reads data through `clientconnect()`, after looking up client details through class `Appclient`. **`appclient.php` is not in the project.**
- MantriAPI requests have no `clientid` field, so the Phase 3 rule "reuse the existing connection" does not say which database to use.

### 1.4 Security defect in the original: arbitrary SQL execution over HTTP

ASP.NET MVC exposes every **public, non-static** controller method as an action, so these helpers are routable:

| Route | Effect |
|---|---|
| `/MantriAPI/fnReturnDt?strSQL=...` | **Executes any SQL** |
| `/MantriAPI/fnReturnString?strSQL=...` | **Executes any SQL** |
| `/MantriAPI/GenerateDateFormat`, `/MantriAPI/GenerateTrNo` | Query the DB |
| `/MantriAPI/PushNotifications`, `/MantriAPI/AutoPushNotification` | Send push notifications |
| `/MantriAPI/GetTableRows`, `/MantriAPI/RandomNumber`, `/MantriAPI/Index` | Harmless |

The PHP version will keep these as **private helpers** and will not expose them. All other SQL is built by string concatenation, so it is open to injection; PHP will use prepared statements with the same values.

---

## 2. MantirAPIModel.cs analysis

### 2.1 Behaviour that applies to all request models

- Binding is done by the MVC `DefaultModelBinder` from form fields, the query string, or a JSON body (when `Content-Type: application/json`).
- An `int` or `Int32` that is missing or unparseable becomes `0`, with no error. A missing `string` becomes `null`.
- No class uses `[Required]` or other validation attributes. All validation is hand-written in the controller.
- Every request model carries `apikey` and `secretkey`. They are compared with the constants `strApiKey` and `strSecretKey` in the controller; these move to `config/api_config.php`.

### 2.2 Response models

All responses are serialized by `JavaScriptSerializer` through MVC `Json()`. Public **fields are emitted before properties**.

| Class | JSON shape, in emitted order |
|---|---|
| `dataConversiontoJson` | `ListDetails` (`[]` by default), `cpermission`, `cresponse`, `error` |
| `DashBoardDetails` | `ModuleInfo`, `OptionInfo`, `RightsInfo`, `Notifications`, `ImageSlider`, `UserInfo` (all `[]` by default), `cpermission`, `cresponse`, `error` |
| `AttMonthyearDetails` | `AttMonthyear`, `cpermission`, `cresponse`, `error` |
| `AttendanceDetails` | `AttedanceInfo` (sic), `cpermission`, `cresponse`, `error` |
| `CommonDetails` | `DataInfo`, `cpermission`, `cresponse`, `error` |

These classes are declared but never used by any action: `NameMenuObject`, `NameModuleObject`, `NavigationItem`, `SubNavigationItem`, `FlatItem`, `EmailStatusObject`, `PSObject`, `OPTObject`, `MantirAPIModel`.

`FirebaseNotificationObject` (`multicast_id`, `success`, `failure`) is used internally to read the FCM response.

### 2.3 Request models and their fields

`apikey` and `secretkey` are omitted below. Types are C# types.

| Model | Fields |
|---|---|
| EmployeeObject, LeaveTypeObject, GatePassTypeObject, CanteenNameListObject, CanteenItemListObject | empid:int, locid:int, allreq:string |
| LoginObject | username, password, device: string |
| UserCompanyAccessObject | loginid:int, roleid:int |
| SendOTPObject | username:string, locid:int |
| GlobalObject | (keys only) |
| EmployeeNotificationCountObject | loginid:int, locid:int |
| PushNotificationObject | loginid:int, startdate, enddate, title, body, urllink, bodytype: string, locid:int |
| EmployeeAuthToken | loginid:int, authtoken:string |
| ModuleObject | empid:int, locid:int |
| OptionObject | locid:int |
| UserInfoObject | loginid:int |
| UserRoleAccessObject | loginid, roleid, locid: int |
| DashboardObject | empid, locid: int |
| NotificationObject | loginid, locid, status: int |
| AttInfoObject | loginid, locid: int; attmonth, attyear: string |
| AttObject | loginid, locid: int; startdate, enddate: string |
| AttAppObject | loginid, locid: int; appdate, attappdetails: string |
| LeaveBalanceObject | loginid, locid, leavetypeid: int; startdate, enddate: string |
| LeaveApplyObject | loginid, locid, empid: int; leavedate, reqdate, leaveappdetails: string |
| LeaveAppObject | loginid, locid: int; appdate, leaveappdetails: string |
| LeaveApprovalDetailsObject | loginid, locid, leaveid: int |
| GatePassApplyObject | loginid, locid, empid: int; gpsdate, reqdate, gatepassappdetails: string |
| GatePassAppObject | loginid, locid: int; appdate, gatepassappdetails: string |
| GatepassApprovalDetailsObject | loginid, locid, gatepassid: int |
| PayslipGeneratedObject | empid:**string**, locid:int, slipmonth:string |
| CPWObject | loginid:int, oldpwd, newpwd: string |
| CanteenNameSaveObject | empid, locid, canteenid: int; canteenname, canteencode, description: string; active:int |
| CanteenNameObject, DeleteCanteenNameObject | empid, locid, canteenid: int |
| CanteenItemObject, DeleteCanteenItemObject | empid, locid, itemid: int |
| CanteenItemSaveObject | empid, locid, itemid: int; itemcode, itemname, description, price: string; image: **byte[]**; imagepath: string; isdiscount: int; levelamt1–5: decimal; active: int |
| CanteenMenuListObject | empid, locid, canteenid: int; allreq: string |
| CanteenMenuObject, DeleteCanteenMenuObject | empid, locid, canteenmenuid: int |
| CanteenMenuItemObject | empid, locid, canteenid, canteenmenuid: int |
| CanteenMenuSaveObject | empid, locid, canteenmenuid, canteenid: int; menucode, menuname, description, itemdata: string; active: int |
| CanteenScheduleMenuListObject | empid, locid, canteenid: int |
| CanteenScheduleMenuObject, DeleteCanteenScheduleMenuObject | empid, locid, scheduleid: int |
| CanteenScheduleMenuSaveObject | empid, locid, scheduleid, canteenid, canteenmenuid: int; effectivefrom, effectiveto, fromtime, totime: string; mon–sun: int; itemdata: string |
| CanteenPreorderMealSaveObject | loginid, locid, employeeid, departmentid, canteenid: int; mealdate, remark, itemdata: string; featuremenuid: int |
| CanteenPreorderMealListObject, CanteenGuestMealListObject | loginid, locid: int; fromdate, todate: string; employeeid, canteenid: int |
| CanteenPreorderMealObject, CanteenGuestMealObject | loginid, locid, preorderid: int |
| CanteenEmployeeObject | loginid, locid: int |
| CanteenGuestMealSaveObject | as CanteenPreorderMealSaveObject, plus purpose, personname, personemail, personphno: string |
| CanteenPosSaveObject | loginid, locid: int; barcode: string; featuremenuid: int |

### 2.4 Nested JSON passed inside string fields

| Field | Content | How C# reads it |
|---|---|---|
| `itemdata` | JSON array of `CanteenMenuItem` {menuitemid, canteenmenuid, itemid}, `CanteenScheduleMenuItem` {scheduleitemid, scheduleid, centeenid, itemid}, or `CanteenPreorderMealItem` {canteenmenuid, itemid, qty, price, discount, discountlevel} | `JavaScriptSerializer.Deserialize` |
| `attappdetails`, `leaveappdetails`, `gatepassappdetails` | JSON-like array text | **Not parsed as JSON.** A hand-written splitter replaces `},` with `*`, strips `[ ] { }`, splits on `*`, then on `,`, removes `"`, and splits on `:`. A value containing `,` or `:` is truncated. PHP must reproduce this splitter exactly; `json_decode` would behave differently. |

---

## 3. Response serialization contract

Every action returns HTTP 200 with `Content-Type: application/json; charset=utf-8` unless an exception escapes. When one does, ASP.NET returns **HTTP 500 with an HTML error page**.

Row lists come from `GetTableRows(DataTable)`: one object per row, keys are the SQL column aliases in column order, and values keep their CLR types.

| SQL value | C# JSON output | PHP must emit |
|---|---|---|
| int, bigint | number | number (not string) |
| decimal or numeric | number with the DB scale kept (e.g. `12.50`) | raw number text |
| bit | `true` / `false` | boolean (depends on the MySQL column type) |
| datetime or date | `"\/Date(1700000000000)\/"` (milliseconds since the epoch, UTC) | same string |
| `NULL` (`DBNull`) | **`{}`** (`JavaScriptSerializer` writes DBNull as an empty object) | `{}`, to be confirmed |
| varchar or nvarchar | string. `<`, `>`, `&`, `'` are escaped as `<` and similar; `/` and non-ASCII are not escaped | same |

---

## 4. API endpoint mapping

**Route:** `/MantriAPI/{Action}`, the MVC default `{controller}/{action}`. Matching is case-insensitive.

**HTTP column:**

- `POST` means the action has `[HttpPost]`; a GET request returns 404.
- `GET/POST` means the action has no attribute, so both methods are accepted.

**Credential check:** unless noted, a request whose `apikey` or `secretkey` does not match gets `cpermission:"notgranted"`, `cresponse:"Failure"`, `error:"Credentials not matching"`. Its list is `[]`; when the C# code built an empty typed `DataTable`, the list is still `[]` because that table has no rows.

**Success:** unless noted, `cpermission:"granted"`, `cresponse:"Success"`, `error:"Permission Granted Successfully !"`.

**MySQL column:**

- ✅ all objects exist
- ⚠️ partially exists
- ❌ the procedure or table is missing

### 4.1 Authentication, users and options

| # | Action | HTTP | Request | SQL / procedure (exact order) | Response | MySQL |
|---|---|---|---|---|---|---|
| 1 | GetEmployees | POST | EmployeeObject | `EXEC TPP_GetEmployees empid,locid`. If rows > 1 and `allreq=="Y"`, insert `{employeename:"All",employeeid:0}` at the top. | ListDetails | ❌ |
| 2 | GetLeaveType | POST | LeaveTypeObject | `EXEC TPP_GetLeaveType empid,locid`. "All" row: `leavetype:"All", leavetypeid:0, minleavedays:-1, allowexcessleave:-1`. | ListDetails | ❌ |
| 3 | GetGatePassType | POST | GatePassTypeObject | `EXEC TPP_GetGatePassType empid,locid`. "All" row: `gatepasstype, gatepasstypeid:0`. | ListDetails | ❌ |
| 4 | LoginCheck | POST | LoginObject | 1. `SELECT EMI_LoginName username, EMI_LoginPwd password, EMI_Name employeename, EMI_Id employeeid, EMI_CliId locationid, EMI_GPSReqd gpsreqd, '<strSecretKey>' accesstoken, CASE WHEN EMI_Id<-1 THEN 'User' ELSE 'Employee' END usercaption FROM PDV_EMI WHERE EMI_LoginName=? AND EMI_LoginPwd=?`<br>2. For each row: if `employeeid>0` or `==-1`, `UPDATE MA_EMI SET EMI_DeviceId=device WHERE EMI_Id=…`; otherwise `UPDATE MSA_URD SET URD_DeviceId=device WHERE URD_Id=…`.<br>3. Re-run the SELECT. 0 rows gives notgranted / `"Check Username & Password !"`. | ListDetails | ⚠️ `EMI_GPSReqd`, `EMI_DeviceId`, `MSA_URD` missing |
| 5 | GetUserCompanyAccess | POST | UserCompanyAccessObject | If `roleid==-2`: `SELECT CLI_Id Location_Id, CLI_Code Location_Code, CLI_Name Location_Name FROM pdv_cli`. Otherwise the same columns `INNER JOIN (SELECT DISTINCT UAC_CliId FROM MSA_UAC WHERE UAC_UId=loginid)`. An exception gives notgranted / Failure / exception text. | ListDetails | ✅ |
| 6 | SendOTP | GET/POST | SendOTPObject | `EXEC TPP_GetSMST locid,1`, then run the stored `SMST_SQLText` with `{{UserName}}` and `{{Location}}` replaced. Substitute `SMST_MapField` (`sms;col,...`) into `SMST_SMSText`. `SELECT * FROM MSA_SMSS WHERE SMSS_CliId=locid`. HTTP GET `URL?username=&password=&to=&from=&text=<urlencoded>&dlr-url `. On HTTP 200, call `SMSL_Save(@TVP_SMSL)`. | ListDetails = one row `{empid,response,username,phoneno,otp,message}`. Messages: `OTP Send Sucessfully`, `Phone No Does Not Exists`, `User Name Does Not Exists`, `SMS Template Does Not Exists Please Contact Admin`, `SMS Setting Error`, `SMS URL Error`, or the exception message. | ❌ |
| 7 | GetGlobalOptions | GET/POST | GlobalObject | `EXEC PDV_GetGlobalOptions` | ListDetails | ❌ |
| 8 | EmployeeNotificationCount | POST | EmployeeNotificationCountObject | `SELECT COUNT(CMD_Status) notificationcount FROM MSA_CMD WHERE CAST(GetDate() AS DATE) BETWEEN CAST(CMD_STDate AS DATE) AND CAST(CMD_EDDate AS DATE) AND CMD_Active=1 AND CMD_EmiId=loginid AND CMD_Status=0` | ListDetails | ⚠️ `CMD_Status` missing |
| 9 | PushEmployeeNotification | GET/POST | PushNotificationObject | `EXEC TPP_PushNotification loginid,'title','body','urllink','bodytype','startdate','enddate',locid`, then `PushNotifications(rows, locid)` (§5.3) | keys + messages only | ❌ |
| 10 | EmployeeAuthToken | GET/POST | EmployeeAuthToken | If `loginid>0` or `==-1`: `UPDATE MA_EMI SET EMI_AuthToken=? WHERE EMI_Id=?` | keys + messages only | ⚠️ `EMI_AuthToken` missing |
| 11 | ByModule | GET/POST | ModuleObject | **No credential check.** `EXEC TPP_GetModules empid,locid`. For each module, a `JSON_QUERY(SELECT DISTINCT FLI_Id menuid, FLI_Code menucode, FLIM_Name menuname, UAR_View viewmode, UAR_Add addmode, UAR_Edit editmode, UAR_Delete deletemode, UAR_Print printmode FROM PDV_FLIM ⋈ PDV_FLI ⋈ PDV_UAR WHERE UAR_UId=empid AND UAR_CliId=locid AND FLIM_Name='<module>' FOR JSON PATH)`. Combined into one object `FOR JSON PATH, WITHOUT_ARRAY_WRAPPER`, and all `\` are removed. With no modules, `Remove()` throws and the request returns HTTP 500. | **A JSON string literal** that contains the object | ❌ proc; FOR JSON is SQL Server-only |
| 12 | GetOption | POST | OptionObject | `EXEC TPP_GetOptionInfo locid`. An exception gives **granted / Success** with the exception text in `error`. | ListDetails | ❌ |
| 13 | GetUserInfo | POST | UserInfoObject | `EXEC TPP_GetUserInfo loginid`. Exception handling as #12. | ListDetails | ❌ |
| 14 | GetUserRoleAccess | POST | UserRoleAccessObject | `EXEC TPP_GetRoleAccess loginid,locid,roleid,0`, then for each module `EXEC TPP_GetRoleAccess loginid,locid,roleid,moduleid`. `moduleicon` and `menuicon` get the prefix `{http\|https}://{HTTP_HOST}/icons/` (left empty when blank). A `menudata` column is added holding the JSON-serialized menu rows **as a string**. Exception handling as #12. | ListDetails | ❌ |
| 15 | GetDashboard | POST | DashboardObject | `EXEC TPP_GetImageSlider empid,locid` | DashBoardDetails.ImageSlider; the other five lists are `[]` | ❌ |
| 16 | NotificationInfo | GET/POST | NotificationObject | If `status>0`: `UPDATE MSA_CMD SET CMD_Status=1 WHERE CMD_Active=1 AND CMD_Status=0 AND CMD_EmiId=loginid`. Then `EXEC TPP_GetNotifications loginid,locid`. | ListDetails | ❌ / ⚠️ |
| 33 | PayslipGenerated | GET/POST | PayslipGeneratedObject | Fails the credential check if `Convert.ToInt32(empid)==0`; a non-numeric value throws and returns HTTP 500. `SELECT OPTHR_PayslipGenerateURL PayslipGeneratedURL FROM MSA_OPTHR WHERE OPTHR_CliId=locid` (last row wins). An empty URL or no row gives notgranted / `"Please set Payslip Generated URL"`. Otherwise POST JSON `{"SMONTH":slipmonth,"EMPIds":empid,"CLIId":locid}` and put the raw response body in `payslipbase64`. | ListDetails = `[{payslipbase64}]`; error `"Payslip Generated Successfully !"` | ✅ |
| 34 | ChangePWD | POST | CPWObject | Fails the credential check if `loginid==0`. If `oldpwd` is empty or null: `SELECT … FROM PDV_EMI WHERE EMI_Id=loginid`; otherwise `… AND EMI_LoginPwd=oldpwd`. 0 rows gives notgranted / `"Check your old password"`. Otherwise `CPW_Save(@EmiId int, @Pw nvarchar(40))` and `"Password Changed Successfully !"`. ListDetails is the SELECT rows in both cases. | ListDetails | ⚠️ `CPW_Save` missing |

### 4.2 Attendance, leave and gate pass

`GenerateDateFormat(d, loc)` runs `SELECT [dbo].[TPF_DateFormat]('d', loc) AS DFormat` and returns the first row as a string.

| # | Action | HTTP | Request | SQL / procedure | Response | MySQL |
|---|---|---|---|---|---|---|
| 17 | AttMonYear | POST | GlobalObject | `EXEC TPP_MonthAndYear` | AttMonthyearDetails | ❌ |
| 18 | AttHashColor | POST | GlobalObject | `EXEC TPP_AttHashColor` | ListDetails | ❌ |
| 19 | AttendanceInfo | POST | AttInfoObject | `EXEC TPP_AttInfo loginid,locid,'attmonth','attyear'` | AttendanceDetails | ❌ |
| 20 | AttendanceApprovalInfo | POST | AttObject | `TPF_DateFormat` ×2, then `EXEC TPP_GetAttAppPending loginid,locid,'start','end'`. **Both run before the credential check, and the data is returned even when credentials fail.** | AttendanceDetails | ❌ |
| 21 | ApproveAttendance | POST | AttAppObject | Parse `attappdetails` into rows `{empid,locid,loginid,attid,compname=hostname,status,remarks,appdate=TPF_DateFormat(appdate)}`, then `TPP_ATTStatus(@TVP_ATA)`. No try/catch. | error `"Status changed Successfully."` | ❌ TVP |
| 22 | GetLeaveBal | POST | LeaveBalanceObject | `EXEC TPP_GetLeaveBal loginid,locid,leavetypeid,'start','end'` (dates formatted) | ListDetails | ❌ |
| 23 | LeaveAppply *(sic: three p's)* | POST | LeaveApplyObject | See §5.1 | error: `" Leave application not save please set Reporting Manager"`, `"Leave application X is already available"`, the `attinfo` text, or `"Saved Successfully !"` | ❌ |
| 24 | LeaveApprovalInfo | POST | AttObject | Dates are formatted before the credential check. `EXEC TPP_GetLeaveAppPending loginid,locid,'s','e'` | AttendanceDetails | ❌ |
| 25 | LeaveDetailsInfo | POST | AttObject | Dates are formatted before the credential check. `EXEC TPP_GetLeaveAppDetails loginid,locid,'s','e'` | CommonDetails | ❌ |
| 26 | LeaveDetails | POST | LeaveApprovalDetailsObject | `EXEC TPP_GetLeaveDetails loginid,locid,leaveid` | AttendanceDetails | ❌ |
| 27 | ApproveLeave | POST | LeaveAppObject | Parse into `{empid,locid,loginid,lapid,ladid,compname,status,remarks,appdate}`, then `TPP_LeaveStatus(@TVP_LAA)`, then `AutoPushNotification(locid)` | error `"Status changed Successfully !"` | ❌ TVP |
| 28 | GatePassApply | POST | GatePassApplyObject | `SELECT EMI_REmiId FROM PDV_EMI WHERE EMI_Id=empid`. 0 gives `" Gate pass not save please set Reporting Manager"`. Otherwise `GenerateTrNo(locid,"gatepassapply")` (§5.2) and build TVP rows `{gatepassno,gatepassdate,reqdate,empid,locid,compname,gatepasstypeid,fromtime,totime,gatepassreason}`. Time values rejoin one extra `:` piece. With no details, one default row is used. Then `TPP_GatePassApply(@TVP_GPP)` and AutoPush. | `"Saved Successfully !"` | ❌ |
| 29 | GatePassInfo | POST | AttObject | `EXEC TPP_GetGatePassAppPending loginid,locid,'s','e'` | AttendanceDetails | ❌ |
| 30 | GatePassDetailsInfo | POST | AttObject | Dates are formatted before the credential check. `EXEC TPP_GetGatePassAppDetails …` | CommonDetails | ❌ |
| 31 | GatepassDetails | POST | GatepassApprovalDetailsObject | `EXEC TPP_GetGatepassDetails loginid,locid,gatepassid` | AttendanceDetails | ❌ |
| 32 | ApproveGatePass | POST | GatePassAppObject | Rows `{empid,locid,loginid,gppid,gpdid,compname,status,remarks,appdate}`, then `TPP_GatePassStatus(@TVP_GPA)` and AutoPush | `"Status changed Successfully !"` | ❌ TVP |

### 4.3 Canteen

**None of the canteen tables or procedures exist in MySQL.** Endpoints marked "try/catch" return notgranted / Failure / exception text on error.

| # | Action | HTTP | Request | SQL / procedure | Response |
|---|---|---|---|---|---|
| 35 | GetCanteenNameList | POST | CanteenNameListObject | `EXEC TPP_GetCanteenName empid,locid`. "All" row: `canteenname:"All", canteennameid:0` | ListDetails |
| 36 | CanteenNameList | POST | CanteenNameListObject | `SELECT CTL_Id canteenid, CTL_Code canteencode, CTL_Name canteenname, CTL_Description description, CTL_Active active, CTL_CliId locationid FROM PDV_CTMCTL WHERE CTL_CliId=locid` | ListDetails |
| 37 | SaveCanteenName | POST | CanteenNameSaveObject | `EXEC TPP_SaveCanteenName canteenid,'code','name','desc',active,empid,locid` (try/catch) | `"Saved Successfully !"` |
| 38 | GetCanteenName | POST | CanteenNameObject | Same SELECT as #36 with `WHERE CTL_Id=canteenid` | ListDetails |
| 39 | DeleteCanteenName | POST | DeleteCanteenNameObject | `UPDATE CTM_CTL SET CTL_Deleted=1 WHERE CTL_Id=?` (try/catch) | `"Delete Successfully !"` |
| 40 | GetCanteenItemList | POST | CanteenItemListObject | `SELECT CRAI_Id itemid, CRAI_Code+'\| '+CRAI_Name itemname FROM PDV_CTMCRAI` plus the "All" row | ListDetails |
| 41 | CanteenItemList | POST | CanteenItemListObject | `SELECT CRAI_Id itemid, CRAI_Code itemcode, CRAI_Name itemname, CRAI_Description description, CRAI_Price price, CRAI_ImagePath imagepath, CRAI_Image image, CRAI_IsDiscount isdiscount, CRAI_DLevelAmt1..5 leaveamt1..5 (sic), CAST(CRAI_DLevelAmtN*100/CRAI_Price AS NUMERIC(18,2)) leavepercN FROM PDV_CTMCRAI`. Price 0: SQL Server raises divide-by-zero (HTTP 500); MySQL returns NULL. | ListDetails |
| 42 | GetCanteenItem | POST | CanteenItemObject | Same as #41 with `WHERE CRAI_Id=itemid` | ListDetails |
| 43 | SaveCanteenItem | POST | CanteenItemSaveObject | If `image` is present: write `Item_ddMMyyyyhhmmss.png` to `~/CanteenImage/` (re-encoded as PNG), and set imagepath to the **physical directory path**. Otherwise imagepath = the request `imagepath`, or `/CanteenImage/default_item.png`. Then `EXEC TPP_SaveCanteenItem itemid,'code','name','desc',active,'price','imagepath','<image>',isdiscount,'l1'..'l5',empid,locid`. **`<image>` is the literal text `System.Byte[]`** when an image is sent, and empty otherwise. (try/catch) | `"Saved Successfully !"` |
| 44 | DeleteCanteenItem | POST | DeleteCanteenItemObject | `UPDATE CTM_CRAI SET CRAI_Deleted=1 WHERE CRAI_Id=?` | `"Delete Successfully !"` |
| 45 | CanteenMenuList | POST | CanteenMenuListObject | `SELECT CMI_Id canteenmenuid, CMI_CtlId centeenid, CMI_Code canteenmenucode, CMI_Name canteenmenuname, CMI_Description description, CMI_Active active, CMI_CliId locationid FROM PDV_CTMCMI WHERE 1=1 AND CMI_CliId=locid [AND CMI_CtlId=canteenid if >0]` | ListDetails |
| 46 | GetCanteenMenu | POST | CanteenMenuObject | The #45 columns plus `'' itemdetails`, `WHERE CMI_Id=?`. For each row, `itemdetails` = a JSON string of `SELECT CMR_Id menuitemid, CMR_CmiId canteenmenuid, CMR_CraiId itemid, CRAI_Name itemname FROM PDV_CTMCMR ⋈ PDV_CTMCRAI WHERE CMR_CmiId=?` | ListDetails |
| 47 | SaveCanteenMenu | POST | CanteenMenuSaveObject | `TPP_SaveCanteenMenu(@CMIId, @CMICtlId, @CMICode, @CMIName, @CMIDescription, @CMIActive, @TVP_CTMCMR{TCMR_Id, TCMR_CmiId, TCMR_CraiId}, @LOGINId=empid, @CMICliId=locid)`. The procedure's result set is read but **discarded**. | `"Saved Successfully !"`, ListDetails `[]` |
| 48 | DeleteCanteenMenu | POST | DeleteCanteenMenuObject | `UPDATE CTM_CMI SET CMI_Deleted=1 WHERE CMI_Id=?` and `UPDATE CTM_CMR SET CMR_Deleted=1 WHERE CMR_CmiId=?` | `"Delete Successfully !"` |
| 49 | CanteenScheduleMenuList | POST | CanteenScheduleMenuListObject | `SELECT CMSM_Id scheduleid, CMSM_CtlId centeenid, CTL_Name canteenname, CMSM_CmiId canteenmenuid, CMI_Name canteenmenuname, CAST(CMSM_EffFrom AS NVARCHAR) effectivefrom, CAST(CMSM_EffTo AS NVARCHAR) effectiveto, HH:MM fromtime, HH:MM totime, CMSM_CliId locationid, weekassign` (`'Mon_'` or `'_'` … `'Sun'` or `''`) `FROM PDV_CTMCMSM LEFT JOIN PDV_CTMCTL LEFT JOIN PDV_CTMCMI WHERE CMSM_CliId=? [AND CMSM_CtlId=?]` | ListDetails |
| 50 | GetCanteenScheduleMenu | POST | CanteenScheduleMenuObject | As #49 with `mon..sun` columns and `''` itemdetails, `WHERE CMSM_Id=?`. itemdetails is filled from `PDV_CTMCMSD ⋈ PDV_CTMCRAI` (scheduleitemid, scheduleid, itemid, itemname). | ListDetails |
| 51 | SaveScheduleCanteenMenu | POST | CanteenScheduleMenuSaveObject | `TPP_SaveCanteenScheduleMenu(@CMSMId, @CMSMCtlId, @CMSMCmiId, @CMSMEffFrom (NULL if empty), @CMSMEffTo (NULL if empty), @CMSMFromTime, @CMSMToTime, @CMSMMon..@CMSMSun, @TVP_CTMCMSD{TCMSD_Id, TCMSD_CmsmId, TCMSD_CraiId}, @LOGINId, @CMSMCliId)` | `"Saved Successfully !"` |
| 52 | DeleteCanteenScheduleMenu | POST | DeleteCanteenScheduleMenuObject | `UPDATE CTM_CMSM SET CMSM_Deleted=1 …` and `UPDATE CTM_CMSD SET CMSD_Deleted=1 WHERE CMSD_CmsmId=?` | `"Delete Successfully !"` |
| 53 | GetCanteenMenuItemList | GET/POST | CanteenMenuItemObject | `SELECT CMI_Id canteenmenuid, CMR_Id menuitemid, CMR_CraiId itemid, CRAI_Name itemname, CRAI_Description description, CRAI_Price stdprice, CRAI_ImagePath imagepath, CRAI_IsDiscount isdiscount, CRAI_DLevelAmt1 discount, 0 discountlevel, CRAI_Price actualprice FROM PDV_CTMCMI ⋈ PDV_CTMCMR ⋈ PDV_CTMCRAI WHERE CMI_Id=? AND CMI_CtlId=? AND CMI_Active=1 AND CMI_CliId=?` | ListDetails |
| 54 | CanteenPreorderMealList | POST | CanteenPreorderMealListObject | `EXEC TPP_CanteenPreorderMealList 'from','to',employeeid,canteenid,loginid,locid,0`. For each row, the same call with `preorderid` gives the `itemdetails` JSON string. | ListDetails |
| 55 | GetCanteenPreorderMeal | POST | CanteenPreorderMealObject | `EXEC TPP_CanteenPreorderMeal preorderid,0`; for each row `…,1` gives `itemdetails` | ListDetails |
| 56 | SaveCanteenPreorderMeal | POST | CanteenPreorderMealSaveObject | `GenerateTrNo(locid,"canteenmeal")`. Barcode `PM`+`yyMMdd`+`rand(1..99998)` padded to 5. `TPP_SaveCanteenPreorderMeal(@CPOMNo, @CPOMDate, @CPOMCtlId, @CPOMEmiId, @CPOMDpiId, @CPOMBarocde, @CCPOMRemark (default "Applied Pre-order meal"), @TVP_CTRCPOD{TCPOD_CmiId, TCPOD_CraiId, TCPOD_Qty, TCPOD_Price, TCPOD_Discount, TCPOD_DiscountLevel}, @LOGINId, @CPOMCliId, @CPOMFlihId)` | `"Saved Successfully !"` |
| 57 | CanteenGuestMealList | POST | CanteenGuestMealListObject | As #54 with `TPP_CanteenGuestMealList` | ListDetails |
| 58 | GetCanteenGuestMeal | POST | CanteenGuestMealObject | As #55 with `TPP_CanteenGuestMeal` | ListDetails |
| 59 | GetCanteenEmployee | POST | CanteenEmployeeObject | `SELECT * FROM PDV_EMCAN WHERE EMCAN_EmiId=loginid` | ListDetails |
| 60 | SaveCanteenGuestMeal | POST | CanteenGuestMealSaveObject | As #56 with barcode `GM…` and remark default `"Applied Guest Meal Order "`, plus `@CPOMPurpose`, `@CPOMPersonName`, `@CPOMPersonEmail`, `@CPOMPersonPhNo`. Calls `TPP_SaveCanteenGuestMeal`. | `"Saved Successfully !"` |
| 61 | SaveCanteenPos | POST | CanteenPosSaveObject | `EXEC TPP_CanteenBarcode 'barcode',locid`. 0 rows gives `"Invalid QR Code Or Scan Again"`. `SELECT CONVERT(VARCHAR,CTRS_EntryDateTime,120) EntryDateTime FROM PDV_CTRCPOM ⋈ PDV_CTRCPOD ⋈ PDV_CTRCTRS WHERE CPOM_Barocde=? AND CPOM_CliId=? GROUP BY CTRS_EntryDateTime`. Any row gives `"QR Code is already scanned Log Datetime : <dt>"`. Otherwise build `@TVP_CTRCTRS` (18 columns, `DrCr='Cr'`, remark `"Appplied canteen successfully "`) and call `TPP_SaveCanteenPos(@TVP_CTRCTRS, @LOGINId, @CTRSCliId)`. | `"QR Code scanned successfully."` |

Actions #33–34 are listed in §4.1 for grouping. The numbering follows source order.

---

## 5. Behaviour that must be reproduced exactly

### 5.1 `LeaveAppply`

1. `SELECT EMI_REmiId FROM PDV_EMI WHERE EMI_Id=empid`. If the value is 0 or there is no row, return the Reporting Manager error.
2. For each detail entry, take `fromdate`, `todate`, `halfaday` and `halfadaytype`, then set `ldays = (todate − fromdate).Days + 1`.
3. Loop `ld = 0..ldays-1` with **`fromdate = fromdate.AddDays(ld)` reassigned each time**. The offsets checked are therefore cumulative (+0, +1, +3, +6, …), so some days are skipped. This is an original bug and is preserved as-is.
4. On each pass, run `EXEC TPP_GetLeaveApplied empid,locid,'d'` (keeping `leaveappno`) and `EXEC TPP_CheckAttExists empid,locid,'d','HD','HDType'` (keeping `attinfo`). A later empty result does not clear an earlier value.
5. If either value is set, return a Failure.
6. Otherwise call `GenerateTrNo(locid,"leaveapply")`, build the TVP rows `{leaveno, leavedate, reqdate, empid, locid, compname, leavetypeid, fromdate, todate, leavereason, halfaday, halfadaytype}` (or one default row), call `TPP_LeaveApply(@TVP_LAP)`, then `AutoPushNotification(locid)`.

### 5.2 `GenerateTrNo(locid, type)`

The prefix is `yy` plus a month letter (`A`=Jan … `L`=Dec). For `canteenmeal` it is `yyMMdd` instead.

The query is `SELECT TOP 1 RIGHT(No, LEN(No)-len(prefix)) TrNo FROM <PDV_LAP | PDV_CTRCPOM | PDV_GPP> WHERE <CliId>=locid AND No<>'' AND LEFT(No,len(prefix))=prefix ORDER BY LEN(No) DESC, No DESC`.

The next number is `prefix + (n+1)`, zero-padded to 5 digits, or 7 digits for `canteenmeal`. It is not concurrency-safe; the original behaviour is kept.

### 5.3 `PushNotifications(rows, locid)` and `AutoPushNotification(locid)`

- `AutoPushNotification` runs `EXEC TPP_AutoPushNotification` and passes the rows to `PushNotifications`.
- `PushNotifications` runs `SELECT OPT_FCMServerKey, OPT_FCMSenderId, OPT_FCMUrl FROM MSA_OPT WHERE OPT_CliId=locid` and reads `Rows[0]`. **With no row it throws, and the calling request returns HTTP 500 after its data was already saved.**
- For each notification row it POSTs to the FCM URL with `Authorization: key=…` and `Sender: id=…`, body `{to, priority:"high", content_available:true, data:{title, body, urllink, islink, menucode, menuname, transactionid}}`. If `success` is non-zero, it runs `UPDATE MSA_CMD SET CMD_Status=1 WHERE CMD_Id=?`.
- ⚠️ This uses the **legacy FCM HTTP API (server key)**, which Google shut down in 2024. A real call now gets an HTTP error, and in C# that becomes HTTP 500.
- `msa_opt` currently has **0 rows** locally.

### 5.4 Credential-check quirks

| Action | Behaviour |
|---|---|
| LoginCheck | The condition is `apikey≠K \|\| (secretkey≠S && (username empty \|\| password empty))`, because `&&` binds tighter than `\|\|`. A wrong secret key alone passes when username and password are supplied. |
| SendOTP | The condition is `apikey≠K && secretkey≠S`, so it fails **only when both keys are wrong**. |
| ByModule | No check at all. |

### 5.5 Error and exception contract

| Endpoints | On exception |
|---|---|
| GetUserCompanyAccess, all canteen Save and Delete endpoints | `notgranted` / `Failure` / `ex.ToString()` (includes the .NET stack trace) |
| GetOption, GetUserInfo, GetUserRoleAccess | `granted` / `Success` / `ex.ToString()` |
| SendOTP | `notgranted` / `Failure` / `ex.Message`, plus the row |
| All other endpoints | Uncaught: HTTP 500 with an HTML page |

Planned PHP behaviour:

- Keep the same JSON envelope and status codes.
- Put the exception **message** (not a stack trace) in `error`, and log full details to `logs/api_error.log`.
- For uncaught failures, return HTTP 500 with a minimal body. Showing details will be controlled by a debug flag in `config/api_config.php`, off by default.

---

## 6. Decisions taken before Phase 2 (2026-11-27)

1. **Database objects.** PHP calls the same procedure names with the same parameter order. The procedures, the function and the missing tables and columns are ported to MySQL separately; the work list is in `02_MySQL_Object_Contract.md`.
2. **Table-valued parameters.** Each one is passed as a single JSON-array `LONGTEXT` parameter in the same position.
3. **Connection.** `DbConnect::connect()` is used unchanged.
4. **NULL serialization.** `{}`, as the C# API emitted, switchable with `MANTRI_NULL_AS_EMPTY_OBJECT`.

Test results and deviations are in `03_Testing_and_Verification.md`.
