# Add Parcel

### Generalità

La funzionalità **Add Parcel** da la possibilità, una volta creata la spedizione principale, di aggiungere o rimuovere colli in modo indipendente ottenendo le relative etichette.

### Lista corrieri supportati

\* vedi [note](#note-sui-corrieri)

|   CORRIERE (ID Gsped)   | AGGIUNTA COLLI | RIMOZIONE COLLI |
| :---------------------: | :------------: | :-------------: |
|        BRT\* (1)        |       Sì       |        Sì       |
|        TNT\* (2)        |       Sì       |        Sì       |
|      DPDFrance (6)      |       Si       |        Si       |
|   PDB Inviosystem (19)  |       Sì       |        Sì       |
|        Fedex (20)       |       Si       |        Si       |
|         RKS (28)        |       Si       |        Si       |
|       Dummy1 (70)       |       Sì       |        Sì       |
|       Dummy2 (71)       |       Sì       |        Sì       |
|       Dummy3 (72)       |       Sì       |        Sì       |
|       Dummy4 (73)       |       Sì       |        Sì       |
|       Dummy5 (74)       |       Sì       |        Sì       |
|       Dummy6 (75)       |       Sì       |        Sì       |
|       Dummy7 (76)       |       Sì       |        Sì       |
|       Dummy8 (77)       |       Sì       |        Sì       |
|       Dummy9 (78)       |       Sì       |        Sì       |
|       Dummy10 (79)      |       Sì       |        Sì       |
|    Italsempione (90)    |       Sì       |        Sì       |
|    Logisticando (91)    |       Sì       |        Sì       |
|    CSI Logistica (92)   |       Sì       |        Sì       |
|      Ribosped (93)      |       Sì       |        Sì       |
|    Zust - Tiesse (94)   |       Sì       |        Sì       |
|        Lynx (95)        |       Sì       |        Sì       |
|     Speditalia (97)     |       Sì       |        Sì       |
|         SVL (98)        |       Sì       |        Sì       |
|        ARCO (100)       |       Sì       |        Sì       |
|        GLS (101)        |       Sì       |        No       |
|       Fercam (131)      |       Sì       |        Sì       |
|        ALT (178)        |       Sì       |        Sì       |
|      LICCARDI (179)     |       Sì       |        Sì       |
|      DHL WLA (182)      |       Sì       |        Sì       |
| Ferrari Trasporti (190) |       Sì       |        Sì       |
|      Bracchi (191)      |       Sì       |        Sì       |
|      Sending (192)      |       Sì       |        Sì       |
|  Rhenus Logistics (193) |       Sì       |        Sì       |

{% hint style="info" %}
La lista dei corrieri abilitati è soggetta a modifiche, si prega i verificare gli aggiornamenti ad intervalli regolari
{% endhint %}

<details>

<summary>Note sui corrieri</summary>

* BRT -> solamente soluzione B2
* TNT -> solo per la stessa data di creazione etichetta e prima della data/ora ritiro della stessa. Se necessario allungare questa data consultare sezione [#data-previsto-affidamento](https://apidocs.gsped.com/shipment/corrieri/tnt#data-previsto-affidamento "mention")
* ALT e Liccardi -> comunicare a Gsped l'intenzione di effettuare chiamate di Add/Delete Parcels (richiede un cambio di configurazione)

</details>

### Logica di funzionamento processo Add Parcel

Per utilizzare nel modo corretto la funzionalità **Add Parcel** bisogna utilizzare 3 endpoint:

1. **Shipment** POST  - Per la creazione della spedizione
2. **Parcels** POST o DELETE - Per l'aggiunta o la rimozione dei colli
3. **ShipmentConfirm** POST -  Per la conferma finale della spedizione e relativa chiusura alle modifiche

{% hint style="danger" %}
ATTENZIONE: La rimozione dell'unico collo di una spedizione equivale alla cancellazione della stessa.
{% endhint %}

{% hint style="info" %}
ATTENZIONE: La conferma di una spedizione inibisce la possibilità di aggiungere o rimuover colli da una spedizione
{% endhint %}

## Aggiunta singolo collo a spedizione

<mark style="color:green;">`POST`</mark> `https://api.gsped.it/[istanza]/Parcels`

Body in JSON.\
Utilizzabile in 2 modi:\
1 - Solo con ID spedizione + dati del collo\
2 - Dati del destinatario + dati del collo

#### Request Body

| Name                                                  | Type   | Description                               |
| ----------------------------------------------------- | ------ | ----------------------------------------- |
| id\_sped<mark style="color:red;">\*</mark>            | String | ID univoco Gsped                          |
| ddt\_alpha<mark style="color:red;">\*</mark>          | String | Riferimento alfanumerico della spedizione |
| rcpt\_cap<mark style="color:red;">\*</mark>           | String | Cap destinatario                          |
| rcpt\_city<mark style="color:red;">\*</mark>          | String | Città destinatario                        |
| rcpt\_addr<mark style="color:red;">\*</mark>          | String | Indirizzo destinatario                    |
| rcpt\_name<mark style="color:red;">\*</mark>          | String | Nome destinatario                         |
| rcpt\_prov<mark style="color:red;">\*</mark>          | String | Provincia/Stato destinatario              |
| rcpt\_country\_code<mark style="color:red;">\*</mark> | String | Nazione destinatario iso code 2 char      |
| collo<mark style="color:red;">\*</mark>               | Object | [Dati del collo ](#undefined)             |

{% tabs %}
{% tab title="200: OK Collo aggiunto con successo" %}

```javascript
{
    "id_collo": 2,
    "id_sped": "123456789",
    "labels": {
        "jpg": "Stringa base64",
        "pdf": "Stringa base64",
        "zpl": "Stringa ZPL"
    },
    "tracking_collo": "JJD01111111111"
}
```

{% endtab %}

{% tab title="400: Bad Request Payload errato" %}

```javascript
{
  "error": "Dati spedizione non presenti o in formato sbagliato"
}
```

{% endtab %}

{% tab title="404: Not Found Spedizione non trovata per ID" %}

```javascript
{
  "error": "Shipment '1234' doesn't exists!"
}
```

{% endtab %}

{% tab title="404: Not Found Spedizione non trovata per dati destinatario" %}

```javascript
{
  "error": "Unable to find unique shipment by ddt and address"
}
```

{% endtab %}
{% endtabs %}

### Oggetto Collo

| Attributo     | Tipo    | Required |
| ------------- | ------- | :------: |
| peso          | integer |     X    |
| volume        | float   |     X    |
| larghezza     | integer |     X    |
| altezza       | integer |     X    |
| lunghezza     | integer |     X    |
| codice\_collo | string  |          |

### Esempio Payload Parcels POST

{% tabs %}
{% tab title="ID Spedizione" %}

```json
{
  "id_sped":"1234567",
  "collo": {
    "peso": "5",
    "volume": "0.01",
    "larghezza": "35",
    "altezza": "15",
    "lunghezza": "10",
    "codice_collo": "identificativo1234"
  }
}
```

{% endtab %}

{% tab title="Dati Destinatario" %}

```json
{
  "ddt_alpha":"test_parcel_8",
  "rcpt_name":"Rossi Gino",
  "rcpt_addr":"Via Milano 8",
  "rcpt_cap":"20123",
  "rcpt_city":"Milano",
  "rcpt_prov":"MI",
  "rcpt_country_code" : "IT",
  "collo": {
    "peso": "5",
    "volume": "0.01",
    "larghezza": "35",
    "altezza": "15",
    "lunghezza": "20",
    "codice_collo": "identificativo1234"
  }
}
```

{% endtab %}
{% endtabs %}

### Snippet codice di esempio Parcel POST

{% tabs %}
{% tab title="PHP" %}

```php
<?php

$curl = curl_init();

curl_setopt_array($curl, [
  CURLOPT_URL => "https://api.gsped.it/sandbox/Parcels",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => "{\n  \"id_sped\":\"1\",\n  \"collo\": {\n    \"peso\": \"5\",\n    \"volume\": \"0.01\",\n    \"larghezza\": \"35\",\n    \"altezza\": \"15\",\n    \"lunghezza\": \"10\"\n  }\n}",
  CURLOPT_HTTPHEADER => [
    "Content-Type: application/json",
    "x-api-key: YOUR-API-KEY"
  ],
]);

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}
```

{% endtab %}

{% tab title="Python" %}

```python
import http.client

conn = http.client.HTTPSConnection("api.gsped.it")

payload = "{\n  \"id_sped\":\"1\",\n  \"collo\": {\n    \"peso\": \"5\",\n    \"volume\": \"0.01\",\n    \"larghezza\": \"35\",\n    \"altezza\": \"15\",\n    \"lunghezza\": \"10\"\n  }\n}"

headers = {
    'Content-Type': "application/json",
    'x-api-key': "YOUR-API-KEY"
    }

conn.request("POST", "/sandbox/Parcels", payload, headers)

res = conn.getresponse()
data = res.read()

print(data.decode("utf-8"))
```

{% endtab %}

{% tab title="GO" %}

```go
package main

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

func main() {

	url := "https://api.gsped.it/sandbox/Parcels"

	payload := strings.NewReader("{\n  \"id_sped\":\"1\",\n  \"collo\": {\n    \"peso\": \"5\",\n    \"volume\": \"0.01\",\n    \"larghezza\": \"35\",\n    \"altezza\": \"15\",\n    \"lunghezza\": \"10\"\n  }\n}")

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

	req.Header.Add("Content-Type", "application/json")
	req.Header.Add("x-api-key", "YOUR-API-KEY")

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

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

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

}
```

{% endtab %}

{% tab title="C#" %}

```csharp
var client = new HttpClient();
var request = new HttpRequestMessage
{
    Method = HttpMethod.Post,
    RequestUri = new Uri("https://api.gsped.it/sandbox/Parcels"),
    Headers =
    {
        { "x-api-key", "YOUR-API-KEY" },
    },
    Content = new StringContent("{\n  \"id_sped\":\"1\",\n  \"collo\": {\n    \"peso\": \"5\",\n    \"volume\": \"0.01\",\n    \"larghezza\": \"35\",\n    \"altezza\": \"15\",\n    \"lunghezza\": \"10\"\n  }\n}")
    {
        Headers =
        {
            ContentType = new MediaTypeHeaderValue("application/json")
        }
    }
};
using (var response = await client.SendAsync(request))
{
    response.EnsureSuccessStatusCode();
    var body = await response.Content.ReadAsStringAsync();
    Console.WriteLine(body);
}
```

{% endtab %}

{% tab title="cURL" %}

```bash
curl --request POST \
  --url https://api.gsped.it/sandbox/Parcels \
  --header 'Content-Type: application/json' \
  --header 'x-api-key: YOUR-API-KEY' \
  --data '{
  "id_sped":"1",
  "collo": {
    "peso": "5",
    "volume": "0.01",
    "larghezza": "35",
    "altezza": "15",
    "lunghezza": "10"
  }
}'
```

{% endtab %}
{% endtabs %}

## Rimozione collo da spedizione

<mark style="color:red;">`DELETE`</mark> `https://api.gsped.it/[istanza]/Parcels`

Form Url-Encoded Body\
Utilizzabile in 2 modi:\
1 - Solo con ID spedizione + dati del collo\
2 - Dati del destinatario + dati del collo

#### Request Body

| Name                | Type   | Description                          |
| ------------------- | ------ | ------------------------------------ |
| id\_sped            | String | ID univoco Gsped                     |
| ddt\_alpha          | String | Riferimento alfanumerico spedizione  |
| rcpt\_name          | String | Nome destinatario                    |
| rcpt\_addr          | String | Indirizzo destinatario               |
| rcpt\_city          | String | Città destinatario                   |
| rcpt\_cap           | String | Cap destinatario                     |
| rcpt\_prov          | String | Provincia/Stato destinatario         |
| rcpt\_country\_code | String | Nazione destinatario iso code 2 char |

{% tabs %}
{% tab title="200: OK Rimozione collo avvenuta" %}

```javascript
{
    "id": "50000723",
    "num_spedizione": "7004525883",
    "num_collo": 1
}
```

{% endtab %}

{% tab title="200: OK Rimozione ultimo collo con cancellazione spedizione" %}

```javascript
{
    "result": "Shipment deleted"
}
```

{% endtab %}

{% tab title="403: Forbidden Cancellazione spedizione confermata" %}

```javascript
{
    "error" : "This shipment is already confirmed"
}
```

{% endtab %}

{% tab title="404 Spedizione non esiste con ID" %}

```javascript
{
  "error": "Shipment '1' doesn't exists!"
}
```

{% endtab %}

{% tab title="404: Not Found Spedizione non esiste con dati destinatario" %}

```javascript
{
  "error": "Unable to find unique shipment by ddt and address"
}
```

{% endtab %}
{% endtabs %}

### Snippet di codice esempio Parcels DELETE

{% tabs %}
{% tab title="PHP" %}

```php
<?php

$curl = curl_init();

curl_setopt_array($curl, [
  CURLOPT_URL => "https://api.gsped.it/sandbox/Parcels",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "DELETE",
  CURLOPT_POSTFIELDS => "id_sped=69562763",
  CURLOPT_HTTPHEADER => [
    "Content-Type: application/x-www-form-urlencoded",
    "x-api-key: YOUR-API-KEY"
  ],
]);

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}
```

{% endtab %}

{% tab title="Python" %}

```python
import http.client

conn = http.client.HTTPSConnection("api.gsped.it")

payload = "id_sped=69562763"

headers = {
    'Content-Type': "application/x-www-form-urlencoded",
    'x-api-key': "YOUR-API-KEY"
    }

conn.request("DELETE", "/sandbox/Parcels", payload, headers)

res = conn.getresponse()
data = res.read()

print(data.decode("utf-8"))
```

{% endtab %}

{% tab title="GO" %}

```go
package main

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

func main() {

	url := "https://api.gsped.it/sandbox/Parcels"

	payload := strings.NewReader("id_sped=69562763")

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

	req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
	req.Header.Add("x-api-key", "YOUR-API-KEY")

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

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

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

}
```

{% endtab %}

{% tab title="C#" %}

```csharp
var client = new HttpClient();
var request = new HttpRequestMessage
{
    Method = HttpMethod.Delete,
    RequestUri = new Uri("https://api.gsped.it/sandbox/Parcels"),
    Headers =
    {
        { "x-api-key", "YOUR-API-KEY" },
    },
    Content = new FormUrlEncodedContent(new Dictionary<string, string>
    {
        { "id_sped", "69562763" },
    }),
};
using (var response = await client.SendAsync(request))
{
    response.EnsureSuccessStatusCode();
    var body = await response.Content.ReadAsStringAsync();
    Console.WriteLine(body);
}c
```

{% endtab %}

{% tab title="cURL" %}

```bash
curl --request DELETE \
  --url https://api.gsped.it/sandbox/Parcels \
  --header 'Content-Type: application/x-www-form-urlencoded' \
  --header 'x-api-key: YOUR-API-KEY' \
  --data id_sped=69562763
```

{% endtab %}
{% endtabs %}
