# Perusahaan API — `GET /hcga/perusahaan/main` & `POST /hcga/perusahaan`

Master company data. The HO main table (`tbl_m_perusahaan_main`) is the source of truth for company ids; each site keeps a local copy in `tbl_m_perusahaan`.

Code: `app/routes/hcga.route.js` → `app/controllers/perusahaan.controller.js` → `app/services/perusahaan.service.js`. Request validation: `app/request/perusahaan.request.js`.

## Databases

| Name in code | Database | Connection env | Table |
| --- | --- | --- | --- |
| `db.sequelizeHoMain` | `DB_DATABASE_HO_MAIN` | `DB_HOST_HO`, `DB_PORT_HO`, `DB_USERNAME_HO`, `DB_PASSWORD_HO` | `tbl_m_perusahaan_main` |
| `db.sequelizeHrga` (model `db.perusahaan`) | `DB_DATABASE` | `DB_HOST`, `DB_PORT`, `DB_USERNAME`, `DB_PASSWORD` | `tbl_m_perusahaan` |

Columns (both tables, `site` only in `tbl_m_perusahaan_main`):

| Column | Type | Notes |
| --- | --- | --- |
| `id` | string, PK | `P01`, `P02`, … generated by the API |
| `perusahaan` | string | Company name |
| `is_family` | 0 / 1 | |
| `status` | 0 / 1 | |
| `owner_unit` | string | JSON array as text, e.g. `["UNIT_A","UNIT_B"]` |
| `site` | string | HO main only, filled from `JOBSITE` in `.env` |

> `.env` is read once at start. Restart the server after changing it (`node --watch` does not reload `.env`).

---

## `GET /hcga/perusahaan/main`

List of companies from HO main. Returns only `id`, `site`, `perusahaan`, ordered by `id`. No filters, no pagination.

```bash
curl http://127.0.0.1:3012/hcga/perusahaan/main
```

**200**

```json
{
  "status": "success",
  "message": "Berhasil mengambil daftar perusahaan",
  "data": [
    { "id": "P01", "site": "HO", "perusahaan": "PT Contoh Satu" },
    { "id": "P02", "site": "MHU", "perusahaan": "PT Contoh Dua" }
  ]
}
```

---

## `POST /hcga/perusahaan`

Adds a new company to **both** `tbl_m_perusahaan_main` (HO) and `tbl_m_perusahaan` (local). Either both inserts succeed or neither is kept.

### Body (JSON)

| Field | Type | Required | Default | Rule |
| --- | --- | --- | --- | --- |
| `perusahaan` | string | yes | — | trimmed, max 255 |
| `is_family` | number | yes | — | `0` or `1` |
| `status` | number | no | `1` | `0` or `1` |
| `owner_unit` | string[] | no | `[]` | unique, non-empty strings |

Unknown fields are ignored. `id` and `site` cannot be sent; they are set by the API.

```bash
curl -X POST http://127.0.0.1:3012/hcga/perusahaan \
  -H 'Content-Type: application/json' \
  -d '{"perusahaan":"PT Contoh","is_family":1,"status":1,"owner_unit":["UNIT_A","UNIT_B"]}'
```

**201**

```json
{
  "statusCode": 201,
  "status": "success",
  "message": "Data perusahaan berhasil ditambahkan",
  "synced": false,
  "data": {
    "id": "P03",
    "perusahaan": "PT Contoh",
    "is_family": 1,
    "status": 1,
    "owner_unit": ["UNIT_A", "UNIT_B"]
  }
}
```

When the company already exists in HO main for this site but not locally, the response is still **201**, with `"synced": true` and the message `Data perusahaan sudah ada di master HO, disinkronkan ke lokal`. A new company returns `"synced": false`.

### Flow

1. Validate the body.
2. Reject if the name already exists in local `tbl_m_perusahaan` (409).
3. Open a transaction on local and on HO main.
4. Read the highest `P<number>` from `tbl_m_perusahaan_main` with `FOR UPDATE`. Parallel requests wait here, so they never get the same id.
5. Look in `tbl_m_perusahaan_main` for the same `perusahaan` **and** `site = JOBSITE`:

| HO main (same name + this site) | Action | `synced` |
| --- | --- | --- |
| Found | Copy that row (`id`, `perusahaan`, `is_family`, `status`, `owner_unit`) into local only. No new id, no HO main insert. The body's `is_family` / `status` / `owner_unit` are ignored; HO main is the source of truth. | `true` |
| Not found | New id = highest + 1, zero-padded to 2 digits (`P09` → `P10`, `P99` → `P100`, empty table → `P01`). Insert into `tbl_m_perusahaan_main` with `site = JOBSITE`, then into local. | `false` |

6. Commit HO main, then commit local. If any insert fails, both are rolled back.

The same name under a **different** site is allowed in HO main and does not count as a match; each site gets its own id.

Known gap: the two databases cannot commit atomically. If the HO main commit succeeds and the local commit then fails, the company exists only in HO main. Sending the same request again repairs it: step 5 finds the HO main row and creates the local row with the same id.

### Errors

Every response from this endpoint, success or error, carries `statusCode` in the body, equal to the HTTP status. All responses, validation included, are built in `createPerusahaan` in the controller, not by the shared `validate` middleware or the global error handler.

Validation error:

```json
{
  "statusCode": 400,
  "status": "error",
  "message": "Validation error",
  "errors": ["\"is_family\" must be one of [0, 1]"]
}
```

Other errors:

```json
{ "statusCode": 409, "status": "error", "message": "..." }
```

| `statusCode` | When | Message |
| --- | --- | --- |
| 400 | Body invalid | `Validation error` + list |
| 409 | Name already in local table | `Perusahaan "<name>" sudah terdaftar dengan id <id>` |
| 409 | Id already exists in HO main | `Gagal menyimpan perusahaan ke master HO (tbl_m_perusahaan_main): ...` |
| 502 | HO main insert failed (connection, missing column, etc.) | `Gagal menyimpan perusahaan ke master HO (tbl_m_perusahaan_main): ...` |
| 409 | Id already exists in local table (local out of sync with HO main) | `Id <id> sudah dipakai di tbl_m_perusahaan, data lokal tidak sinkron dengan master HO` |
| 500 | Any other local DB error | Original error message |

## Troubleshooting

| Symptom | Check |
| --- | --- |
| `connect ETIMEDOUT` | Restart the server first. Then test from the same terminal: `nc -vz -G 5 $DB_HOST_HO 3306`. If it connects but slowly (>10 s), MySQL is doing reverse DNS; ask the DBA for `skip-name-resolve` or add `dialectOptions: { connectTimeout: 60000 }` to `sequelizeHoMain`. |
| 502 on POST | HO main insert failed; the message contains the MySQL error (e.g. unknown column, access denied). |
| 409 "data lokal tidak sinkron" | Local `tbl_m_perusahaan` has an id that HO main does not. Sync local from HO main. |
