* updated to koin api v2

This commit is contained in:
Danyi Dávid 2019-05-13 21:34:09 +02:00
parent f875b915e9
commit 7006443669

View File

@ -11,6 +11,7 @@ use Doctrine\ORM\ORMException;
use GuzzleHttp\Client; use GuzzleHttp\Client;
use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ResponseInterface;
use Zend\EventManager\Event; use Zend\EventManager\Event;
use Zend\Json\Json;
class KoinService class KoinService
{ {
@ -40,21 +41,6 @@ class KoinService
/** @var EntityManager */ /** @var EntityManager */
private $entityManager; private $entityManager;
/** @var string */
private $accountId;
/** @var string */
private $csrfParam;
/** @var string */
private $csrfToken;
/** @var array */
private $expenseCategories = [];
/** @var array */
private $incomeCategories = [];
public function __construct(Client $httpClient, array $config, EntityManager $em) public function __construct(Client $httpClient, array $config, EntityManager $em)
{ {
@ -355,15 +341,36 @@ class KoinService
array $tags): int array $tags): int
{ {
$pageData = $this->login($this->config['koin.user'], $this->config['koin.pass']); $pageData = $this->login($this->config['koin.user'], $this->config['koin.pass']);
$token = Json::decode($pageData->getBody())->token;
$this->loadFormData($pageData->getBody()->getContents()); $accounts = $this->getAccounts($token);
return $this->postData( $categories = $this->getCategories($token);
$amount,
$currency, $categoryId = array_reduce($categories, function($carry, $item) use ($category) {
$date, return $carry ? $carry : ($item['name'] == $category ? $item['id'] : false);
$this->getCategoryId($category), }, false);
$this->getTagsString($tags)
); if (!$categoryId) {
$categoryId = array_reduce($categories, function($carry, $item) {
return $carry ? $carry : ($item['name'] == self::DEFAULT_EXPENSE ? $item['id'] : false);
}, false);
}
$saveResponse = $this->httpClient
->post(self::BASE_URI . "/web/transactions", [
'headers' => ['Bearer' => $token],
'json' => [
'account_id' => $accounts[0]['id'],
'category_id' => $categoryId,
'currency' => $currency,
'date' => $date,
'is_favourite' => false,
'tagData' => $this->getTagsString($tags),
'value' => $amount,
],
]);
return $saveResponse->getStatusCode();
} }
/** /**
@ -373,111 +380,40 @@ class KoinService
*/ */
private function login(string $user, string $pass): ResponseInterface private function login(string $user, string $pass): ResponseInterface
{ {
$httpResponse = $this->httpClient->get(self::BASE_URI); return $this->httpClient
->post(self::BASE_URI . "/web/auth/login", [
$body = $httpResponse->getBody(); 'json' => [
'email' => $user,
$this->getCsrfToken($body->getContents()); 'password' => $pass,
$httpResponse = $this->httpClient
->post(self::BASE_URI . "/site/login", [
'form_params' => [
$this->csrfParam => $this->csrfToken,
'LoginForm[email]' => $user,
'LoginForm[pass]' => $pass,
'LoginForm[rememberMe]' => 0,
], ],
]); ]);
return $httpResponse;
} }
/** /**
* @param $htmlData * @param string $token
* @return array
*/ */
private function loadFormData(string $htmlData) private function getAccounts(string $token): array
{ {
$documentXpath = $this->getCsrfToken($htmlData); $response = $this->httpClient->get(self::BASE_URI . "/web/accounts", [
$this->getAccountId($documentXpath); 'headers' => [
'Bearer' => $token,
$expenseOptionElements = $documentXpath->query('//select[@id="transaction-category_id"]/optgroup[@label="Kiadás"]/option'); ],
$incomeOptionElements = $documentXpath->query('//select[@id="transaction-category_id"]/optgroup[@label="Bevétel"]/option'); ]);
return Json::decode($response->getBody(), Json::TYPE_ARRAY)['accounts'];
/** @var \DOMElement $element */
foreach ($expenseOptionElements as $element) {
$this->expenseCategories[$element->nodeValue] = $element->getAttribute("value");
}
/** @var \DOMElement $element */
foreach ($incomeOptionElements as $element) {
$this->incomeCategories[$element->nodeValue] = $element->getAttribute("value");
}
} }
/** /**
* Parse csrf from html * @param string $token
* * @return array
* @param $html
* @return \DOMXPath
*/ */
private function getCsrfToken(string $html): \DOMXPath private function getCategories(string $token): array
{ {
$xmlErrorHandling = libxml_use_internal_errors(TRUE); $response = $this->httpClient->get(self::BASE_URI . "/web/categories", [
$domDocument = new \DOMDocument(); 'query' => ['show_hidden' => 1],
$domDocument->loadHTML($html); 'headers' => ['Bearer' => $token],
libxml_clear_errors(); ]);
libxml_use_internal_errors($xmlErrorHandling); return Json::decode($response->getBody(), Json::TYPE_ARRAY)['categories'];
$documentXpath = new \DOMXPath($domDocument);
$paramElement = $documentXpath->query('//meta[@name="csrf-param"]')->item(0);
$tokenElement = $documentXpath->query('//meta[@name="csrf-token"]')->item(0);
if ($paramElement instanceof \DOMElement) {
$this->csrfParam = $paramElement->getAttribute("content");
}
if ($tokenElement instanceof \DOMElement) {
$this->csrfToken = $tokenElement->getAttribute("content");
}
return $documentXpath;
}
/**
* Parse account_id from html
* @param \DOMXPath $documentXpath
*/
private function getAccountId(\DOMXPath $documentXpath)
{
$accountIdElement = $documentXpath->query('//input[@id="transaction-account_id"]')->item(0);
if ($accountIdElement instanceof \DOMElement) {
$this->accountId = $accountIdElement->getAttribute("value");
}
}
/**
* @param string $amount
* @param string $currency
* @param string $date
* @param string $category
* @param string $tags
* @return int
*/
private function postData(string $amount, string $currency, string $date, string $category, string $tags): int
{
$saveResponse = $this->httpClient
->post(self::BASE_URI . "/main/save-transaction", [
'form_params' => [
$this->csrfParam => $this->csrfToken,
'Transaction[account_id]' => $this->accountId,
'Transaction[category_id]' => $category,
'Transaction[value]' => $amount,
'Transaction[currency]' => $currency,
'Transaction[imgKey]' => "",
'Transaction[tagData]' => $tags,
'Transaction[date]' => $date,
],
]);
return $saveResponse->getStatusCode();
} }
/** /**
@ -488,21 +424,4 @@ class KoinService
{ {
return implode(';', $tags); return implode(';', $tags);
} }
/**
* Returns the category id from the human readable name
* Income is scanned first, if there is a duplicate type it will be treated as income
* @param string $category
* @return string
*/
private function getCategoryId(string $category): string
{
if (in_array($category, array_keys($this->incomeCategories))) {
return $this->incomeCategories[$category];
}
if (in_array($category, array_keys($this->expenseCategories))) {
return $this->expenseCategories[$category];
}
return $this->expenseCategories[self::DEFAULT_EXPENSE];
}
} }