# Sucursales

> Facture desde otros lugares además del domicilio fiscal del emisor: cada sucursal con su código postal, su dirección en el PDF y sus series.

Un emisor factura desde su domicilio fiscal (la **Matriz**) y, si tiene más lugares, desde sus sucursales. El CFDI solo lleva el código postal del lugar (`LugarExpedicion`), así que cada sucursal tiene el suyo, y de él dependen también la hora de la `Fecha` (Cancún, Tijuana y Hermosillo no tienen la de la Ciudad de México) y el IVA 8 % de la franja fronteriza. Su dirección va en el PDF y, si se las da, sus facturas llevan sus propias series. Son las mismas de **Ajustes › Sucursales** en la app.

## Crear una sucursal

```bash tab="cURL"
curl https://api.fiscalisto.com/v1/branches \
  -H "Authorization: Bearer $FISCALISTO_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Sucursal Monterrey",
    "zip": "64000",
    "address": { "street": "Av. Constitución", "exterior": "1500", "neighborhood": "Centro", "city": "Monterrey" },
    "phone": "81 1234 5678",
    "series": { "invoice": "MTY" }
  }'
```

```ts tab="TypeScript"
import { Fiscalisto } from "fiscalisto";

// La llave viene de FISCALISTO_API_KEY.
const fiscalisto = new Fiscalisto();

const branch = await fiscalisto.branches.create({
  name: "Sucursal Monterrey",
  zip: "64000",
  address: {
    street: "Av. Constitución",
    exterior: "1500",
    neighborhood: "Centro",
    city: "Monterrey",
  },
  phone: "81 1234 5678",
  series: { invoice: "MTY" },
});
```

```python tab="Python"
from fiscalisto import Fiscalisto

# La llave viene de FISCALISTO_API_KEY.
fiscalisto = Fiscalisto()

branch = fiscalisto.branches.create({
    "name": "Sucursal Monterrey",
    "zip": "64000",
    "address": {
        "street": "Av. Constitución",
        "exterior": "1500",
        "neighborhood": "Centro",
        "city": "Monterrey",
    },
    "phone": "81 1234 5678",
    "series": {"invoice": "MTY"},
})
```

```php tab="PHP"
<?php

use Fiscalisto\Fiscalisto;

// La llave viene de FISCALISTO_API_KEY.
$fiscalisto = new Fiscalisto();

$branch = $fiscalisto->branches->create([
    'name' => 'Sucursal Monterrey',
    'zip' => '64000',
    'address' => [
        'street' => 'Av. Constitución',
        'exterior' => '1500',
        'neighborhood' => 'Centro',
        'city' => 'Monterrey',
    ],
    'phone' => '81 1234 5678',
    'series' => ['invoice' => 'MTY'],
]);
```

```go tab="Go"
package main

import (
	"context"
	"fmt"
	"log"

	fiscalisto "fiscalisto.com/go"
)

func main() {
	// La llave viene de FISCALISTO_API_KEY.
	client, err := fiscalisto.NewClient("")
	if err != nil {
		log.Fatal(err)
	}
	ctx := context.Background()

	branch, err := client.Branches.Create(ctx, &fiscalisto.CreateBranchParams{
		Name: "Sucursal Monterrey",
		Zip:  "64000",
		Address: &fiscalisto.CreateBranchParamsAddress{
			Street:       fiscalisto.String("Av. Constitución"),
			Exterior:     fiscalisto.String("1500"),
			Neighborhood: fiscalisto.String("Centro"),
			City:         fiscalisto.String("Monterrey"),
		},
		Phone: fiscalisto.String("81 1234 5678"),
		Series: &fiscalisto.CreateBranchParamsSeries{
			Invoice: fiscalisto.String("MTY"),
		},
	})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(branch.ID)
}
```

```java tab="Java"
import com.fiscalisto.FiscalistoClient;
import com.fiscalisto.model.CreateBranchParams;
import com.fiscalisto.model.CreateBranchParamsAddress;
import com.fiscalisto.model.CreateBranchParamsSeries;

// La llave viene de FISCALISTO_API_KEY.
var fiscalisto = new FiscalistoClient();

var branch = fiscalisto.branches().create(new CreateBranchParams()
        .setName("Sucursal Monterrey")
        .setZip("64000")
        .setAddress(new CreateBranchParamsAddress()
                .setStreet("Av. Constitución")
                .setExterior("1500")
                .setNeighborhood("Centro")
                .setCity("Monterrey"))
        .setPhone("81 1234 5678")
        .setSeries(new CreateBranchParamsSeries().setInvoice("MTY")));
System.out.println(branch.getId());
```

```csharp tab="C#"
using Fiscalisto;

// La llave viene de FISCALISTO_API_KEY.
var fiscalisto = new FiscalistoClient();

var branch = await fiscalisto.Branches.CreateAsync(new CreateBranchParams
{
    Name = "Sucursal Monterrey",
    Zip = "64000",
    Address = new()
    {
        Street = "Av. Constitución",
        Exterior = "1500",
        Neighborhood = "Centro",
        City = "Monterrey",
    },
    Phone = "81 1234 5678",
    Series = new() { Invoice = "MTY" },
});
```

Contesta la sucursal (`brn_…`), con `state` tomado de su código postal si no lo manda. Cada código postal es de una sola sucursal (otro igual contesta `branch_exists`, y dice cuál) y el del domicilio fiscal del emisor no es sucursal: es la Matriz. Hasta 200 por emisor.

`series` tiene una serie por tipo de CFDI: `invoice` (facturas, tipo I), `credit_note` (notas de crédito, tipo E), `payment` (complementos de pago, tipo P) y `transfer` (traslados, tipo T). La que no da usa la del emisor.

## Facturar desde ella

Mande `branch` en la factura:

```bash tab="cURL"
curl https://api.fiscalisto.com/v1/invoices \
  -H "Authorization: Bearer $FISCALISTO_API_KEY" \
  -H "Idempotency-Key: pedido-1042" \
  -H "Content-Type: application/json" \
  -d '{
    "branch": "brn_OufpKqnrvx9p3",
    "customer": { "tax_id": "URE180429TM6", "legal_name": "UNIVERSIDAD ROBOTICA ESPAÑOLA", "tax_system": "601", "zip": "86991" },
    "payment_form": "03",
    "items": [{ "description": "Consultoría", "product_key": "80101500", "unit_price": 1000 }]
  }'
```

```ts tab="TypeScript"
import { Fiscalisto } from "fiscalisto";

// La llave viene de FISCALISTO_API_KEY.
const fiscalisto = new Fiscalisto();

const invoice = await fiscalisto.invoices.create({
  branch: "brn_OufpKqnrvx9p3",
  customer: {
    tax_id: "URE180429TM6",
    legal_name: "UNIVERSIDAD ROBOTICA ESPAÑOLA",
    tax_system: "601",
    zip: "86991",
  },
  payment_form: "03",
  items: [
    {
      description: "Consultoría",
      product_key: "80101500",
      unit_price: 1000,
    },
  ],
}, { idempotencyKey: "pedido-1042" });
```

```python tab="Python"
from fiscalisto import Fiscalisto

# La llave viene de FISCALISTO_API_KEY.
fiscalisto = Fiscalisto()

invoice = fiscalisto.invoices.create({
    "branch": "brn_OufpKqnrvx9p3",
    "customer": {
        "tax_id": "URE180429TM6",
        "legal_name": "UNIVERSIDAD ROBOTICA ESPAÑOLA",
        "tax_system": "601",
        "zip": "86991",
    },
    "payment_form": "03",
    "items": [
        {
            "description": "Consultoría",
            "product_key": "80101500",
            "unit_price": 1000,
        },
    ],
}, idempotency_key="pedido-1042")
```

```php tab="PHP"
<?php

use Fiscalisto\Fiscalisto;

// La llave viene de FISCALISTO_API_KEY.
$fiscalisto = new Fiscalisto();

$invoice = $fiscalisto->invoices->create([
    'branch' => 'brn_OufpKqnrvx9p3',
    'customer' => [
        'tax_id' => 'URE180429TM6',
        'legal_name' => 'UNIVERSIDAD ROBOTICA ESPAÑOLA',
        'tax_system' => '601',
        'zip' => '86991',
    ],
    'payment_form' => '03',
    'items' => [
        [
            'description' => 'Consultoría',
            'product_key' => '80101500',
            'unit_price' => 1000,
        ],
    ],
], ['idempotency_key' => 'pedido-1042']);
```

```go tab="Go"
package main

import (
	"context"
	"fmt"
	"log"

	fiscalisto "fiscalisto.com/go"
)

func main() {
	// La llave viene de FISCALISTO_API_KEY.
	client, err := fiscalisto.NewClient("")
	if err != nil {
		log.Fatal(err)
	}
	ctx := context.Background()

	invoice, err := client.Invoices.Create(ctx, &fiscalisto.InvoiceCreate{
		Branch: fiscalisto.String("brn_OufpKqnrvx9p3"),
		Customer: fiscalisto.ObjectOf(fiscalisto.InvoiceCreateCustomer{
			TaxID:     "URE180429TM6",
			LegalName: "UNIVERSIDAD ROBOTICA ESPAÑOLA",
			TaxSystem: "601",
			Zip:       "86991",
		}),
		PaymentForm: fiscalisto.String("03"),
		Items: []fiscalisto.InvoiceCreateItem{
			{
				Description: fiscalisto.String("Consultoría"),
				ProductKey:  fiscalisto.String("80101500"),
				UnitPrice:   fiscalisto.Float64(1000),
			},
		},
	}, fiscalisto.WithIdempotencyKey("pedido-1042"))
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(invoice.ID)
}
```

```java tab="Java"
import com.fiscalisto.FiscalistoClient;
import com.fiscalisto.RequestOptions;
import com.fiscalisto.model.InvoiceCreate;
import com.fiscalisto.model.InvoiceCreateCustomer;
import com.fiscalisto.model.InvoiceCreateItem;
import java.util.List;

// La llave viene de FISCALISTO_API_KEY.
var fiscalisto = new FiscalistoClient();

var invoice = fiscalisto.invoices().create(new InvoiceCreate()
        .setBranch("brn_OufpKqnrvx9p3")
        .setCustomer(new InvoiceCreateCustomer()
                .setTaxId("URE180429TM6")
                .setLegalName("UNIVERSIDAD ROBOTICA ESPAÑOLA")
                .setTaxSystem("601")
                .setZip("86991"))
        .setPaymentForm("03")
        .setItems(List.of(
                new InvoiceCreateItem()
                        .setDescription("Consultoría")
                        .setProductKey("80101500")
                        .setUnitPrice(1000)
        )), RequestOptions.idempotencyKey("pedido-1042"));
System.out.println(invoice.getId());
```

```csharp tab="C#"
using Fiscalisto;

// La llave viene de FISCALISTO_API_KEY.
var fiscalisto = new FiscalistoClient();

var invoice = await fiscalisto.Invoices.CreateAsync(new InvoiceCreate
{
    Branch = "brn_OufpKqnrvx9p3",
    Customer = new InvoiceCreateCustomer
    {
        TaxId = "URE180429TM6",
        LegalName = "UNIVERSIDAD ROBOTICA ESPAÑOLA",
        TaxSystem = "601",
        Zip = "86991",
    },
    PaymentForm = "03",
    Items = new()
    {
        new()
        {
            Description = "Consultoría",
            ProductKey = "80101500",
            UnitPrice = 1000,
        },
    },
}, new RequestOptions { IdempotencyKey = "pedido-1042" });
```

La factura sale con `LugarExpedicion="64000"`, la serie `MTY` y la dirección de la sucursal en el PDF, y su objeto dice `branch: "brn_OufpKqnrvx9p3"`. Sin `branch`, sale de la Matriz (`branch: null`). Sus complementos de pago y notas de crédito siguen solos a la sucursal de la factura: no hace falta mandarla otra vez. `branch` también va en cada factura de un lote y en las facturas recurrentes.

La `Fecha` es la hora de la sucursal: una factura de su sucursal de Cancún a las 11:30 pm del 31 en la Ciudad de México ya es del día 1 a las 12:30 am.

## Cambiarla, archivarla o borrarla

`POST /v1/branches/{id}` cambia solo lo que manda; una serie en `null` vuelve a la del emisor. Una sucursal que ya facturó no cambia de código postal (sus facturas se reconocen por él): si se mudó, archívela y cree otra.

```bash tab="cURL"
curl https://api.fiscalisto.com/v1/branches/brn_OufpKqnrvx9p3 \
  -H "Authorization: Bearer $FISCALISTO_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "archived": true }'
```

```ts tab="TypeScript"
import { Fiscalisto } from "fiscalisto";

// La llave viene de FISCALISTO_API_KEY.
const fiscalisto = new Fiscalisto();

const branch = await fiscalisto.branches.update("brn_OufpKqnrvx9p3", { archived: true });
```

```python tab="Python"
from fiscalisto import Fiscalisto

# La llave viene de FISCALISTO_API_KEY.
fiscalisto = Fiscalisto()

branch = fiscalisto.branches.update("brn_OufpKqnrvx9p3", {"archived": True})
```

```php tab="PHP"
<?php

use Fiscalisto\Fiscalisto;

// La llave viene de FISCALISTO_API_KEY.
$fiscalisto = new Fiscalisto();

$branch = $fiscalisto->branches->update('brn_OufpKqnrvx9p3', ['archived' => true]);
```

```go tab="Go"
package main

import (
	"context"
	"fmt"
	"log"

	fiscalisto "fiscalisto.com/go"
)

func main() {
	// La llave viene de FISCALISTO_API_KEY.
	client, err := fiscalisto.NewClient("")
	if err != nil {
		log.Fatal(err)
	}
	ctx := context.Background()

	branch, err := client.Branches.Update(ctx, "brn_OufpKqnrvx9p3", &fiscalisto.UpdateBranchParams{
		Archived: fiscalisto.Bool(true),
	})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(branch.ID)
}
```

```java tab="Java"
import com.fiscalisto.FiscalistoClient;
import com.fiscalisto.model.UpdateBranchParams;

// La llave viene de FISCALISTO_API_KEY.
var fiscalisto = new FiscalistoClient();

var branch = fiscalisto.branches().update("brn_OufpKqnrvx9p3", new UpdateBranchParams().setArchived(true));
System.out.println(branch.getId());
```

```csharp tab="C#"
using Fiscalisto;

// La llave viene de FISCALISTO_API_KEY.
var fiscalisto = new FiscalistoClient();

var branch = await fiscalisto.Branches.UpdateAsync("brn_OufpKqnrvx9p3", new UpdateBranchParams { Archived = true });
```

Archivada, ya no se factura desde ella (una factura con su `branch` se rechaza) y sus facturas la siguen nombrando; `"archived": false` la restaura. `DELETE /v1/branches/{id}` borra solo una que nunca facturó; con facturas contesta `branch_has_invoices`.

`GET /v1/branches` las lista, las más recientes primero, sin las archivadas salvo con `include_archived=true`; `zip=64000` deja la de ese código postal.
