# CareFix helpdesk integration

For whoever configures Caresoft's helpdesk (Freshdesk, Zoho Desk, osTicket, an in-house tool, or anything that can call an API).

## 1. Create a CareFix ticket from the helpdesk

```
POST https://<carefix-server>/api/integrations/tickets
X-CareFix-Integration-Key: <InboundKey>
Content-Type: application/json

{
  "hospitalCode": "PUN-017",
  "externalRef": "HD-22871",
  "raisedBy": "anita.patil",
  "title": "Pan 40 issued twice on IPD 8871",
  "issueText": "UHID 240518 IPD 8871: Pan 40 issued twice on 14 Sep from main pharmacy, bill shows double."
}
```

- `hospitalCode` is the code shown under **Hospitals** in CareFix.
- `raisedBy` is the engineer's CareFix username. They must be assigned to that hospital.
- `externalRef` is the helpdesk ticket number. Sending the same reference again returns the existing ticket instead of creating a duplicate.

Response:

```json
{ "ticketId": 41, "ticketNo": "CF-000041", "created": true }
```

The AI starts diagnosing immediately.

## 2. Check a ticket's status

```
GET https://<carefix-server>/api/integrations/tickets?hospitalCode=PUN-017&externalRef=HD-22871
X-CareFix-Integration-Key: <InboundKey>
```

## 3. Receive status changes

When `WebhookUrl` is set, CareFix posts every state change of a linked ticket:

```json
{
  "event": "ticket.updated",
  "ticketNo": "CF-000041",
  "externalRef": "HD-22871",
  "hospitalCode": "PUN-017",
  "state": "Verified",
  "risk": "High",
  "fixSummary": "Cancel duplicate Pan 40 issue line 118904 and reduce IPD bill 77431 totals by ₹186.",
  "closeNote": null,
  "updatedAt": "2026-09-22T05:41:00Z"
}
```

States: `New`, `Diagnosing`, `NeedsInfo`, `FixProposed`, `Approved`, `Executed`, `Verified`, `RolledBack`, `Closed`.

Headers:
- `X-CareFix-Signature: sha256=<hex>` is the HMAC-SHA256 of the raw body using `WebhookSecret`. Reject requests where it doesn't match.
- `X-CareFix-Delivery: <id>` is unique per event. Use it to ignore repeats.

Reply with any 2xx status. Failed deliveries are retried with growing gaps (up to 4 hours apart) for about a day.

Signature check (C#):

```csharp
var expected = "sha256=" + Convert.ToHexString(
    HMACSHA256.HashData(Encoding.UTF8.GetBytes(secret), rawBodyBytes)).ToLowerInvariant();
bool valid = CryptographicOperations.FixedTimeEquals(
    Encoding.UTF8.GetBytes(expected), Encoding.UTF8.GetBytes(signatureHeader));
```

Signature check (PHP):

```php
$expected = 'sha256=' . hash_hmac('sha256', file_get_contents('php://input'), $secret);
$valid = hash_equals($expected, $_SERVER['HTTP_X_CAREFIX_SIGNATURE'] ?? '');
```

## Suggested helpdesk rules

- When a ticket is tagged "database" and has a hospital code, call step 1.
- On `NeedsInfo`, add an internal note so the engineer knows the AI is waiting for them.
- On `Verified` or `Closed`, add the fix summary to the ticket and move it to "Resolved".
