Skip to content

Commit

Permalink
Add exceptions, Parse address, Update API version from 3 to 4, Add IB…
Browse files Browse the repository at this point in the history
…AN for Split TVA, Change errors logics
  • Loading branch information
Alex Stoica committed Jun 1, 2019
1 parent dc55d7a commit 831419d
Show file tree
Hide file tree
Showing 8 changed files with 220 additions and 58 deletions.
59 changes: 49 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
# API ANAF
Librarie PHP pentru verificarea gratuita a contribuabililor care sunt inregistrati conform art. 316 din Codul Fiscal

Data care pot fi obtinute:
Date care pot fi obtinute:
- Denumire/Adresa companie
- Platitor/Neplatitor TVA
- Platitor TVA la incasare
- Platitor Split TVA
- IBAN Split TVA
- Data inregistrare TVA
- Status Societate (Activa/Inactiva)
- etc.
- Data radiere

:heart: Daca iti este de folos te rog sa oferi o stea :star:

Expand All @@ -19,18 +20,56 @@ composer require itrack/anaf

- Initializare librarie

$anaf = new \Itrack\Anaf\Client(); <br><br>
```php
$anaf = new \Itrack\Anaf\Client();
```

- Pentru a verifica doar un cui urmati foloseste metoda $anaf->addCui(CUI VALOARE INTEGER, "DATA VERIFICARE") conform exemplului de mai jos:
### Pentru a verifica doar un CUI foloseste metoda

$anaf->addCui(123456, "2017-12-31"); <br>
print_r($anaf->getResults());<br><br>
```php
$cui = "123456";
$dataVerificare = "YYYY-MM-DD";
$anaf->addCui($cui, $dataVerificare);
```

- Pentru a verifica mai multe CUI-uri in acelasi timp foloseste metoda $anaf->addCui(CUI VALOARE INTEGER, "DATA VERIFICARE") de mai multe ori:

$anaf->addCui(123456, "2017-12-31"); <br>
$anaf->addCui(654321, "2017-11-24"); <br>
print_r($anaf->getResults());
#### Conform exemplului de mai jos:

```php
$cui = "123456";
$dataVerificare = "2019-05-20";
$anaf->addCui($cui, $dataVerificare);
$raspuns = $anaf->getOneResult();
```

### Pentru a verifica mai multe CUI-uri in acelasi timp foloseste urmeaza exemplul de mai jos:

```php
$anaf->addCui("123456", "2019-05-20");
$anaf->addCui("RO654321"); // Daca data nu este setata, valoarea default va fi data de azi
$raspuns = $anaf->getResults();

// SAU

$cuis = [
"123456",
"RO6543221"
];
$anaf->addCui($cuis, "2019-05-20");
$raspuns = $anaf->getResults();
```

# Limite
Poti solicita raspuns pentru maxim 500 de CUI-uri simultan cu o rata de 1 request / secunda.

# Tratarea exceptiilor
Din versiunea 2.0.0 am adaugat exceptii pentru tratarea erorilor, pentru a nu afecta mediile de productie te rog sa tratezi aceste exceptii prin try -> catch

Exceptii:

* Itrack\Anaf\Exceptions\LimitExceeded - Ai depasit limita de 500 de CUI-uri / request;
* Itrack\Anaf\Exceptions\ResponseFailed - Raspunsul primit de la ANAF nu este in format JSON, exceptia returneaza body-ul raspunsului pentru a fi verificat manual;
* Itrack\Anaf\Exceptions\RequestFailed - Raspunsul primit de la ANAF nu are status de succes, verifica manual raspunsul primit in exceptie.

# Linkuri utile
https://blog.turma.ro/api-anaf/ <br>
Expand Down
1 change: 1 addition & 0 deletions composer.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
{
"name": "itrack/anaf",
"type": "library",
"version": "2.0.0",
"description": "API ANAF pentru verificarea contribuabililor care sunt inregistrati conform art. 316 din Codul Fiscal",
"authors": [{
"name": "Alex Stoica",
Expand Down
69 changes: 66 additions & 3 deletions example.php
Original file line number Diff line number Diff line change
@@ -1,7 +1,70 @@
<?php
include("vendor/autoload.php");

// Gather data about more CUI's
$anaf = new \Itrack\Anaf\Client();
$anaf->addCui(123456, "2017-12-31");
$anaf->addCui(654321, "2017-11-24");
print_r($anaf->getResults());

$anaf->addCui(123456, "2019-05-31");
$anaf->addCui("RO16826034");

print_r($anaf->getResults());

// Gather data about more CUI's using an array
$anaf = new \Itrack\Anaf\Client();

$cuis = [
"RO123456",
"123456",
123456
];
$anaf->addCui($cuis);

print_r($anaf->getResults());

// Gather data about one CUI
$anaf = new \Itrack\Anaf\Client();

$anaf->addCui("14080700");

print_r($anaf->getOneResult());

/*
Output example:
stdClass Object
(
[cui] => 14080700
[data] => 2019-06-01
[denumire] => REALITATEA MEDIA SA
[adresa] => stdClass Object
(
[raw] => MUNICIPIUL BUCUREŞTI, SECTOR 1, ŞOS. BUCUREŞTI-PLOIEŞTI, NR.172-176, BL.CORP A, ET.3, AP.CAMERA 5
[judet] => Municipiul Bucureşti
[localitate] => Sector 1
[strada] => Şos. Bucureşti-Ploieşti
[numar] => 172-176
[altele] => Bl.corp A, Et.3, Ap.camera 5
)
[scpTVA] => 1
[data_inceput_ScpTVA] => 2001-08-01
[data_sfarsit_ScpTVA] =>
[data_anul_imp_ScpTVA] =>
[mesaj_ScpTVA] => platitor IN SCOPURI de TVA la data cautata
[dataInceputTvaInc] =>
[dataSfarsitTvaInc] =>
[dataActualizareTvaInc] =>
[dataPublicareTvaInc] =>
[tipActTvaInc] =>
[statusTvaIncasare] =>
[dataInactivare] =>
[dataReactivare] =>
[dataPublicare] =>
[dataRadiere] =>
[statusInactivi] =>
[dataInceputSplitTVA] => 2018-03-01
[dataAnulareSplitTVA] =>
[statusSplitTVA] => 1
[iban] => RO53TREZ701505001XXXXTVA
)
*/
Binary file added response.PNG
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
137 changes: 92 additions & 45 deletions src/Client.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@
namespace Itrack\Anaf;

/**
* Implementare API V3 ANAF
* https://webservicesp.anaf.ro/PlatitorTvaRest/api/v3/
* Implementare API V4 ANAF
* https://webservicesp.anaf.ro/PlatitorTvaRest/api/v4/
*/
class Client
{
Expand All @@ -15,7 +15,7 @@ class Client
/**
* @var string
*/
protected $apiUri = 'https://webservicesp.anaf.ro/PlatitorTvaRest/api/v3/ws/tva';
protected $apiUri = 'https://webservicesp.anaf.ro/PlatitorTvaRest/api/v4/ws/tva';

/**
* CUI List
Expand All @@ -25,51 +25,77 @@ class Client
protected $cuis = [];

/**
* @var array
*/
protected $errors = [];

/**
* Add cui to list
* Add more or one cui to list
*
* @param $cui
* @param $fiscals
* @param null $date
* @return $this
*/
public function addCui($cui, $date = null)
public function addCui($fiscals, $date = null)
{

// If not have set date return today
if(is_null($date)) {
$date = date('Y-m-d');
}

// Limit maxim numbers of cuis
if(count($this->cuis) >= self::ANAF_CUI_LIMIT) {
$this->errors = "You have exceeded the large number of cui's allowed!";
return $this;

if(!is_array($fiscals)) {
$fiscals = [$fiscals];
}

// Normalization
$cui = preg_replace('/\D/', '', $cui);
foreach($fiscals as $cui) {
// Keep only numbers from CUI
$cui = preg_replace('/\D/', '', $cui);

// Add cui to list
$this->cuis[] = [
"cui" => $cui,
"data" => $date
];
// Add cui to list
$this->cuis[] = [
"cui" => $cui,
"data" => $date
];
}

return $this;
}


/**
* Get results of request
*
* @return bool|object
* @return array
*/
public function getResults()
{
$results = $this->callApi();
foreach($results as $company) {
$company->adresa = $this->parseAddress($company->adresa);
}

return $results;
}

/**
* Get first result
*
* @return object
*/
public function getOneResult()
{
$company = $this->callApi()[0];
$company->adresa = $this->parseAddress($company->adresa);

return $company;
}

/**
* Call ANAF API
*
* @return array
*/
private function callApi()
{
// Limit maxim numbers of cuis
if(count($this->cuis) >= self::ANAF_CUI_LIMIT) {
throw new Exceptions\LimitExceeded('Poti verifica simultam pana la 500 de CUI-uri.');
}

// Make request
$curl = curl_init();
curl_setopt_array($curl, array(
Expand All @@ -90,45 +116,66 @@ public function getResults()

// Check http code
if (!isset($info['http_code']) || $info['http_code'] !== 200) {
$this->errors = "Response status: {$info['http_code']} | Response body: {$response}";
return false;
throw new Exceptions\ResponseFailed("Response status: {$info['http_code']} | Response body: {$response}");
}

// Get items
$items = json_decode($response);

// Check if have json because ANAF return errors in plain text
if(json_last_error() !== JSON_ERROR_NONE) {
$this->errors = "Json parse error | Response body: {$response}";
return false;
throw new Exceptions\ResponseFailed("Json parse error | Response body: {$response}");
}

// Check success stats
if ("SUCCESS" !== $items->message || 200 !== $items->cod) {
$this->errors = "Response message: {$items->message} | Response body: {$response}";
return false;
}

// Return first item if don't more items
if(count($items->found) == 1) {
return $items->found[0];
throw new Exceptions\RequestFailed("Response message: {$items->message} | Response body: {$response}");
}

return $items->found;
}

/**
* Return errors if exist of false if all is OK
* Parse company address
*
* @return array|bool
* @return object
*/
public function getErrors()
private function parseAddress($raw)
{
if(empty($this->errors)) {
return false;
// Check if raw is empty
if(empty($raw)) {
return $raw;
}

return $this->errors;
}
// Normal case from all uppercase
$rawText = mb_convert_case($raw, MB_CASE_TITLE, 'UTF-8');

// Parse address
$list = array_map('trim', explode(",", $rawText, 5));
list($judet, $localitate, $strada, $numar, $altele) = array_pad($list, 5, '');

// Parse county
$judet = trim(str_replace('Jud.', '', $judet));

// Parse city
$localitate = trim(str_replace(['Mun.', 'Orş.'], ['', 'Oraş'], $localitate));

// Parse street
$strada = trim(str_replace('Str.', '', $strada));

}
// Parse number
$numar = trim(str_replace('Nr.', '', $numar));

// New object for address
$address = new \stdClass;

$address->raw = $raw;
$address->judet = $judet;
$address->localitate = $localitate;
$address->strada = $strada;
$address->numar = $numar;
$address->altele = $altele;

return $address;
}
}
4 changes: 4 additions & 0 deletions src/Exceptions/LimitExceeded.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
<?php
namespace Itrack\Anaf\Exceptions;

class LimitExceeded extends \Exception {}
4 changes: 4 additions & 0 deletions src/Exceptions/RequestFailed.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
<?php
namespace Itrack\Anaf\Exceptions;

class RequestFailed extends \Exception {}
4 changes: 4 additions & 0 deletions src/Exceptions/ResponseFailed.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
<?php
namespace Itrack\Anaf\Exceptions;

class ResponseFailed extends \Exception {}

0 comments on commit 831419d

Please sign in to comment.