> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.insurgateway.com/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://docs.insurgateway.com/_mcp/server.

# Reject Policy

POST https://testgatewayapi.insurapps.net/api/offline/jobs/{jobId}/policies/reject
Content-Type: application/json

## Reject Policy

Sigorta şirketinin, `PolicyRequested` aşamasındaki bir işin (job) poliçe talebini reddetmesini sağlar. İstek başarılı olduğunda `PolicyRejected` state geçişi tetiklenir; red nedeni işe işlenir, aynı teklifteki diğer işler yeniden aktif edilir ve ilgili taraflara bildirim e-postası gönderilir.

***

### Uç Nokta (Endpoint)

`POST {{baseUrl}}/api/offline/jobs/:jobId/policies/reject`

***

### Kullanım

Bu servis, poliçeleşme talebi karşılanamadığında kullanılır. Önerilen akış:

1. `Authentication Login` servisinden token alınır.
2. `GET /api/offline/jobs` ile `PolicyRequested` aşamasındaki işler listelenir.
3. `GET /api/offline/rejectreasons/1` ile `Policy` kategorisindeki geçerli red nedenleri çekilir. Dönen liste, token'daki sigorta şirketi için tanımlı olanlarla sınırlıdır.
4. Bu servis, seçilen `rejectReasonId` ve açıklama mesajıyla çağrılır.
5. `204 No Content` dönerse iş `PolicyRejected` aşamasına geçmiştir. Acente bu işten sonra yeniden poliçe talebinde bulunabilir (`PolicyRejected` → `PolicyRequested` geçişi tanımlıdır).

> 💡 Red nedeni listesini sabit kodlamayın: `IncludedInsuranceCompanies` / `ExcludedInsuranceCompanies` kısıtları nedeniyle geçerli nedenler sigorta şirketine göre değişir. Her zaman `rejectreasons` servisinden okuyun.

> ⚠️ İş `PolicyRequested` aşamasında değilse state machine geçişe izin vermez ve istek `400 Bad Request` / `OfflinePolicies.StateTransitionFailed` ile sonuçlanır.

***

### Kimlik Doğrulama

Bu uç nokta geçerli bir JWT erişim token'ı gerektirir. Token, `Authentication Login` servisinden alınır ve `Authorization` başlığında gönderilir.

| Başlık          | Tür    | Zorunlu | Açıklama                                   |
| --------------- | ------ | ------- | ------------------------------------------ |
| `Authorization` | string | ✅       | `Bearer <token>` biçiminde erişim token'ı. |
| `Content-Type`  | string | ✅       | `application/json` olmalıdır.              |

Token'ın `InsuranceCompanyAPIUser`, `InsuranceCompanyAPIAdmin` veya `Supervizor` rollerinden en az birini ve `Update` yetkisini taşıması gerekir. `InsuranceCompanyAPIUser` yalnızca kendi üzerine atanmış işleri reddedebilir; `InsuranceCompanyAPIAdmin` ve `Supervizor` şirket kapsamındaki tüm işleri reddedebilir.

***

### İstek Parametreleri (Path Variables)

| Parametre | Tür     | Zorunlu | Min | Max        | Açıklama                                           |
| --------- | ------- | ------- | --- | ---------- | -------------------------------------------------- |
| `jobId`   | integer | ✅       | 1   | 2147483647 | Poliçe talebi reddedilecek işin benzersiz kimliği. |

> ⚠️ `jobId` yalnızca yoldan alınır. Gövdede `jobId` göndermek etkisizdir; sunucu bu alanı her zaman yol parametresiyle ezer.

***

### İstek Gövdesi

| Parametre        | Tür     | Zorunlu | Açıklama                                                                                                                                                                                                     |
| ---------------- | ------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `message`        | string  | ✅       | Red açıklaması. Boş olamaz, en fazla 1000 karakter. Kaydedilmeden önce sunucuda HTML/script içeriğinden arındırılır.                                                                                         |
| `rejectReasonId` | integer | ✅       | Red nedeni kimliği. Sıfırdan büyük olmalı, `Policy` kategorisinde (`ReasonCategory` = 1) tanımlı olmalı ve işin sigorta şirketine kapalı olmamalıdır. Geçerli liste için `GET /api/offline/rejectreasons/1`. |
| `attachment`     | object  | —       | Reddi destekleyen PDF belge. Bkz. `PolicyFileRequest` nesnesi.                                                                                                                                               |

**`PolicyFileRequest` nesnesi** (`attachment`):

| Parametre       | Tür    | Zorunlu | Açıklama                                                                                          |
| --------------- | ------ | ------- | ------------------------------------------------------------------------------------------------- |
| `fileName`      | string | ✅       | Dosya adı. `.pdf` uzantısıyla bitmelidir.                                                         |
| `base64Content` | string | ✅       | Base64 kodlanmış dosya içeriği. Çözüldüğünde `%PDF` imzasıyla başlayan geçerli bir PDF olmalıdır. |
| `contentType`   | string | —       | Yok sayılır; sunucu içerik türünü her zaman `application/pdf` olarak atar.                        |

> ⚠️ `attachment` gönderilirse `fileName` ve `base64Content` alanlarının ikisi de zorunlu hâle gelir. Belge, işe `DocumentType = Other` tipiyle kaydedilir.

**Örnek İstek (ek belgesiz):**

```json
{
  "message": "Risk kabul kriterleri poliçe talebini karşılamamaktadır.",
  "rejectReasonId": 5
}
```

**Örnek İstek (ek belgeli):**

```json
{
  "message": "Poliçe reddi gerekçeleri ekteki belgede detaylandırılmıştır.",
  "rejectReasonId": 5,
  "attachment": {
    "fileName": "rejection_reasons.pdf",
    "base64Content": "JVBERi0xLjQKJeLjz9M..."
  }
}
```

***

### İstek Gövdesi Şeması (JSON Schema)

```json
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "title": "RejectPolicyRequest",
  "type": "object",
  "required": ["message", "rejectReasonId"],
  "properties": {
    "message": {
      "type": "string",
      "minLength": 1,
      "maxLength": 1000
    },
    "rejectReasonId": {
      "type": "integer",
      "format": "int32",
      "exclusiveMinimum": 0,
      "maximum": 2147483647,
      "$comment": "ReasonCategory = Policy olan kayıtlar. Liste: GET /api/offline/rejectreasons/1 — https://docs.insurgateway.com/offline-constants"
    },
    "attachment": { "$ref": "#/$defs/PolicyFileRequest" }
  },
  "$defs": {
    "PolicyFileRequest": {
      "type": "object",
      "required": ["fileName", "base64Content"],
      "properties": {
        "fileName": {
          "type": "string",
          "minLength": 5,
          "pattern": "(?i)\\.pdf$"
        },
        "base64Content": {
          "type": "string",
          "minLength": 1,
          "contentEncoding": "base64",
          "contentMediaType": "application/pdf",
          "$comment": "Çözüldüğünde %PDF imzasıyla başlamalıdır."
        },
        "contentType": {
          "type": ["string", "null"],
          "$comment": "Yok sayılır; sunucu application/pdf atar."
        }
      }
    }
  }
}
```

> 💡 Şemada `additionalProperties: false` bilinçli olarak yoktur: API bilinmeyen alanları yok sayar, isteği reddetmez.

***

### Başarılı Yanıt (204 No Content)

Poliçe talebi başarıyla reddedildiğinde HTTP `204 No Content` döner. **Yanıt gövdesi yoktur.**

Bu noktada sunucu tarafında gerçekleşenler:

| Tablo / Sistem | İşlem                                                                                       |
| -------------- | ------------------------------------------------------------------------------------------- |
| `Jobs`         | `CurrentStage = PolicyRejected`, `RejectReasonId` güncellenir.                              |
| `JobActions`   | `PolicyRejected` tipinde yeni aksiyon eklenir; `RequestDetails` alanına red mesajı yazılır. |
| `JobDocuments` | `attachment` gönderildiyse belge `DocumentType = Other` ile kaydedilir.                     |
| Platform       | Red aksiyonu ve red nedeni platform servisine iletilir.                                     |
| Diğer işler    | Aynı teklifteki diğer işler yeniden aktif edilir.                                           |
| E-posta        | Acente iletişimi kapalı değilse red bildirimi gönderilir.                                   |

***

### Hatalı Yanıt (400 Bad Request)

Hatalar `ApiResponse` sarmalayıcısıyla döner:

| Alan       | Tür           | Açıklama                                                                                                                               |
| ---------- | ------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
| `Status`   | boolean       | Hata durumunda her zaman `false`.                                                                                                      |
| `Code`     | string        | Hata kodu. Alan ve red nedeni doğrulamalarında `Validation.General`, state geçişi hatalarında `OfflinePolicies.StateTransitionFailed`. |
| `Message`  | string        | Hata açıklaması.                                                                                                                       |
| `Response` | array \| null | Doğrulama hatalarında `{ Field, Message }` listesi; diğer hatalarda `null`.                                                            |

**Alan doğrulama hatası:**

```json
{
  "Status": false,
  "Code": "Validation.General",
  "Message": "One or more validation errors occurred",
  "Response": [
    { "Field": "Message", "Message": "Message is required." },
    { "Field": "RejectReasonId", "Message": "RejectReasonId must be greater than zero." }
  ]
}
```

**Red nedeni doğrulama hataları** — `Response[].Field` alanında dönen kodlar:

| `Field`                                                     | Ne zaman oluşur                                         |
| ----------------------------------------------------------- | ------------------------------------------------------- |
| `JobRejectReason.RejectReasonNotFound`                      | Gönderilen `rejectReasonId` sistemde kayıtlı değil.     |
| `JobRejectReason.InvalidRejectReasonCategory`               | Red nedeni `Policy` kategorisine ait değil.             |
| `JobRejectReason.RejectReasonNotAllowedForInsuranceCompany` | Red nedeni, işin bağlı olduğu sigorta şirketine kapalı. |

```json
{
  "Status": false,
  "Code": "Validation.General",
  "Message": "One or more validation errors occurred",
  "Response": [
    {
      "Field": "JobRejectReason.InvalidRejectReasonCategory",
      "Message": "The reject reason must be in the Policy category."
    }
  ]
}
```

**State geçişi hatası** — iş `PolicyRequested` aşamasında değilse ya da red bilgisi platforma iletilemezse:

```json
{
  "Status": false,
  "Code": "OfflinePolicies.StateTransitionFailed",
  "Message": "Policy rejection failed: Aksiyon bilgileri platforma iletilemedi! Hata Mesajı: Servis yanıt vermedi.",
  "Response": null
}
```

> ⚠️ Red bilgisi platforma iletilemediğinde aksiyon geri alınır ve iş `PolicyRequested` aşamasına döndürülür; istek yeniden denenebilir.

***

### Hatalı Yanıt (401 Unauthorized)

Token gönderilmediğinde, geçersiz olduğunda veya süresi dolduğunda HTTP `401 Unauthorized` döner. **Yanıt gövdesi boştur.**

> 💡 Token'ın süresi dolduysa yanıtta `Token-Expired: true` başlığı bulunur. Bu durumda `POST /api/authentication/refreshtoken` ile yeni token alınmalıdır.

***

### Hatalı Yanıt (403 Forbidden)

| `Code`                                  | Ne zaman oluşur                                                                                  |
| --------------------------------------- | ------------------------------------------------------------------------------------------------ |
| `OfflineUsers.InsuranceCompanyNotFound` | Token'da geçerli bir sigorta şirketi ataması yok.                                                |
| `OfflineUsers.UserIdentityNotResolved`  | Token'dan kullanıcı kimliği çözümlenemedi.                                                       |
| `OfflineJobs.JobOwnershipDenied`        | `InsuranceCompanyAPIUser` rolündeki kullanıcı, kendisine ait olmayan bir işi reddetmeye çalıştı. |

```json
{
  "Status": false,
  "Code": "OfflineJobs.JobOwnershipDenied",
  "Message": "You do not have permission to access this job.",
  "Response": null
}
```

***

### Hatalı Yanıt (404 Not Found)

```json
{
  "Status": false,
  "Code": "OfflineJobs.JobNotFound",
  "Message": "No job found for the requested JobId: 999999.",
  "Response": null
}
```

***

### Hatalı Yanıt (500 Internal Server Error)

State geçişi sırasında beklenmeyen bir hata oluştuğunda `JobState.TransitionError` döner.

```json
{
  "Status": false,
  "Code": "JobState.TransitionError",
  "Message": "An unexpected error occurred during job state transition.",
  "Response": null
}
```

Reference: https://docs.insurgateway.com/insurgateway-api/offline/reject-policy

## Authentication

- `Authorization` header (bearer token, required) — Bearer authentication of the form `Bearer <token>`, where token is your auth token.

## Servers

- `https://testgatewayapi.insurapps.net` (https://testgatewayapi.insurapps.net, default)
- `https://gatewayapi.insurapps.net` (https://gatewayapi.insurapps.net)

## Request

### Path parameters

- `jobId` (integer, required) — Poliçe talebi reddedilecek işin benzersiz kimliği.

### Headers

- `Authorization` (string, optional)

## Response

### 204

No Content

## Errors

### 400 Bad Request Error

Bad Request

### 403 Forbidden Error

Forbidden

### 404 Not Found Error

Not Found

## Examples

**Request**

```json
{
  "message": "Risk kabul kriterleri poliçe talebini karşılamamaktadır.",
  "rejectReasonId": 5
}
```

**Response**

```json
""
```

**SDK Code**

```python Offline_rejectPolicy_example
import requests

url = "https://testgatewayapi.insurapps.net/api/offline/jobs/1/policies/reject"

payload = {
    "message": "Risk kabul kriterleri poliçe talebini karşılamamaktadır.",
    "rejectReasonId": 5
}
headers = {
    "Authorization": "Bearer <token>",
    "Content-Type": "application/json"
}

response = requests.post(url, json=payload, headers=headers)

print(response.json())
```

```javascript Offline_rejectPolicy_example
const url = 'https://testgatewayapi.insurapps.net/api/offline/jobs/1/policies/reject';
const options = {
  method: 'POST',
  headers: {Authorization: 'Bearer <token>', 'Content-Type': 'application/json'},
  body: '{"message":"Risk kabul kriterleri poliçe talebini karşılamamaktadır.","rejectReasonId":5}'
};

try {
  const response = await fetch(url, options);
  const data = await response.json();
  console.log(data);
} catch (error) {
  console.error(error);
}
```

```go Offline_rejectPolicy_example
package main

import (
	"fmt"
	"strings"
	"net/http"
	"io"
)

func main() {

	url := "https://testgatewayapi.insurapps.net/api/offline/jobs/1/policies/reject"

	payload := strings.NewReader("{\n  \"message\": \"Risk kabul kriterleri poliçe talebini karşılamamaktadır.\",\n  \"rejectReasonId\": 5\n}")

	req, _ := http.NewRequest("POST", url, payload)

	req.Header.Add("Authorization", "Bearer <token>")
	req.Header.Add("Content-Type", "application/json")

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := io.ReadAll(res.Body)

	fmt.Println(res)
	fmt.Println(string(body))

}
```

```ruby Offline_rejectPolicy_example
require 'uri'
require 'net/http'

url = URI("https://testgatewayapi.insurapps.net/api/offline/jobs/1/policies/reject")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true

request = Net::HTTP::Post.new(url)
request["Authorization"] = 'Bearer <token>'
request["Content-Type"] = 'application/json'
request.body = "{\n  \"message\": \"Risk kabul kriterleri poliçe talebini karşılamamaktadır.\",\n  \"rejectReasonId\": 5\n}"

response = http.request(request)
puts response.read_body
```

```java Offline_rejectPolicy_example
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

HttpResponse<String> response = Unirest.post("https://testgatewayapi.insurapps.net/api/offline/jobs/1/policies/reject")
  .header("Authorization", "Bearer <token>")
  .header("Content-Type", "application/json")
  .body("{\n  \"message\": \"Risk kabul kriterleri poliçe talebini karşılamamaktadır.\",\n  \"rejectReasonId\": 5\n}")
  .asString();
```

```php Offline_rejectPolicy_example
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://testgatewayapi.insurapps.net/api/offline/jobs/1/policies/reject', [
  'body' => '{
  "message": "Risk kabul kriterleri poliçe talebini karşılamamaktadır.",
  "rejectReasonId": 5
}',
  'headers' => [
    'Authorization' => 'Bearer <token>',
    'Content-Type' => 'application/json',
  ],
]);

echo $response->getBody();
```

```csharp Offline_rejectPolicy_example
using RestSharp;

var client = new RestClient("https://testgatewayapi.insurapps.net/api/offline/jobs/1/policies/reject");
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Bearer <token>");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n  \"message\": \"Risk kabul kriterleri poliçe talebini karşılamamaktadır.\",\n  \"rejectReasonId\": 5\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift Offline_rejectPolicy_example
import Foundation

let headers = [
  "Authorization": "Bearer <token>",
  "Content-Type": "application/json"
]
let parameters = [
  "message": "Risk kabul kriterleri poliçe talebini karşılamamaktadır.",
  "rejectReasonId": 5
] as [String : Any]

let postData = JSONSerialization.data(withJSONObject: parameters, options: [])

let request = NSMutableURLRequest(url: NSURL(string: "https://testgatewayapi.insurapps.net/api/offline/jobs/1/policies/reject")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
    print(error as Any)
  } else {
    let httpResponse = response as? HTTPURLResponse
    print(httpResponse)
  }
})

dataTask.resume()
```