PageRenderTime 56ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 1ms

/app/code/local/Goodahead/NovaPoshta/Model/Api/Client.php

https://bitbucket.org/kowalski08051/novaposhta
PHP | 891 lines | 426 code | 60 blank | 405 comment | 48 complexity | 9119a5a9ca09e51389028b849c08afdf MD5 | raw file
  1. <?php
  2. class Goodahead_NovaPoshta_Model_Api_Client {
  3. /**
  4. * Key for API NovaPoshta
  5. *
  6. * @var string $_key
  7. * @see https://my.novaposhta.ua/settings/index#apikeys
  8. */
  9. protected $_key;
  10. /**
  11. * @var bool $_throwErrors Throw exceptions when in response is error
  12. */
  13. protected $_throwErrors = FALSE;
  14. /**
  15. * @var string $_format Format of returned data - array, json, xml
  16. */
  17. protected $_format = 'array';
  18. /**
  19. * @var string $_connectionType Connection type (curl | file_get_contents)
  20. */
  21. protected $_connectionType = 'curl';
  22. /**
  23. * @var string $_areas Areas (loaded from file, because there is no so function in NovaPoshta API 2.0)
  24. */
  25. protected $_areas;
  26. /**
  27. * @var string $_model Set current model for methods save(), update(), delete()
  28. */
  29. protected $_model = 'Common';
  30. /**
  31. * @var string $_method Set method of current model
  32. */
  33. protected $_method;
  34. /**
  35. * @var array $_params Set params of current method of current model
  36. */
  37. protected $_params;
  38. /**
  39. * Default constructor
  40. *
  41. * @param string $key NovaPoshta API key
  42. * @param bool $throwErrors Throw request errors as Exceptions
  43. * @param bool $connectionType Connection type (curl | file_get_contents)
  44. * @return Goodahead_Novaposhta_Model_Api_Client
  45. */
  46. function __construct($key, $throwErrors = FALSE, $connectionType = 'curl') {
  47. $this->_throwErrors = $throwErrors;
  48. return $this
  49. ->setKey($key)
  50. ->setConnectionType($connectionType)
  51. ->model('Common');
  52. }
  53. /**
  54. * Setter for key property
  55. *
  56. * @param string $key NovaPoshta API key
  57. * @return Goodahead_Novaposhta_Model_Api_Client
  58. */
  59. function setKey($key) {
  60. $this->_key = $key;
  61. return $this;
  62. }
  63. /**
  64. * Getter for key property
  65. *
  66. * @return string
  67. */
  68. function getKey() {
  69. return $this->_key;
  70. }
  71. /**
  72. * Setter for $connectionType property
  73. *
  74. * @param string $connectionType Connection type (curl | file_get_contents)
  75. * @return this
  76. */
  77. function setConnectionType($connectionType) {
  78. $this->_connectionType = $connectionType;
  79. return $this;
  80. }
  81. /**
  82. * Getter for $connectionType property
  83. *
  84. * @return string
  85. */
  86. function getConnectionType() {
  87. return $this->_connectionType;
  88. }
  89. /**
  90. * Setter for format property
  91. *
  92. * @param string $format Format of returned data by methods (json, xml, array)
  93. * @return Goodahead_Novaposhta_Model_Api_Client
  94. */
  95. function setFormat($format) {
  96. $this->_format = $format;
  97. return $this;
  98. }
  99. /**
  100. * Getter for format property
  101. *
  102. * @return string
  103. */
  104. function getFormat() {
  105. return $this->_format;
  106. }
  107. /**
  108. * Prepare data before return it
  109. *
  110. * @param json $data
  111. * @return mixed
  112. */
  113. private function prepare($data) {
  114. //Returns array
  115. if ($this->_format == 'array') {
  116. $result = is_array($data)
  117. ? $data
  118. : json_decode($data, 1);
  119. // If error exists, throw Exception
  120. if ($this->_throwErrors AND $result['errors'])
  121. throw new Exception(is_array($result['errors']) ? implode("\n", $result['errors']) : $result['errors']);
  122. return $result['data'];
  123. }
  124. // Returns json or xml document
  125. return $data;
  126. }
  127. /**
  128. * Converts array to xml
  129. *
  130. * @param array
  131. */
  132. private function array2xml(array $array, $xml = false){
  133. ($xml === false) AND $xml = new \SimpleXMLElement('<root/>');
  134. foreach($array as $key => $value){
  135. if (is_array($value)){
  136. $this->array2xml($value, $xml->addChild($key));
  137. } else {
  138. $xml->addChild($key, $value);
  139. }
  140. }
  141. return $xml->asXML();
  142. }
  143. /**
  144. * Make request to NovaPoshta API
  145. *
  146. * @param string $model Model name
  147. * @param string $method Method name
  148. * @param array $params Required params
  149. */
  150. private function request($model, $method, $params = NULL) {
  151. // Get required URL
  152. $url = $this->_format == 'xml'
  153. ? 'https://api.novaposhta.ua/v2.0/xml/'
  154. : 'https://api.novaposhta.ua/v2.0/json/';
  155. $data = array(
  156. 'apiKey' => $this->_key,
  157. 'modelName' => $model,
  158. 'calledMethod' => $method,
  159. 'methodProperties' => $params
  160. );
  161. // Convert data to neccessary format
  162. $post = $this->_format == 'xml'
  163. ? $this->array2xml($data)
  164. : $post = json_encode($data);
  165. if ($this->getConnectionType() == 'curl') {
  166. $ch = curl_init($url);
  167. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  168. curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: '.($this->_format == 'xml' ? 'text/xml' : 'application/json')));
  169. curl_setopt($ch, CURLOPT_HEADER, 0);
  170. curl_setopt($ch, CURLOPT_POST, 1);
  171. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
  172. curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
  173. $result = curl_exec($ch);
  174. curl_close($ch);
  175. } else {
  176. $result = file_get_contents($url, null, stream_context_create(array(
  177. 'http' => array(
  178. 'method' => 'POST',
  179. 'header' => "Content-type: application/x-www-form-urlencoded;\r\n",
  180. 'content' => $post,
  181. ),
  182. )));
  183. }
  184. return $this->prepare($result);
  185. }
  186. /**
  187. * Set current model and empties method and params properties
  188. *
  189. * @param string $model
  190. * @return mixed
  191. */
  192. function model($model = '') {
  193. if ( ! $model)
  194. return $this->_model;
  195. $this->_model = $model;
  196. $this->_method = NULL;
  197. $this->_params = NULL;
  198. return $this;
  199. }
  200. /**
  201. * Set method of current model property and empties params properties
  202. *
  203. * @param string $method
  204. * @return mixed
  205. */
  206. function method($method = '') {
  207. if ( ! $method)
  208. return $this->_method;
  209. $this->_method = $method;
  210. $this->_params = NULL;
  211. return $this;
  212. }
  213. /**
  214. * Set params of current method/property property
  215. *
  216. * @param array $params
  217. * @return mixed
  218. */
  219. function params($params) {
  220. $this->_params = $params;
  221. return $this;
  222. }
  223. /**
  224. * Execute request to NovaPoshta API
  225. *
  226. * @return mixed
  227. */
  228. function execute() {
  229. return $this->request($this->_model, $this->_method, $this->_params);
  230. }
  231. /**
  232. * Get tracking information by track number
  233. *
  234. * @param string $track Track number
  235. * @return mixed
  236. */
  237. function documentsTracking($track) {
  238. return $this->request('InternetDocument', 'documentsTracking', array('Documents' => array('item' => $track)));
  239. }
  240. /**
  241. * Get cities of company NovaPoshta
  242. *
  243. * @param int $page Num of page
  244. * @param string $findByString Find city by russian or ukrainian word
  245. * @param string $ref ID of city
  246. * @return mixed
  247. */
  248. function getCities($page = 0, $findByString = '', $ref = '') {
  249. return $this->request('Address', 'getCities', array(
  250. 'Page' => $page,
  251. 'FindByString' => $findByString,
  252. 'Ref' => $ref,
  253. ));
  254. }
  255. /**
  256. * Get warehouses by city
  257. *
  258. * @param string $cityRef ID of city
  259. * @param int $page
  260. * @return mixed
  261. */
  262. function getWarehouses($cityRef, $page = 0) {
  263. return $this->request('Address', 'getWarehouses', array(
  264. 'CityRef' => $cityRef,
  265. 'Page' => $page,
  266. ));
  267. }
  268. /**
  269. * Get 5 nearest warehouses by array of strings
  270. *
  271. * @param array $searchStringArray
  272. * @return mixed
  273. */
  274. function findNearestWarehouse($searchStringArray) {
  275. $searchStringArray = (array) $searchStringArray;
  276. return $this->request('Address', 'findNearestWarehouse', array(
  277. 'SearchStringArray' => $searchStringArray,
  278. ));
  279. }
  280. /**
  281. * Get warehouse by city name and warehouse's description
  282. *
  283. * @param string $cityRef ID of city
  284. * @param string $description Description like in getted by getWarehouses()
  285. * @return mixed
  286. */
  287. function getWarehouse($cityRef, $description = '') {
  288. $warehouses = $this->getWarehouses($cityRef);
  289. $data = array();
  290. if (is_array($warehouses['data'])) {
  291. if (count($warehouses['data']) == 1) {
  292. $data = $warehouses['data'][0];
  293. } elseif (count($warehouses['data']) > 1 AND $description) {
  294. foreach ($warehouses['data'] as $warehouse) {
  295. if (mb_stripos($warehouse['Description'], $description) !== FALSE
  296. OR mb_stripos($warehouse['DescriptionRu'], $description) !== FALSE) {
  297. $data = $warehouse;
  298. break;
  299. }
  300. }
  301. }
  302. }
  303. // Error
  304. ( ! $data) AND $error = 'Warehouse was not found';
  305. // Return data in same format like NovaPoshta API
  306. return $this->prepare(
  307. array(
  308. 'success' => empty($error),
  309. 'data' => array($data),
  310. 'errors' => (array) $error,
  311. 'warnings' => array(),
  312. 'info' => array(),
  313. ));
  314. }
  315. /**
  316. * Get streets list by city and/or search string
  317. *
  318. * @param string $cityRef ID of city
  319. * @param string $findByString
  320. * @param int $page
  321. * @return mixed
  322. */
  323. function getStreet($cityRef, $findByString = '', $page = 0) {
  324. return $this->request('Address', 'getStreet', array(
  325. 'FindByString' => $findByString,
  326. 'CityRef' => $cityRef,
  327. 'Page' => $page,
  328. ));
  329. }
  330. /**
  331. * Find current area in list of areas
  332. *
  333. * @param array $areas List of arias, getted from file
  334. * @param string $findByString Area name
  335. * @param string $ref Area Ref ID
  336. * @return array
  337. */
  338. protected function findArea(array $areas, $findByString = '', $ref = '') {
  339. $data = array();
  340. if ( ! $findByString AND ! $ref)
  341. return $data;
  342. // Try to find current region
  343. foreach ($areas as $key => $area) {
  344. // Is current area found by string or by key
  345. $found = $findByString
  346. ? ((mb_stripos($area['Description'], $findByString) !== FALSE)
  347. OR (mb_stripos($area['DescriptionRu'], $findByString) !== FALSE)
  348. OR (mb_stripos($area['Area'], $findByString) !== FALSE)
  349. OR (mb_stripos($area['AreaRu'], $findByString) !== FALSE))
  350. : ($key == $ref);
  351. if ($found) {
  352. $area['Ref'] = $key;
  353. $data[] = $area;
  354. break;
  355. }
  356. }
  357. return $data;
  358. }
  359. /**
  360. * Get area by name or by ID
  361. *
  362. * @param string $findByString Find area by russian or ukrainian word
  363. * @param string $ref Get area by ID
  364. * @return array
  365. */
  366. function getArea($findByString = '', $ref = '') {
  367. // Load areas list from file
  368. empty($this->_areas) AND $this->_areas = include dirname(__FILE__).'/Goodahead_Novaposhta_Model_Api_ClientAreas.php';
  369. $data = $this->findArea($this->_areas, $findByString, $ref);
  370. // Error
  371. empty($data) AND $error = 'Area was not found';
  372. // Return data in same format like NovaPoshta API
  373. return $this->prepare(
  374. array(
  375. 'success' => empty($error),
  376. 'data' => $data,
  377. 'errors' => (array) $error,
  378. 'warnings' => array(),
  379. 'info' => array(),
  380. ));
  381. }
  382. /**
  383. * Get areas list by city and/or search string
  384. *
  385. * @param string $ref ID of area
  386. * @param int $page
  387. * @return mixed
  388. */
  389. function getAreas($ref = '', $page = 0) {
  390. return $this->request('Address', 'getAreas', array(
  391. 'Ref' => $ref,
  392. 'Page' => $page,
  393. ));
  394. }
  395. /**
  396. * Find city from list by name of region
  397. *
  398. * @param array $cities Array from query getCities to NovaPoshta
  399. * @param string $areaName
  400. * @return array
  401. */
  402. protected function findCityByRegion($cities, $areaName) {
  403. $data = array();
  404. $areaRef = '';
  405. // Get region id
  406. $area = $this->getArea($areaName);
  407. $area['success'] AND $areaRef = $area['data'][0]['Ref'];
  408. if ($areaRef AND is_array($cities['data'])) {
  409. foreach($cities['data'] as $city) {
  410. if ($city['Area'] == $areaRef) {
  411. $data[] = $city;
  412. }
  413. }
  414. }
  415. return $data;
  416. }
  417. /**
  418. * Get city by name and region (if it needs)
  419. *
  420. * @param string $cityName City's name
  421. * @param string $areaName Region's name
  422. * @return array City's data
  423. */
  424. function getCity($cityName, $areaName = '') {
  425. // Get cities by name
  426. $cities = $this->getCities(0, $cityName);
  427. if (is_array($cities['data'])) {
  428. // If cities more then one, calculate current by area name
  429. $data = (count($cities['data']) > 1)
  430. ? $this->findCityByRegion($cities, $areaName)
  431. : $cities['data'][0];
  432. }
  433. // Error
  434. ( ! $data) AND $error = 'City was not found';
  435. // Return data in same format like NovaPoshta API
  436. return $this->prepare(
  437. array(
  438. 'success' => empty($error),
  439. 'data' => array($data),
  440. 'errors' => (array) $error,
  441. 'warnings' => array(),
  442. 'info' => array(),
  443. ));
  444. }
  445. /**
  446. * Magic method of calling functions (uses for calling Common Model of NovaPoshta API)
  447. *
  448. * @param string $method Called method of Common Model
  449. * @param array $arguments Array of params
  450. */
  451. function __call($method, $arguments) {
  452. $common_model_method = array(
  453. 'getTypesOfCounterparties',
  454. 'getBackwardDeliveryCargoTypes',
  455. 'getCargoDescriptionList',
  456. 'getCargoTypes',
  457. 'getDocumentStatuses',
  458. 'getOwnershipFormsList',
  459. 'getPalletsList',
  460. 'getPaymentForms',
  461. 'getTimeIntervals',
  462. 'getServiceTypes',
  463. 'getTiresWheelsList',
  464. 'getTraysList',
  465. 'getTypesOfAlternativePayers',
  466. 'getTypesOfPayers',
  467. 'getTypesOfPayersForRedelivery',
  468. );
  469. // Call method of Common model
  470. if (in_array($method, $common_model_method)) {
  471. return $this
  472. ->model('Common')
  473. ->method($method)
  474. ->params(NULL)
  475. ->execute();
  476. }
  477. }
  478. /**
  479. * Delete method of current model
  480. *
  481. * @param array $params
  482. * @return mixed
  483. */
  484. function delete($params) {
  485. return $this->request($this->_model, 'delete', $params);
  486. }
  487. /**
  488. * Update method of current model
  489. * Required params:
  490. * For ContactPerson model: Ref, CounterpartyRef, FirstName (ukr), MiddleName, LastName, Phone (format 0xxxxxxxxx)
  491. * For Counterparty model: Ref, CounterpartyProperty (Recipient|Sender), CityRef, CounterpartyType (Organization, PrivatePerson),
  492. * FirstName (or name of organization), MiddleName, LastName, Phone (0xxxxxxxxx), OwnershipForm (if Organization)
  493. *
  494. * @param array $params
  495. * @return mixed
  496. */
  497. function update($params) {
  498. return $this->request($this->_model, 'update', $params);
  499. }
  500. /**
  501. * Save method of current model
  502. * Required params:
  503. * For ContactPerson model (only for Organization API key, for PrivatePerson error will be returned):
  504. * CounterpartyRef, FirstName (ukr), MiddleName, LastName, Phone (format 0xxxxxxxxx)
  505. * For Counterparty model:
  506. * CounterpartyProperty (Recipient|Sender), CityRef, CounterpartyType (Organization, PrivatePerson),
  507. * FirstName (or name of organization), MiddleName, LastName, Phone (0xxxxxxxxx), OwnershipForm (if Organization)
  508. *
  509. * @param array $params
  510. * @return mixed
  511. */
  512. function save($params) {
  513. return $this->request($this->_model, 'save', $params);
  514. }
  515. /**
  516. * getCounterparties() function of model Counterparty
  517. *
  518. * @param string $counterpartyProperty Type of Counterparty (Sender|Recipient)
  519. * @param int $page Page number
  520. * @param string $findByString String to search
  521. * @param string $cityRef City ID
  522. * @return mixed
  523. */
  524. function getCounterparties($counterpartyProperty = 'Recipient', $page = NULL, $findByString = NULL, $cityRef = NULL) {
  525. // Any param can be skipped
  526. $params = array();
  527. $params['CounterpartyProperty'] = $counterpartyProperty ? $counterpartyProperty : 'Recipient';
  528. $page AND $params['Page'] = $page;
  529. $findByString AND $params['FindByString'] = $findByString;
  530. $cityRef AND $params['CityRef'] = $cityRef;
  531. return $this->request('Counterparty', 'getCounterparties', $params);
  532. }
  533. /**
  534. * cloneLoyaltyCounterpartySender() function of model Counterparty
  535. * The counterparty will be not created immediately, you can wait a long time
  536. *
  537. * @param string $cityRef City ID
  538. * @return mixed
  539. */
  540. function cloneLoyaltyCounterpartySender($cityRef) {
  541. return $this->request('Counterparty', 'cloneLoyaltyCounterpartySender', array('CityRef' => $cityRef));
  542. }
  543. /**
  544. * getCounterpartyContactPersons() function of model Counterparty
  545. *
  546. * @param string $ref Counterparty ref
  547. * @return mixed
  548. */
  549. function getCounterpartyContactPersons($ref) {
  550. return $this->request('Counterparty', 'getCounterpartyContactPersons', array('Ref' => $ref));
  551. }
  552. /**
  553. * getCounterpartyAddresses() function of model Counterparty
  554. *
  555. * @param string $ref Counterparty ref
  556. * @param int $page
  557. * @return mixed
  558. */
  559. function getCounterpartyAddresses($ref, $page = 0) {
  560. return $this->request('Counterparty', 'getCounterpartyAddresses', array('Ref' => $ref, 'Page' => $page));
  561. }
  562. /**
  563. * getCounterpartyOptions() function of model Counterparty
  564. *
  565. * @param string $ref Counterparty ref
  566. * @return mixed
  567. */
  568. function getCounterpartyOptions($ref) {
  569. return $this->request('Counterparty', 'getCounterpartyOptions', array('Ref' => $ref));
  570. }
  571. /**
  572. * getCounterpartyByEDRPOU() function of model Counterparty
  573. *
  574. * @param string $edrpou EDRPOU code
  575. * @param string $cityRef City ID
  576. * @return mixed
  577. */
  578. function getCounterpartyByEDRPOU($edrpou, $cityRef) {
  579. return $this->request('Counterparty', 'getCounterpartyByEDRPOU', array('EDRPOU' => $edrpou, 'cityRef' => $cityRef));
  580. }
  581. /**
  582. * Get price of delivery between two cities
  583. *
  584. * @param string $citySender City ID
  585. * @param string $cityRecipient City ID
  586. * @param string $serviceType (DoorsDoors|DoorsWarehouse|WarehouseWarehouse|WarehouseDoors)
  587. * @param float $weight
  588. * @param float $cost
  589. * @return mixed
  590. */
  591. function getDocumentPrice($citySender, $cityRecipient, $serviceType, $weight, $cost) {
  592. return $this->request('InternetDocument', 'getDocumentPrice', array(
  593. 'CitySender' => $citySender,
  594. 'CityRecipient' => $cityRecipient,
  595. 'ServiceType' => $serviceType,
  596. 'Weight' => $weight,
  597. 'Cost' => $cost,
  598. ));
  599. }
  600. /**
  601. * Get approximately date of delivery between two cities
  602. *
  603. * @param string $citySender City ID
  604. * @param string $cityRecipient City ID
  605. * @param string $serviceType (DoorsDoors|DoorsWarehouse|WarehouseWarehouse|WarehouseDoors)
  606. * @param string $dateTime Date of shipping
  607. * @return mixed
  608. */
  609. function getDocumentDeliveryDate($citySender, $cityRecipient, $serviceType, $dateTime) {
  610. return $this->request('InternetDocument', 'getDocumentDeliveryDate', array(
  611. 'CitySender' => $citySender,
  612. 'CityRecipient' => $cityRecipient,
  613. 'ServiceType' => $serviceType,
  614. 'DateTime' => $dateTime,
  615. ));
  616. }
  617. /**
  618. * Get documents list
  619. *
  620. * @param array $params List of params
  621. * Not required keys:
  622. * 'Ref', 'IntDocNumber', 'InfoRegClientBarcodes', 'DeliveryDateTime', 'RecipientDateTime',
  623. * 'CreateTime', 'SenderRef', 'RecipientRef', 'WeightFrom', 'WeightTo',
  624. * 'CostFrom', 'CostTo', 'SeatsAmountFrom', 'SeatsAmountTo', 'CostOnSiteFrom',
  625. * 'CostOnSiteTo', 'StateIds', 'ScanSheetRef', 'DateTime', 'DateTimeFrom',
  626. * 'RecipientDateTime', 'isAfterpayment', 'Page', 'OrderField =>
  627. * [
  628. * IntDocNumber, DateTime, Weight, Cost, SeatsAmount, CostOnSite,
  629. * CreateTime, EstimatedDeliveryDate, StateId, InfoRegClientBarcodes, RecipientDateTime
  630. * ],
  631. * 'OrderDirection' => [DESC, ASC], 'ScanSheetRef'
  632. * @return mixed
  633. */
  634. function getDocumentList($params = NULL) {
  635. return $this->request('InternetDocument', 'getDocumentList', $params ? $params : NULL);
  636. }
  637. /**
  638. * Get document info by ID
  639. *
  640. * @param string $ref Document ID
  641. * @return mixed
  642. */
  643. function getDocument($ref) {
  644. return $this->request('InternetDocument', 'getDocument', array(
  645. 'Ref' => $ref,
  646. ));
  647. }
  648. /**
  649. * Generetes report by Document refs
  650. *
  651. * @param array $params Params like getDocumentList with requiered keys
  652. * 'Type' => [xls, csv], 'DocumentRefs' => []
  653. * @return mixed
  654. */
  655. function generateReport($params) {
  656. return $this->request('InternetDocument', 'generateReport', $params);
  657. }
  658. /**
  659. * Check required fields for new InternetDocument and set defaults
  660. *
  661. * @param array & $counterparty Recipient info array
  662. * @return void
  663. */
  664. protected function checkInternetDocumentRecipient(array & $counterparty) {
  665. // Check required fields
  666. if ( ! $counterparty['FirstName'])
  667. throw new \Exception('FirstName is required filed for recipient');
  668. // MiddleName realy is not required field, but manual says otherwise
  669. // if ( ! $counterparty['MiddleName'])
  670. // throw new \Exception('MiddleName is required filed for sender and recipient');
  671. if ( ! $counterparty['LastName'])
  672. throw new \Exception('LastName is required filed for recipient');
  673. if ( ! $counterparty['Phone'])
  674. throw new \Exception('Phone is required filed for recipient');
  675. if ( ! ($counterparty['City'] OR $counterparty['CityRef']))
  676. throw new \Exception('City is required filed for recipient');
  677. if ( ! ($counterparty['Region'] OR $counterparty['CityRef']))
  678. throw new \Exception('Region is required filed for recipient');
  679. // Set defaults
  680. if ( ! $counterparty['CounterpartyType']) {
  681. $counterparty['CounterpartyType'] = 'PrivatePerson';
  682. }
  683. }
  684. /**
  685. * Check required params for new InternetDocument and set defaults
  686. *
  687. * @param array & $params
  688. * @return void
  689. */
  690. protected function checkInternetDocumentParams(array & $params) {
  691. if ( ! $params['Description'])
  692. throw new \Exception('Description is required filed for new Internet document');
  693. if ( ! $params['Weight'])
  694. throw new \Exception('Weight is required filed for new Internet document');
  695. if ( ! $params['Cost'])
  696. throw new \Exception('Cost is required filed for new Internet document');
  697. ( ! $params['DateTime']) AND $params['DateTime'] = date('d.m.Y');
  698. ( ! $params['ServiceType']) AND $params['ServiceType'] = 'WarehouseWarehouse';
  699. ( ! $params['PaymentMethod']) AND $params['PaymentMethod'] = 'Cash';
  700. ( ! $params['PayerType']) AND $params['PayerType'] = 'Recipient';
  701. ( ! $params['SeatsAmount']) AND $params['SeatsAmount'] = '1';
  702. ( ! $params['CargoType']) AND $params['CargoType'] = 'Cargo';
  703. ( ! $params['VolumeGeneral']) AND $params['VolumeGeneral'] = '0.0004';
  704. }
  705. /**
  706. * Create Internet Document by
  707. *
  708. * @param array $sender Sender info.
  709. * Required:
  710. * For existing sender:
  711. * 'Description' => String (Full name i.e.), 'City' => String (City name)
  712. * For creating:
  713. * 'FirstName' => String, 'MiddleName' => String,
  714. * 'LastName' => String, 'Phone' => '000xxxxxxx', 'City' => String (City name), 'Region' => String (Region name),
  715. * 'Warehouse' => String (Description from getWarehouses))
  716. * @param array $recipient Recipient info, same like $sender param
  717. * @param array $params Additional params of Internet Document
  718. * Required:
  719. * 'Description' => String, 'Weight' => Float, 'Cost' => Float
  720. * Recommended:
  721. * 'VolumeGeneral' => Float (default = 0.004), 'SeatsAmount' => Int (default = 1),
  722. * 'PayerType' => (Sender|Recipient - default), 'PaymentMethod' => (NonCash|Cash - default)
  723. * 'ServiceType' => (DoorsDoors|DoorsWarehouse|WarehouseDoors|WarehouseWarehouse - default)
  724. * 'CargoType' => String
  725. * @param mixed
  726. */
  727. function newInternetDocument($sender, $recipient, $params) {
  728. // Check for required params and set defaults
  729. $this->checkInternetDocumentRecipient($recipient);
  730. $this->checkInternetDocumentParams($params);
  731. if ( ! $sender['CitySender']) {
  732. $senderCity = $this->getCity($sender['City'], $sender['Region']);
  733. $sender['CitySender'] = $senderCity['data'][0]['Ref'];
  734. }
  735. $sender['CityRef'] = $sender['CitySender'];
  736. if ( ! $sender['SenderAddress'] AND $sender['CitySender'] AND $sender['Warehouse']) {
  737. $senderWarehouse = $this->getWarehouse($sender['CitySender'], $sender['Warehouse']);
  738. $sender['SenderAddress'] = $senderWarehouse['data'][0]['Ref'];
  739. }
  740. if ( ! $sender['Sender']) {
  741. $sender['CounterpartyProperty'] = 'Sender';
  742. // Set full name to Description if is not set
  743. if ( ! $sender['Description']) {
  744. $sender['Description'] = $sender['LastName'].' '.$sender['FirstName'].' '.$sender['MiddleName'];
  745. }
  746. // Check for existing sender
  747. $senderCounterpartyExisting = $this->getCounterparties('Sender', 1, $sender['Description'], $sender['CityRef']);
  748. // Copy user to the selected city if user doesn't exists there
  749. if ($senderCounterpartyExisting['data'][0]['Ref']) {
  750. // Counterparty exists
  751. $sender['Sender'] = $senderCounterpartyExisting['data'][0]['Ref'];
  752. $contactSender = $this->getCounterpartyContactPersons($sender['Sender']);
  753. $sender['ContactSender'] = $contactSender['data'][0]['Ref'];
  754. $sender['SendersPhone'] = $sender['Phone'] ? $sender['Phone'] : $contactSender['data'][0]['Phones'];
  755. }
  756. }
  757. // Prepare recipient data
  758. $recipient['CounterpartyProperty'] = 'Recipient';
  759. $recipient['RecipientsPhone'] = $recipient['Phone'];
  760. if ( ! $recipient['CityRecipient']) {
  761. $recipientCity = $this->getCity($recipient['City'], $recipient['Region']);
  762. $recipient['CityRecipient'] = $recipientCity['data'][0]['Ref'];
  763. }
  764. $recipient['CityRef'] = $recipient['CityRecipient'];
  765. if ( ! $recipient['RecipientAddress']) {
  766. $recipientWarehouse = $this->getWarehouse($recipient['CityRecipient'], $recipient['Warehouse']);
  767. $recipient['RecipientAddress'] = $recipientWarehouse['data'][0]['Ref'];
  768. }
  769. if ( ! $recipient['Recipient']) {
  770. $recipientCounterparty = $this->_model('Counterparty')->save($recipient);
  771. $recipient['Recipient'] = $recipientCounterparty['data'][0]['Ref'];
  772. $recipient['ContactRecipient'] = $recipientCounterparty['data'][0]['ContactPerson']['data'][0]['Ref'];
  773. }
  774. // Full params is merge of arrays $sender, $recipient, $params
  775. $paramsInternetDocument = array_merge($sender, $recipient, $params);
  776. // Creating new Internet Document
  777. return $this->_model('InternetDocument')->save($paramsInternetDocument);
  778. }
  779. /**
  780. * Get only link on internet document for printing
  781. *
  782. * @param string $method Called method of NovaPoshta API
  783. * @param array|string $documentRefs Array of Documents IDs
  784. * @param string $type (html_link|pdf_link)
  785. * @return mixed
  786. */
  787. protected function printGetLink($method, $documentRefs, $type) {
  788. $data = 'https://my.novaposhta.ua/orders/' . $method . '/orders[]/'.implode(',', $documentRefs)
  789. .'/type/'.str_replace('_link', '', $type)
  790. .'/apiKey/'.$this->_key;
  791. // Return data in same format like NovaPoshta API
  792. return $this->prepare(
  793. array(
  794. 'success' => TRUE,
  795. 'data' => array($data),
  796. 'errors' => array(),
  797. 'warnings' => array(),
  798. 'info' => array(),
  799. ));
  800. }
  801. /**
  802. * printDocument method of InternetDocument model
  803. *
  804. * @param array|string $documentRefs Array of Documents IDs
  805. * @param string $type (pdf|html|html_link|pdf_link)
  806. * @return mixed
  807. */
  808. function printDocument($documentRefs, $type = 'html') {
  809. $documentRefs = (array) $documentRefs;
  810. // If needs link
  811. if ($type == 'html_link' OR $type == 'pdf_link')
  812. return $this->printGetLink('printDocument', $documentRefs, $type);
  813. // If needs data
  814. return $this->request('InternetDocument', 'printDocument', array('DocumentRefs' => $documentRefs, 'Type' => $type));
  815. }
  816. /**
  817. * printMarkings method of InternetDocument model
  818. *
  819. * @param array|string $documentRefs Array of Documents IDs
  820. * @param string $type (pdf|new_pdf|new_html|old_html|html_link|pdf_link)
  821. * @return mixed
  822. */
  823. function printMarkings($documentRefs, $type = 'new_html') {
  824. $documentRefs = (array) $documentRefs;
  825. // If needs link
  826. if ($type == 'html_link' OR $type == 'pdf_link')
  827. return $this->printGetLink('printMarkings', $documentRefs, $type);
  828. // If needs data
  829. return $this->request('InternetDocument', 'printMarkings', array('DocumentRefs' => $documentRefs, 'Type' => $type));
  830. }
  831. }