# Company Branch Device Policy

## Purpose

This document records how Musago distinguishes head offices and branch offices, and how devices assigned to branches should be queried.

Use this document as context when changing APIs that query company-owned or branch-assigned devices.

## Company Rules

`tblCompany.compCd` is the company code.

`tblCompany.gCompCd` is the head office company code.

- If `tblCompany.gCompCd = 9999`, the company is a head office.
- If `tblCompany.gCompCd != 9999`, the company is a branch office, and `tblCompany.gCompCd` points to the head office company code.

Example:

| compCd | gCompCd | Meaning |
| ---: | ---: | --- |
| 100 | 9999 | Company 100 is a head office. |
| 101 | 100 | Company 101 is a branch of head office 100. |

## Device Assignment Rules

`tblDevice` is used to decide where a device is assigned.

- `tblDevice.gCompCd` is the head office company code.
- `tblDevice.sCompCd` is the assigned branch company code.

A device belongs to the head office when:

- `sCompCd = 0`
- or `sCompCd = gCompCd`

A device belongs to a branch when:

- `sCompCd != 0`
- and `sCompCd != gCompCd`

Example:

| serialNo | gCompCd | sCompCd | Meaning |
| ---: | ---: | ---: | --- |
| 1004 | 100 | 0 | Device 1004 belongs to head office 100. |
| 1004 | 100 | 100 | Device 1004 belongs to head office 100. |
| 1004 | 100 | 101 | Device 1004 is assigned to branch 101. |

## DISPM Query Rule

When querying DISPM devices for a head office, the existing `tblSensor.gCompCd` query can be used.

```sql
SELECT sensorNm, serialNo AS id
FROM tblSensor
WHERE gCompCd = {compCd}
ORDER BY sensorSeq;
```

When querying DISPM devices for a branch, first select assigned devices from `tblDevice`, then join `tblSensor` by `serialNo`.

```sql
SELECT B.sensorNm, A.serialNo AS id
FROM tblDevice A
INNER JOIN tblSensor B
    ON A.serialNo = B.serialNo
WHERE A.devType = 'DISPM'
  AND A.sCompCd = {compCd}
ORDER BY B.sensorSeq;
```

For branch DISPM event queries, use `tblDevice` as the base table, filter by `devType = 'DISPM'` and `sCompCd = {compCd}`, then join the latest event data by `serialNo`.

## PHP Helper

`apiDispm.php` currently defines `get_company_branch_info($db_conn, $compCd)`.

```php
$compInfo = get_company_branch_info($db_conn, $compCd);

$bHeadCompF = $compInfo['bHeadCompF'];
$headCompCd = $compInfo['headCompCd'];
$companyGCompCd = $compInfo['companyGCompCd'];
```

Return values:

| Key | Meaning |
| --- | --- |
| `bHeadCompF` | `true` when the company is a head office. |
| `headCompCd` | The head office company code. |
| `companyGCompCd` | Raw `tblCompany.gCompCd` value. |

If this logic is needed by multiple API files, move the helper to a shared file such as `../common/libMiscFunc.php`.

## Current Usage

As of this note, the logic is used in `apiDispm.php` for:

- `list`: DISPM current/latest event list query.
- `allp-detail-pack`: DISPM device list query before per-device detail aggregation.
