# MantriAPI: employee APIs (lowercase JSON)

Three APIs were added on 2026-11-27 for creating, reading and listing employees in `ma_emi`.

The JSON uses lowercase, meaningful names that are independent of the database. The SQL always uses the real `EMI_` columns. The mapping lives in one place, `helpers/employee_mapping.php` (`MantriEmployeeMap`), and every request and response goes through it.

They follow the existing API architecture:

- **Route:** `/MantriAPI/<name>` in `helpers/route_table.php`, POST only. Any other verb returns 404.
- **Authentication:** the existing `apikey`/`secretkey` check.
- **Database:** `DbConnect::connect()` from `dbConnect.php`, with prepared statements only.
- **Response:** the existing envelope `ListDetails`, `cpermission`, `cresponse`, `error`.
- **Errors:** handled as in the master data APIs. A database or unexpected error returns `notgranted` / `Failure` with a generic message, and the details are logged.

## 1. saveemployee

**Request.** `employee` is a nested object, sent as an object in a JSON body or as a JSON string in a form field. `loginid` is optional; it is the user recorded in the audit columns.

```json
{ "apikey": "…", "secretkey": "…", "loginid": 1,
  "employee": { "employeeid": 0, "employeecode": "110094", "employeename": "KOLI RAJSHEKHAR HANMANT", "dateofbirth": "1977-06-01", "locationid": -9, "mobileno": null, "issameaddress": 1 } }
```

| `employeeid` | Action |
|---|---|
| `0` (or omitted) | `INSERT INTO ma_emi`, with only the supplied columns. `employeecode` and `employeename` are required. The API also sets: `EMI_TCode = employeecode` (the convention in 809 of 812 existing rows); `EMI_Active = 1` unless `isactive` is sent (all existing rows are active); `EMI_Deleted = 0`; `EMI_EntryEmiId = loginid`; `EMI_EntryDatetime = NOW()`; `EMI_EntryComputer = server host name`. |
| `> 0` | `UPDATE ma_emi … WHERE EMI_Id = ? AND EMI_Deleted = 0`. **Only the fields present in the request are updated.** A field sent as `null` is set to NULL; a field that is absent is left unchanged. `EMI_Id` and `EMI_TCode` are never updated. `EMI_LastEntryEmiId`, `EMI_LastEntryDatetime` and `EMI_LastEntryComputer` are set. An unknown or deleted id returns `Employee not found.`. |

**Success response:**

```json
{"ListDetails":[{"employeeid":813}],"cpermission":"granted","cresponse":"Success","error":"Saved Successfully !"}
```

**Validation.** A failed check returns `notgranted` / `Failure` with one of the messages below. Nothing is written.

| Check | `error` |
|---|---|
| A property that is not a mapped lowercase name, including database names such as `EMI_Name` or mixed case such as `EmployeeName` | `Unknown employee field(s): …` |
| Integer fields | `Invalid value for <field>. Expected an integer.` |
| Dates must be `yyyy-MM-dd` and a real calendar date | `Invalid value for <field>. Expected a date in yyyy-MM-dd format.` |
| 0/1 fields | `Invalid value for <field>. Expected 0 or 1.` |
| Text longer than the varchar size. MariaDB runs here without strict mode and would otherwise truncate silently. | `<field> exceeds the maximum length of N characters.` |
| Insert without a name, or a blank name on update | `employeename is required.` |
| Insert without a code | `employeecode is required.` |
| `isactive: null` on update (`EMI_Active` is NOT NULL) | `isactive cannot be null.` |
| No `employee` object | `employee object is required.` |

**Fields ignored on save.** Read-only fields and master names (`departmentname`, …) are silently ignored. A client can therefore post back an object it received from GetEmployeeDetails.

## 2. GetEmployeeDetails

**Request:**

```json
{ "apikey": "…", "secretkey": "…", "locationid": 1002, "employeeid": 1 }
```

**Query.** It uses an explicit column list from the mapping instead of `SELECT *`, so the password, auth tokens and photo blob are never read. The eight master names are added with `LEFT JOIN`s, and the conditions are `WHERE EMI_Id = ? AND EMI_Id > 0 AND EMI_Deleted = 0 AND EMI_CliId = ?`.

**Location authorization.** This uses the existing rules from `pdhr_getemilist` and `pdv_emi`. The employee must belong to the requested location (an exact `EMI_CliId` match, with no roll-up to the parent location), must not be deleted, and must not be a system user (`EMI_Id <= 0`). If any of these fails, the response is `granted` with `ListDetails: []`. This is the convention for single-record endpoints, and it also means the API does not reveal that the employee exists elsewhere.

**Response.** One employee object in `ListDetails`, with 115 fields plus 8 master names. Real local data, truncated:

```json
{"ListDetails":[{"employeeid":1,"employeecode":"300001","prefix":"mr","employeename":"VISHAL SHAHAJI MADANE","fathername":"SHAHAJI","mothername":"RAJJAKKA","gender":"M","dateofbirth":"2000-01-17","bloodgroupid":null,"bloodgroupname":null,"phoneno":null,"mobileno":"9834283537","emailid":null, …,"departmentid":1,"departmentname":"FOUNDRY SHOP", …,"locationid":1002, …}],"cpermission":"granted","cresponse":"Success","error":"Permission Granted Successfully !"}
```

**Value types:**

| Database value | JSON value |
|---|---|
| NULL | `null` |
| integer | number |
| bit | `0` / `1` |
| date | `"yyyy-MM-dd"` |
| decimal | number |
| text | string |

These three APIs return NULL as `null`, as their specification requires. The older endpoints still return `{}` (see doc 03).

## 3. GetEmployeeLists

**Request.** For every filter, `0` means "no filter". `caetgoryid` is accepted as a legacy spelling of `categoryid`; it is used only when `categoryid` is 0.

```json
{ "apikey": "…", "secretkey": "…", "locationid": -9, "departmentid": 0, "categoryid": 0, "designationid": 0, "employeeid": 0 }
```

**Query.** The SQL from the specification, plus the existing employee rules `e.EMI_Id > 0 AND e.EMI_Deleted = 0` and `ORDER BY e.EMI_Id` so the order is stable. Each filter that is not 0 adds a condition:

- `locationid` → `e.EMI_CliId = ?`
- `departmentid` → `e.EMI_DpiId = ?`
- `categoryid` → `e.EMI_EciId = ?`
- `designationid` → `e.EMI_EmdId = ?`
- `employeeid` → `e.EMI_Id = ?`

Negative location ids such as `-9` are filtered normally.

**Response.** Real local data, truncated:

```json
{"ListDetails":[{"employeeid":123,"employeecode":"SLM10003","employeename":"VIDYA KAMBLE","departmentname":"MURGUD","categoryname":"GHODAWAT RETAIL PRIVATE LIMITED (M)","designationname":"Default","dateofjoining":null}, …],"cpermission":"granted","cresponse":"Success","error":"Permission Granted Successfully !"}
```

## 4. Field mapping (generated from `helpers/employee_mapping.php`)

**Read-only fields.** These are returned but never written by `saveemployee`:

- `employeeroleid` (`EMI_EriId`: Super Admin / Admin / HOD / Operator) and `isadmin`. These are privilege fields, and the API is protected only by a shared key.
- `rejoiningid`, a link to `ma_emrjn` records managed elsewhere.

**Never exposed:**

- `EMI_TCode` (set internally)
- `EMI_LoginName`, `EMI_LoginPwd`
- `EMI_Photo` (base64 blob; use `photopath`)
- `EMI_MAuthToken`, `EMI_MTokenDateTime`, `EMI_WAuthToken`, `EMI_WTokenDateTime`
- `EMI_IsApproved`, `EMI_AEmiId`, `EMI_ADatetime`
- `EMI_Entry*`, `EMI_LastEntry*` (set by the API)
- `EMI_Deleted`

**Names inferred from the master tables.** Most names follow the abbreviation directly. These were worked out from the related tables, and you may want to rename them:

| JSON name | Column | Derived from |
|---|---|---|
| `payrollcycleid` | `EMI_PcmId` | `msa_hrpcm`, which has a pay start and end day |
| `leavepolicyid` | `EMI_LpmId` | `msa_hrlpm` |
| `attendancepolicyid` | `EMI_AtpmId` | `msa_hrapm` |
| `shiftrosterid` | `EMI_ShrId` | `ma_shr` / `ma_shrd`, which has dates |
| `regionid` | `EMI_CrgiId` | `ma_crgi` ("South") |
| `paygradeid` | `EMI_PGriId` | **least certain**: a second grade reference |
| `confirmationduedate` | `EMI_DOCEXP` | not used by any procedure |

| JSON property | MySQL column | Type | Mode |
|---|---|---|---|
| `employeeid` | `EMI_Id` | integer | key, never written |
| `employeecode` | `EMI_Code` | string(100) | read/write |
| `prefix` | `EMI_Prefix` | string(10) | read/write |
| `employeename` | `EMI_Name` | string(200) | read/write |
| `fathername` | `EMI_FatherName` | string(100) | read/write |
| `mothername` | `EMI_MotherName` | string(100) | read/write |
| `gender` | `EMI_Gender` | string(1) | read/write |
| `dateofbirth` | `EMI_DOB` | date `yyyy-MM-dd` | read/write |
| `bloodgroupid` | `EMI_BldId` | integer | read/write |
| `bloodgroupname` | join: `ma_bld.BLD_Name` | string | read-only |
| `phoneno` | `EMI_PhNo` | string(20) | read/write |
| `mobileno` | `EMI_MobileNo` | string(20) | read/write |
| `emailid` | `EMI_CEMailId` | string(100) | read/write |
| `personalemailid` | `EMI_PEMailId` | string(100) | read/write |
| `officialmobileno` | `EMI_CMobileNo` | string(25) | read/write |
| `nationality` | `EMI_Nationality` | string(100) | read/write |
| `maritalstatusid` | `EMI_MarsId` | integer | read/write |
| `spousename` | `EMI_SpouseName` | string(100) | read/write |
| `dateofanniversary` | `EMI_DOA` | date `yyyy-MM-dd` | read/write |
| `noofchildren` | `EMI_NoOfChild` | integer | read/write |
| `disabilityid` | `EMI_DiabId` | integer | read/write |
| `disabilitypercentage` | `EMI_DiabPerc` | integer | read/write |
| `religionid` | `EMI_ReginId` | integer | read/write |
| `aadharno` | `EMI_AadharNo` | string(50) | read/write |
| `panno` | `EMI_PanNo` | string(50) | read/write |
| `contactpersonname` | `EMI_ContactPName` | string(100) | read/write |
| `contactmobileno` | `EMI_ContactMobileNo` | string(25) | read/write |
| `contactpersonrelation` | `EMI_ContactPRelation` | string(100) | read/write |
| `dateofjoining` | `EMI_DOJ` | date `yyyy-MM-dd` | read/write |
| `departmentid` | `EMI_DpiId` | integer | read/write |
| `departmentname` | join: `ma_dpi.DPI_Name` | string | read-only |
| `subdepartmentid` | `EMI_SubDpiId` | integer | read/write |
| `categoryid` | `EMI_EciId` | integer | read/write |
| `categoryname` | join: `ma_eci.ECI_Name` | string | read-only |
| `subcategoryid` | `EMI_SubEciId` | integer | read/write |
| `designationid` | `EMI_EmdId` | integer | read/write |
| `designationname` | join: `ma_emd.EMD_Name` | string | read-only |
| `locationid` | `EMI_CliId` | integer | read/write |
| `parentlocationid` | `EMI_PCliId` | integer | read/write |
| `payrolllocationid` | `EMI_PRCliId` | integer | read/write |
| `currentcountryid` | `EMI_CACoiId` | integer | read/write |
| `currentcountryname` | join: `ma_coi.COI_Name` | string | read-only |
| `currentstateid` | `EMI_CAStiId` | integer | read/write |
| `currentstatename` | join: `ma_sti.STI_Name` | string | read-only |
| `currentaddress` | `EMI_CAddress` | string(200) | read/write |
| `currentaddress1` | `EMI_CAddress1` | string(200) | read/write |
| `currentaddress2` | `EMI_CAddress2` | string(200) | read/write |
| `currentcity` | `EMI_CCity` | string(100) | read/write |
| `currentpincode` | `EMI_CPincode` | string(100) | read/write |
| `issameaddress` | `EMI_IsCAddressSameAsPAddress` | 0/1 | read/write |
| `permanentcountryid` | `EMI_PACoiId` | integer | read/write |
| `permanentcountryname` | join: `ma_coi.COI_Name` | string | read-only |
| `permanentstateid` | `EMI_PAStiId` | integer | read/write |
| `permanentstatename` | join: `ma_sti.STI_Name` | string | read-only |
| `permanentaddress` | `EMI_PAddress` | string(200) | read/write |
| `permanentaddress1` | `EMI_PAddress1` | string(200) | read/write |
| `permanentaddress2` | `EMI_PAddress2` | string(200) | read/write |
| `permanentcity` | `EMI_PCity` | string(500) | read/write |
| `permanentpincode` | `EMI_PPincode` | string(100) | read/write |
| `esicnumber` | `EMI_ESICNumber` | string(100) | read/write |
| `uanno` | `EMI_UANNo` | string(100) | read/write |
| `epfnumber` | `EMI_EPFNumber` | string(100) | read/write |
| `devicecode` | `EMI_DeviceCode` | string(100) | read/write |
| `employeetypeid` | `EMI_EmitId` | integer | read/write |
| `dateofconfirmation` | `EMI_DOC` | date `yyyy-MM-dd` | read/write |
| `confirmationduedate` | `EMI_DOCEXP` | date `yyyy-MM-dd` | read/write |
| `isresigned` | `EMI_IsResigned` | 0/1 | read/write |
| `dateofresignation` | `EMI_DOR` | date `yyyy-MM-dd` | read/write |
| `resignationreason` | `EMI_RReason` | string(100) | read/write |
| `rejoiningid` | `EMI_EmrjnId` | integer | **read-only** |
| `gradeid` | `EMI_GriId` | integer | read/write |
| `paygradeid` | `EMI_PGriId` | integer | read/write |
| `costcenterid` | `EMI_CciId` | integer | read/write |
| `profitcenterid` | `EMI_PrcId` | integer | read/write |
| `reportingmanagerid` | `EMI_RMEmiId` | integer | read/write |
| `hodid` | `EMI_HODEmiId` | integer | read/write |
| `regionid` | `EMI_CrgiId` | integer | read/write |
| `employeeroleid` | `EMI_EriId` | integer | **read-only** |
| `shiftgroupid` | `EMI_ShgmId` | integer | read/write |
| `shiftrosterid` | `EMI_ShrId` | integer | read/write |
| `weeklyoffpatternid` | `EMI_WopmId` | integer | read/write |
| `noticeperiod` | `EMI_NoticePeriod` | integer | read/write |
| `attendancetypeid` | `EMI_AttdtId` | integer | read/write |
| `isextrawork` | `EMI_IsExtraWork` | 0/1 | read/write |
| `otrate` | `EMI_OTRate` | number | read/write |
| `isreportingmanager` | `EMI_IsRM` | 0/1 | read/write |
| `ishod` | `EMI_IsHOD` | 0/1 | read/write |
| `isadmin` | `EMI_IsAdmin` | 0/1 | **read-only** |
| `previousexperienceyears` | `EMI_PreviousExpYear` | integer | read/write |
| `previousexperiencemonths` | `EMI_PreviousExpMonth` | integer | read/write |
| `currentexperienceyears` | `EMI_CurrentExpYear` | integer | read/write |
| `currentexperiencemonths` | `EMI_CurrentExpMonth` | integer | read/write |
| `totalexperienceyears` | `EMI_TotalExpYear` | integer | read/write |
| `totalexperiencemonths` | `EMI_TotalExpMonth` | integer | read/write |
| `epfjoiningdate` | `EMI_EPFJoiningDate` | date `yyyy-MM-dd` | read/write |
| `epfleavingdate` | `EMI_EPFLeavingDate` | date `yyyy-MM-dd` | read/write |
| `epfclosurereason` | `EMI_EPFClosureReason` | string(200) | read/write |
| `esicjoiningdate` | `EMI_ESICJoiningDate` | date `yyyy-MM-dd` | read/write |
| `esicleavingdate` | `EMI_ESICLeavingDate` | date `yyyy-MM-dd` | read/write |
| `esicclosurereason` | `EMI_ESICClosureReason` | string(200) | read/write |
| `vpfnumber` | `EMI_VPFNumber` | string(100) | read/write |
| `vpfjoiningdate` | `EMI_VPFJoiningDate` | date `yyyy-MM-dd` | read/write |
| `vpfleavingdate` | `EMI_VPFLeavingDate` | date `yyyy-MM-dd` | read/write |
| `vpfclosurereason` | `EMI_VPFClosureReason` | string(200) | read/write |
| `deductvpf` | `EMI_DeductVPF` | 0/1 | read/write |
| `vpfamount` | `EMI_VPFAmount` | number | read/write |
| `vpfpercentage` | `EMI_VPFPercentage` | number | read/write |
| `gratuitynumber` | `EMI_GratuityNumber` | string(100) | read/write |
| `taxregime` | `EMI_TaxRegime` | string(10) | read/write |
| `employeegroupid` | `EMI_EGrpId` | integer | read/write |
| `paymentmodeid` | `EMI_MopId` | integer | read/write |
| `bankname` | `EMI_BankName` | string(200) | read/write |
| `bankbranch` | `EMI_BankBranch` | string(100) | read/write |
| `ifsccode` | `EMI_IFSCCode` | string(50) | read/write |
| `accountno` | `EMI_AccountNo` | string(50) | read/write |
| `photopath` | `EMI_Photopath` | string(500) | read/write |
| `isactive` | `EMI_Active` | 0/1 | read/write |
| `isnightallowanceapplicable` | `EMI_IsApplicableNightAllowance` | integer | read/write |
| `overtimeformulaid` | `EMI_OtfmId` | integer | read/write |
| `payrollcycleid` | `EMI_PcmId` | integer | read/write |
| `nightallowancerate` | `EMI_NightAllowanceRate` | number | read/write |
| `attendancepolicyid` | `EMI_AtpmId` | integer | read/write |
| `leavepolicyid` | `EMI_LpmId` | integer | read/write |

## 5. Test results (2026-11-27, local XAMPP, `pravashr_kirangroup`)

**Overall:** 70 / 70 employee tests pass, and every earlier suite still passes. `ma_emi` is unchanged after testing: 812 rows, max id 811.

**How the writes were tested.** Insert and update ran through the real controller code **inside one database transaction that was rolled back**. The only lasting side effect is that the InnoDB `AUTO_INCREMENT` counter moved forward, so the next real employee id will skip a few numbers.

**How the reads were tested.** Read requests, and save requests that fail validation before any SQL runs, went through Apache with the real `DbConnect::connect()`.

| # | Requirement | Result |
|---|---|---|
| 1 | Insert with lowercase fields | Pass. The example request was inserted and a numeric `employeeid` returned. |
| 2 | Update with lowercase fields | Pass. Only the supplied columns changed (`EMI_Name`, `EMI_DpiId`, `EMI_MobileNo`, `EMI_AadharNo` set to NULL). DOB, ESIC, address and TCode were untouched. The last-entry audit columns were set, and no second row was created. |
| 3 | Details by lowercase request | Pass. All 30 example fields round-tripped with identical values and JSON types. A real employee matched `ma_emi`. |
| 4 | Lists by lowercase request | Pass. Location 1000 returned 340 rows, equal to a direct SQL count. |
| 5 | All response properties lowercase | Pass. 123 details properties; the list keys are exactly the 7 specified. Every data key in every response collected is lowercase. |
| 6 | Values saved in the correct EMI columns | Pass. 36 columns were checked directly in the table, including `EMI_TCode = EMI_Code`, `EMI_Active = 1` and the entry audit columns. |
| 7 | NULL handling | Pass. NULL is stored as NULL and returned as `null`, never `{}` or `""`. |
| 8 | Zero and negative location ids | Pass. `locationid` 0 lists all 730/731 non-deleted employees; `-9` filters normally. |
| 9 | Optional filters | Pass for department, category, legacy `caetgoryid` (same result as `categoryid`), designation (a non-matching value gives `[]`) and employeeid. |
| 10 | Authentication failures | Pass, all 3 APIs. An invalid apikey or secretkey gives `notgranted` / `Credentials not matching`; GET gives 404. |
| 11 | Location authorization | Pass. Other locations, deleted employees and the system user `-1` all return `[]`. |
| 12 | Existing APIs keep working | Pass. Unit 45/45, migration HTTP 29/29, master data 66/66, route sweep 70/70 (61 migrated, 6 master, 3 employee). The 5 short master-data aliases you removed now return 404. |

**Additional checks:**

- **Validation:** 13 cases pass, including database column names and mixed-case names being rejected, invalid and impossible dates, over-long text, a missing name or code, an unknown or negative id, and a null `isactive`. None of them wrote anything.
- **Read-only fields:** `isadmin` and `employeeroleid` sent in a save are ignored.
- **Database failure:** all 3 APIs return the generic `Failure` envelope.
- **Final verification:** no `EMI_`, `DPI_`, `ECI_` or `EMD_` names appear in any response. The only place a column name can appear is the `Unknown employee field(s)` message, which echoes the client's own invalid input.
