# CV Digital PIC API — `/cvdigital/pic`

Manages which employees (PIC) may view CV Digital data, per company / site / dept. Every create and delete is written to an audit log.

Code: `app/routes/cvdigital.route.ts` → `app/controllers/cvDigital.controller.ts` → `app/services/cvDigitalPic.service.ts`. Request validation: `app/request/cvDigitalPic.request.js`.

| Method | Path | What it does |
| --- | --- | --- |
| `GET` | `/cvdigital/pic` | PIC list, one row per NRP |
| `GET` | `/cvdigital/pic?nrp=` | Access records of one NRP |
| `POST` | `/cvdigital/pic` | Add access records (bulk) |
| `DELETE` | `/cvdigital/pic` | Remove access records (bulk) |

## Auth

Same as the other `/cvdigital` endpoints (`personelAccess` in `app/middlewares/auth.js`):

```
Authorization: Bearer <access token from new-auth-dashboard>
```

1. Token is verified with `JWT_ACCESS_SECRET` (and `JWT_ISSUER` if set).
2. The token's NRP must be allowed to open the Personel page in dashboard-site (login enabled + gmenu / dept rules).

The token's NRP is the `action_by` in the log. A `nrp` field in the body is accepted but ignored.

| HTTP | When | Message |
| --- | --- | --- |
| 401 | No / malformed `Authorization` header | `Token tidak ditemukan` |
| 401 | Bad signature or issuer | `Token tidak valid` |
| 401 | Expired | `Token sudah kedaluwarsa` |
| 403 | User has no Personel page access | `Anda tidak memiliki akses ke resource ini` |

Auth errors use `{ "statusCode": 401, "status": "error", "message": "..." }`.

## Databases

| Name in code | Used for | Connection |
| --- | --- | --- |
| `db.sequelizeCvPic` | `cv_digital_pic`, `log_auth_cv_digital` | `ENV=DEV` → `DB_HOST_DEV`, `DB_USERNAME_DEV`, `DB_PASSWORD_DEV`. Otherwise (empty / any other value) → the normal `DB_HOST` connection. Port and database name always from `DB_PORT`, `DB_DATABASE`. |
| `db.sequelizeHoMain` | `tbl_m_personel_main` (employee name, company, position, site) | `DB_DATABASE_HO_MAIN` on `DB_HOST_HO` |

The two connections can be on different hosts, so `GET /pic` queries each one and merges the result in the API (no SQL join).

### Tables

`cv_digital_pic`

| Column | Type | Notes |
| --- | --- | --- |
| `id` | uuid | Generated by the API |
| `nrp` | string | PIC |
| `role` | string | Only `view` for now |
| `company` | string | Company id, e.g. `P01` |
| `site` | string | |
| `dept` | string | |
| `valid_until` | datetime, nullable | `NULL` = no expiry |

`log_auth_cv_digital`

| Column | Type | Notes |
| --- | --- | --- |
| `id` | uuid | `UUID()` from MySQL |
| `type` | `new` / `update` / `delete` | `update` not used yet |
| `target_id` | string | `cv_digital_pic.id` |
| `body` | JSON text | Snapshot of the record: `nrp`, `role`, `company`, `site`, `dept`, `valid_until` (no `id`, it is in `target_id`) |
| `action_at` | datetime | MySQL `NOW()` |
| `action_by` | string | NRP from the access token |

---

## `GET /cvdigital/pic`

All PICs, one row per NRP, sorted by NRP.

```bash
curl http://127.0.0.1:3012/cvdigital/pic \
  -H "Authorization: Bearer $TOKEN"
```

**200**

```json
{
  "code": 200, "status": "Ok", "message": "Successfully",
  "data": [
    { "nama": "BUDI", "nrp": "1234", "perusahaan": "PT X", "posisi": "OPERATOR", "site": "BA", "authed": 2 },
    { "nama": "", "nrp": "5678", "perusahaan": "", "posisi": "", "site": "", "authed": 1 }
  ]
}
```

| Key | Source |
| --- | --- |
| `nrp`, `authed` | `cv_digital_pic`, `authed` = number of records for the NRP (expired ones included) |
| `nama`, `perusahaan`, `posisi`, `site` | `tbl_m_personel_main` where `status_aktif = 1` |

Employee not found or not active → the NRP is still listed, with `nama`, `perusahaan`, `posisi`, `site` as `""`.

## `GET /cvdigital/pic?nrp=1234`

Access records of one NRP, sorted by company, site, dept. Unknown NRP → `data: []`.

```bash
curl "http://127.0.0.1:3012/cvdigital/pic?nrp=1234" \
  -H "Authorization: Bearer $TOKEN"
```

**200**

```json
{
  "code": 200, "status": "Ok", "message": "Successfully",
  "data": [
    { "id": "6f1c…", "nrp": "1234", "role": "view", "company": "P01", "site": "BA", "dept": "HCG", "valid_until": null, "authorized": true },
    { "id": "a9d2…", "nrp": "1234", "role": "view", "company": "P01", "site": "BA", "dept": "PLANT", "valid_until": "2026-01-31 00:00:00", "authorized": false }
  ]
}
```

| Key | Notes |
| --- | --- |
| `valid_until` | String `YYYY-MM-DD HH:mm:ss` (DB local time, no UTC conversion) or `null` |
| `authorized` | `true` if `valid_until` is `null` or not passed yet (`>= NOW()` on the DB clock), else `false` |

## `POST /cvdigital/pic`

Adds one or more access records.

```bash
curl -X POST http://127.0.0.1:3012/cvdigital/pic \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "data": [
      { "nrp": "1234", "company": "P01", "site": "BA", "dept": "HCG", "valid_until": "2026-12-31 23:59:59" },
      { "nrp": "5678", "company": "P01", "site": "BA", "dept": "PLANT" }
    ]
  }'
```

| Field | Rule |
| --- | --- |
| `nrp` | Optional, ignored (creator comes from the token) |
| `data` | Required, at least 1 item |
| `data[].nrp`, `company`, `site`, `dept` | Required strings |
| `data[].role` | Optional, only `view` (default `view`) |
| `data[].valid_until` | Optional, `YYYY-MM-DD` or `YYYY-MM-DD HH:mm:ss`, or `null`. Saved as sent |

Flow (one transaction — any error rolls back everything):

1. Reject if the same `nrp` + `company` + `site` + `dept` appears twice in `data` (409).
2. Reject if any of them already exists in `cv_digital_pic` (409). Expired records count as existing.
3. Insert all records with new UUIDs.
4. Insert one `new` log per record.

**201**

```json
{
  "code": 201, "status": "Ok", "message": "Successfully",
  "data": [
    { "id": "6f1c…", "nrp": "1234", "role": "view", "company": "P01", "site": "BA", "dept": "HCG", "valid_until": "2026-12-31 23:59:59" }
  ]
}
```

> The duplicate check runs in the API. Two requests at the same moment can still insert the same record twice. A `UNIQUE(nrp, company, site, dept)` index on `cv_digital_pic` would close this.

## `DELETE /cvdigital/pic`

Removes access records by id.

```bash
curl -X DELETE http://127.0.0.1:3012/cvdigital/pic \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{ "access": ["6f1c…", "a9d2…"] }'
```

| Field | Rule |
| --- | --- |
| `nrp` | Optional, ignored (deleter comes from the token) |
| `access` | Required, at least 1, `cv_digital_pic.id` values (UUID), no repeats |

Flow (one transaction):

1. Lock the records. Any id not found → 404, nothing deleted.
2. Insert one `delete` log per record, `body` = record as it was before deletion.
3. Delete the records.

The API does not check that the ids belong to a specific PIC.

**200**

```json
{ "code": 200, "status": "Ok", "message": "Successfully", "data": ["6f1c…", "a9d2…"] }
```

## Errors

Validation errors (body / query):

```json
{ "message": "Validation error", "errors": ["\"data[0].site\" is required"] }
```

Other errors:

```json
{ "code": 409, "status": "Error", "message": "Role sudah ada untuk: NRP 1234 (company P01, site BA, dept HCG)" }
```

| HTTP | Endpoint | When | Message |
| --- | --- | --- | --- |
| 401 / 403 | all | See [Auth](#auth) | |
| 400 | all | Body / query invalid | `Validation error` + list |
| 409 | POST | Same record twice in `data` | `Role dikirim lebih dari sekali untuk: NRP … (company …, site …, dept …)` |
| 409 | POST | Record already in table | `Role sudah ada untuk: NRP … (company …, site …, dept …)` |
| 404 | DELETE | Id not found | `Akses tidak ditemukan: <id>, <id>` |
| 500 | all | DB error (connection, unknown column, …) | Original error message |

## Env

```env
# DEV -> CV Digital PIC tables use the *_DEV connection; empty -> DB_HOST
ENV=
DB_HOST_DEV=
DB_USERNAME_DEV=
DB_PASSWORD_DEV=
```

`.env` is read once at start. Restart the server after changing it.
