Guest User

Untitled

a guest
Feb 14th, 2018
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 23.45 KB | None | 0 0
  1. <?php
  2.  
  3. namespace Drupal\commerce_quickbooks_enterprise\SoapBundle\Services;
  4.  
  5. use Drupal\commerce_quickbooks_enterprise\QbeUtilities;
  6. use Drupal\Core\Config\ConfigFactoryInterface;
  7. use Drupal\Core\Entity\EntityTypeManagerInterface;
  8. use Drupal\Core\State\StateInterface;
  9. use Drupal\migrate\MigrateExecutable;
  10. use Drupal\migrate\MigrateMessage;
  11. use Drupal\migrate\Plugin\MigratePluginManagerInterface;
  12. use Drupal\migrate\Plugin\MigrationPluginManager;
  13. use Drupal\user\Entity\User;
  14. use Drupal\user\UserAuthInterface;
  15.  
  16. /**
  17. * Handle SOAP requests and return a response.
  18. *
  19. * Class SoapService.
  20. *
  21. * @package Drupal\commerce_quickbooks_enterprise\SoapBundle\Services
  22. */
  23. class SoapService implements SoapServiceInterface {
  24.  
  25. /**
  26. * The row currently being migrated.
  27. *
  28. * @var \Drupal\migrate\Row
  29. */
  30. protected $row;
  31.  
  32. /**
  33. * The migration plugin manager.
  34. *
  35. * @var \Drupal\migrate\Plugin\MigrationPluginManager
  36. */
  37. protected $migrationPluginManager;
  38.  
  39. /**
  40. * The id map plugin manager.
  41. *
  42. * @var \Drupal\migrate\Plugin\MigratePluginManagerInterface
  43. */
  44. protected $idMapPluginManager;
  45.  
  46. /**
  47. * The user auth service.
  48. *
  49. * @var \Drupal\user\UserAuthInterface
  50. */
  51. private $userAuthInterface;
  52.  
  53. /**
  54. * The session manager.
  55. *
  56. * Responsible for managing, validating and invalidating SOAP sessions.
  57. *
  58. * @var \Drupal\commerce_quickbooks_enterprise\SoapBundle\Services\SoapSessionManager
  59. */
  60. protected $sessionManager;
  61.  
  62. /**
  63. * The entity type manager.
  64. *
  65. * @var \Drupal\Core\Entity\EntityTypeManagerInterface
  66. */
  67. protected $entityTypeManager;
  68.  
  69. /**
  70. * The module's configuration.
  71. *
  72. * @var \Drupal\Core\Config\ImmutableConfig
  73. */
  74. protected $config;
  75.  
  76. /**
  77. * The state service.
  78. *
  79. * @var \Drupal\Core\State\StateInterface
  80. */
  81. protected $state;
  82.  
  83. /**
  84. * The current server version.
  85. *
  86. * @var string
  87. */
  88. protected $serverVersion = '1.0';
  89.  
  90. /**
  91. * The version returned by the client.
  92. *
  93. * @var string
  94. */
  95. protected $clientVersion;
  96.  
  97. /**
  98. * The default order in which to process exportable QB Items.
  99. *
  100. * @var array
  101. */
  102. protected $itemPriorities = [
  103. 'add_customer',
  104. 'mod_customer',
  105. 'add_inventory_product',
  106. 'mod_inventory_product',
  107. 'add_non_inventory_product',
  108. 'mod_non_inventory_product',
  109. 'add_invoice',
  110. 'mod_invoice',
  111. 'add_sales_receipt',
  112. 'mod_sales_receipt',
  113. 'add_payment',
  114. ];
  115.  
  116. /**
  117. * Constructs a new SoapService.
  118. *
  119. * @param \Drupal\migrate\Plugin\MigrationPluginManager $migrationPluginManager
  120. * The migration plugin manager.
  121. * @param \Drupal\migrate\Plugin\MigratePluginManagerInterface $idMapPluginManager
  122. * The id mapping plugin migrate manager.
  123. * @param \Drupal\user\UserAuthInterface $userAuthInterface
  124. * The user auth service.
  125. * @param \Drupal\commerce_quickbooks_enterprise\SoapBundle\Services\SoapSessionManager $sessionManager
  126. * The session manager.
  127. * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entityTypeManager
  128. * The entity type manager.
  129. * @param \Drupal\Core\Config\ConfigFactoryInterface $configFactory
  130. * The config factory.
  131. * @param \Drupal\Core\State\StateInterface $state
  132. * The state service.
  133. */
  134. public function __construct(
  135. MigrationPluginManager $migrationPluginManager,
  136. MigratePluginManagerInterface $idMapPluginManager,
  137. UserAuthInterface $userAuthInterface,
  138. SoapSessionManager $sessionManager,
  139. EntityTypeManagerInterface $entityTypeManager,
  140. ConfigFactoryInterface $configFactory,
  141. StateInterface $state
  142. ) {
  143. $this->migrationPluginManager = $migrationPluginManager;
  144. $this->idMapPluginManager = $idMapPluginManager;
  145. $this->userAuthInterface = $userAuthInterface;
  146. $this->sessionManager = $sessionManager;
  147. $this->entityTypeManager = $entityTypeManager;
  148. $this->config = $configFactory->get('commerce_quickbooks_enterprise.quickbooks_admin');
  149. $this->state = $state;
  150. }
  151.  
  152. /**
  153. * {@inheritdoc}
  154. */
  155. public function __call($method, array $data) {
  156. \Drupal::logger('commerce_qbe')->info("QB SOAP service [$method] called. Incoming request: " . print_r($data, TRUE));
  157. $public_services = ['clientVersion', 'serverVersion', 'authenticate'];
  158.  
  159. $request = $this->prepareResponse($method, $data);
  160.  
  161. $uc = ucfirst($method);
  162. $callable = "call$uc";
  163.  
  164. $response = NULL;
  165.  
  166. // If the method being requested requires a validated user, do that now.
  167. if (!in_array($method, $public_services)) {
  168. // The request must have a ticket to proceed.
  169. if (empty($request->ticket)) {
  170. return $request;
  171. }
  172.  
  173. $valid = $this->sessionManager
  174. ->setUuid($request->ticket)
  175. ->validateSession($method);
  176.  
  177. // If the client has a valid ticket and request, log in now.
  178. if ($valid) {
  179. /** @var \Drupal\user\UserInterface $user */
  180. $user = User::load($this->sessionManager->getUid());
  181. user_login_finalize($user);
  182.  
  183. if (!$user->hasPermission('access quickbooks soap service')) {
  184. \Drupal::logger('commerce_qbe')->warning('User logged in successfully but didn\'t have Quickbooks SOAP Service access permissions.');
  185. return $request;
  186. }
  187. }
  188. else {
  189. \Drupal::logger('commerce_qbe')->error('The user had an invalid session token or made an invalid request. Aborting communication...');
  190. return $request;
  191. }
  192. }
  193.  
  194. // If a valid method method is being called, parse the incoming request
  195. // and call the method with the parsed data passed in.
  196. if (is_callable([$this, $callable])) {
  197. // Prepare the response to the client.
  198. $response = $this->$callable($request);
  199. }
  200.  
  201. return $response;
  202. }
  203.  
  204.  
  205. /****************************************************
  206. * Private helper functions *
  207. ****************************************************/
  208.  
  209. /**
  210. * Builds the stdClass object required by a service response handler.
  211. *
  212. * @param string $method_name
  213. * The Quickbooks method being called.
  214. * @param string $data
  215. * The raw incoming soap request.
  216. *
  217. * @return \stdClass
  218. * An object with the following properties:
  219. * stdClass {
  220. * methodNameResult => '',
  221. * requestParam1 => 'foo',
  222. * ...
  223. * requestParamN => 'bar',
  224. * }
  225. */
  226. private function prepareResponse($method_name, $data) {
  227. $response = isset($data[0]) ? $data[0] : new \stdClass();
  228. $response->$method_name = '';
  229.  
  230. return $response;
  231. }
  232.  
  233. /**
  234. * Calculate the completion progress of the current SOAP session.
  235. *
  236. * @return int
  237. * The percentage completed.
  238. */
  239. private function getCompletionProgress() {
  240. $done = 0;
  241. $todo = 0;
  242. foreach ($this->migrationPluginManager->createInstancesByTag('quickbooks_enterprise') as $id => $migration) {
  243. $map = $migration->getIdMap();
  244. $done += $map->importedCount();
  245. $todo += $migration->getSourcePlugin()->count() - $map->processedCount();
  246. }
  247.  
  248. return $done + $todo ? (int) (100 * ($done / ($done + $todo))) : 1;
  249. }
  250.  
  251.  
  252. /****************************************************
  253. * The WSDL defined SOAP service calls *
  254. ****************************************************/
  255.  
  256. /**
  257. * {@inheritdoc}
  258. */
  259. public function callServerVersion(\stdClass $request) {
  260. $request->serverVersionResult = $this->serverVersion;
  261. return $request;
  262. }
  263.  
  264. /**
  265. * {@inheritdoc}
  266. */
  267. public function callClientVersion(\stdClass $request) {
  268. $this->clientVersion = $request->strVersion;
  269.  
  270. $request->clientVersionResult = '';
  271. return $request;
  272. }
  273.  
  274. /**
  275. * {@inheritdoc}
  276. *
  277. * @TODO: Reset failed exports id requested.
  278. */
  279. public function callAuthenticate(\stdClass $request) {
  280. $strUserName = $request->strUserName;
  281. $strPassword = $request->strPassword;
  282.  
  283. // Initial "fail" response.
  284. $result = ['', 'nvu'];
  285.  
  286. // If the service isn't set for whatever reason we can't continue.
  287. if (!isset($this->userAuthInterface)) {
  288. \Drupal::logger('commerce_qbe')->error("User Auth service couldn't be initialized.");
  289. }
  290. else {
  291. $uid = $this->userAuthInterface->authenticate($strUserName, $strPassword);
  292.  
  293. if (!$uid) {
  294. \Drupal::logger('commerce_qbe')->error("Invalid login credentials, aborting quickbooks SOAP service.");
  295. }
  296. else {
  297. \Drupal::logger('commerce_qbe')->info("Quickbooks user $strUserName successfully connected! Commencing data exchange with client.");
  298.  
  299. $uuid = \Drupal::service('uuid')->generate();
  300. $this->sessionManager->startSession($uuid, $uid);
  301.  
  302. $result = [$uuid, ''];
  303. }
  304. }
  305.  
  306. $request->authenticateResult = $result;
  307. return $request;
  308. }
  309.  
  310. /**
  311. * {@inheritdoc}
  312. */
  313. public function callSendRequestXML(\stdClass $request) {
  314. \Drupal::logger('commerce_qbe')->info("Request received, searching for content to export.");
  315.  
  316. $migrations = $this->migrationPluginManager->createInstancesByTag('quickbooks_enterprise');
  317. /** @var \Drupal\migrate\Plugin\MigrationInterface $migration */
  318. foreach ($this->migrationPluginManager->buildDependencyMigration($migrations, []) as $migration) {
  319. // Proceed to next migration if there are no remaining items to import.
  320. $remaining = $migration->getSourcePlugin()->count() - $migration->getIdMapPlugin()->processedCount();
  321. if (!$remaining) {
  322. continue;
  323. }
  324. // Our MigrateSubscriber stops this migration after a single row.
  325. (new MigrateExecutable($migration, new MigrateMessage()))->import();
  326. $this->row = $this->state->get('qbe.current_row');
  327. if ($migration->getIdMap()->errorCount()) {
  328. $errors = iterator_to_array($migration->getIdMap()->getMessageIterator());
  329. $error = array_shift($errors);
  330. \Drupal::logger('commerce_qbe')->error($error->message);
  331. return $request;
  332. }
  333. // Let's end the import for now and we'll continue next time.
  334. break;
  335. }
  336.  
  337. $callback = $this->row->getSourceProperty('static/send_callback');
  338. if (is_callable([$this, $callback])) {
  339. $qbxml = call_user_func([$this, $callback]);
  340. $request->sendRequestXMLResult = $this->addXMLEnvelope($qbxml);
  341. return $request;
  342. }
  343.  
  344. \Drupal::logger('commerce_qbe')->error("Unable to prepare data for export. No method found for [$callback]");
  345. $this->state->get('qbe.current_row');
  346. return $request;
  347. }
  348.  
  349. /**
  350. * Add an XML envelope.
  351. *
  352. * @param string $qbxml
  353. * The qbxml.
  354. *
  355. * @return string
  356. * The xml wrapped in an envelope.
  357. */
  358. protected function addXMLEnvelope($qbxml) {
  359. return '<?xml version="1.0" encoding="utf-8"?><?qbxml version="2.0"?><QBXML><QBXMLMsgsRq onError="stopOnError">' . $qbxml . '</QBXMLMsgsRq></QBXML>';
  360. }
  361.  
  362. /**
  363. * {@inheritdoc}
  364. */
  365. public function callReceiveResponseXML(\stdClass $request) {
  366. $this->row = $this->state->get('qbe.current_row');
  367. $retry = FALSE;
  368.  
  369. // Parse any errors if we have them to decide our next action.
  370. if (!empty($request->response)) {
  371. if ($code = QbeUtilities::extractStatusCode($request->response)) {
  372. $error = [
  373. 'statusCode' => $code,
  374. 'statusMessage' => QbeUtilities::extractStatusMessage($request->response),
  375. ];
  376. $error_msg = "Response error statusCode: " . print_r($error, TRUE);
  377. \Drupal::logger('commerce_qbe_errors')->error($error_msg);
  378. // 3180 is a temporary error with no clear reason. Just retry it.
  379. if ($error['statusCode'] == "3180") {
  380. $retry = TRUE;
  381. }
  382. }
  383. }
  384.  
  385. $callback = $this->row->getSourceProperty('static/receive_callback');
  386. if (!$retry && is_callable([$this, $callback])) {
  387. call_user_func([$this, $callback], $request);
  388. }
  389.  
  390. $request->receiveResponseXMLResult = $this->getCompletionProgress();
  391.  
  392. return $request;
  393. }
  394.  
  395. /**
  396. * Update identifiers.
  397. *
  398. * @param \stdClass $request
  399. * The request.
  400. */
  401. protected function updateIdentifier(\stdClass $request) {
  402. $identifier = QbeUtilities::extractIdentifiers($request->response, $this->row->getSource()['entity_type']);
  403. if ($identifier) {
  404. /** @var \Drupal\migrate\Plugin\Migration $migration */
  405. $migration = $this->migrationPluginManager->createInstance($this->state->get('qbe.current_migration'));
  406. $migration->getIdMap()->saveIdMapping($this->row, ['uuid' => $identifier]);
  407. }
  408. }
  409.  
  410. /**
  411. * {@inheritdoc}
  412. */
  413. public function callGetLastError(\stdClass $request) {
  414. $progress = $this->getCompletionProgress();
  415.  
  416. if ($progress == 100) {
  417. $request->getLastErrorResult = 'No new exports remaining.';
  418. }
  419. else {
  420. $request->getLastErrorResult = "$progress% remaining remaining.";
  421. }
  422.  
  423. return $request;
  424. }
  425.  
  426. /**
  427. * {@inheritdoc}
  428. */
  429. public function callCloseConnection(\stdClass $request) {
  430. $this->sessionManager->closeSession();
  431. $request->closeConnectionResult = 'OK';
  432.  
  433. return $request;
  434. }
  435.  
  436. /**
  437. * Parse profile entities into a template-ready object.
  438. */
  439. protected function prepareCustomerExport() {
  440. if ($this->row->getSourceProperty('bundle') == 'customer') {
  441. $uuid = $this->row->getDestinationProperty('uuid');
  442. $addresses = $this->row->getSourceProperty('address');
  443. $address = reset($addresses);
  444. $customer = new \QuickBooks_QBXML_Object_Customer();
  445. if (QbeUtilities::isQuickbooksIdentifier($uuid)) {
  446. $customer->setListID($uuid);
  447. return $customer->asQBXML(QUICKBOOKS_QUERY_CUSTOMER);
  448. }
  449.  
  450. $address1 = $address['address_line1'];
  451. $address2 = $address['address_line2'];
  452. $address3 = '';
  453. $address4 = '';
  454. $address5 = $address['dependent_locality'];
  455. $city = $address['locality'];
  456. $state = $address['administrative_area'];
  457. $province = '';
  458. $postal_code = $address['postal_code'];
  459. $country = $address['country_code'];
  460. $customer->setBillAddress($address1, $address2, $address3, $address4, $address5, $city, $state, $province, $postal_code, $country);
  461. $customer->setFirstName($address['given_name']);
  462. $customer->setLastName($address['family_name']);
  463. $user = $this->entityTypeManager->getStorage('user')->load($this->row->getSourceProperty('uid'));
  464. $customer->setEmail($user->mail->value);
  465. return $customer->asQBXML(QUICKBOOKS_ADD_CUSTOMER);
  466. }
  467.  
  468. }
  469.  
  470. /**
  471. * Parse Order entities into a template-ready object.
  472. *
  473. * @return string
  474. * An xml export of order data.
  475. */
  476. protected function prepareOrderExport() {
  477. $isInvoice = $this->config->get('exportables')['order_type'] == 'invoices';
  478. $invoice = new \QuickBooks_QBXML_Object_Invoice();
  479. $orderId = $this->row->getSourceProperty('order_id');
  480. /** @var \Drupal\commerce_order\Entity\Order $order */
  481. $order = $this->entityTypeManager->getStorage('commerce_order')->load($orderId);
  482. /** @var \Drupal\migrate\Plugin\Migration $customerMigration */
  483. $customerMigration = $this->migrationPluginManager->createInstance('qbe_customer');
  484. /** @var \Drupal\profile\Entity\Profile $billingProfile */
  485. $billingProfile = $order->getBillingProfile();
  486. if ($db_row = $customerMigration->getIdMap()->getRowBySource(['profile_id' => $billingProfile->id()])) {
  487. $invoice->setCustomerListID($db_row['destid1']);
  488. }
  489. /** @var \Drupal\commerce_payment\Entity\PaymentInterface[] $payments */
  490. $payments = $this->entityTypeManager->getStorage('commerce_payment')->loadMultipleByOrder($order);
  491. $orderPrefix = $this->config->get('id_prefixes')['po_number_prefix'];
  492. $invoice->setRefNumber($orderPrefix . $orderId);
  493. $invoice->setTransactionDate($order->getCompletedTime());
  494. if ($billingProfile) {
  495. /** @var \Drupal\address\Plugin\Field\FieldType\AddressItem $address */
  496. $address = $billingProfile->address->get(0);
  497. $invoice->setCustomerFullName("{$address->getGivenName()} {$address->getFamilyName()}");
  498. $address1 = $address->getAddressLine1();
  499. $address2 = $address->getAddressLine2();
  500. $address3 = '';
  501. $address4 = '';
  502. $address5 = $address->getDependentLocality();
  503. $city = $address->getLocality();
  504. $state = $address->getAdministrativeArea();
  505. $province = '';
  506. $postal_code = $address->getPostalCode();
  507. $country = $address->getCountryCode();
  508. $invoice->setBillAddress($address1, $address2, $address3, $address4, $address5, $city, $state, $province, $postal_code, $country);
  509. }
  510.  
  511. if ($order->hasField('shipments')) {
  512. foreach ($order->shipments->referencedEntities() as $shipment) {
  513. /** @var \Drupal\profile\Entity\Profile $shipping_profile */
  514. if ($shippingProfile = $shipment->getShippingProfile()) {
  515. break;
  516. }
  517. }
  518. }
  519. if (!empty($shippingProfile)) {
  520. /** @var \Drupal\address\Plugin\Field\FieldType\AddressItem $address */
  521. $address = $shippingProfile->address->get(0);
  522. $address1 = $address->getAddressLine1();
  523. $address2 = $address->getAddressLine2();
  524. $address3 = '';
  525. $address4 = '';
  526. $address5 = $address->getDependentLocality();
  527. $city = $address->getLocality();
  528. $state = $address->getAdministrativeArea();
  529. $province = '';
  530. $postal_code = $address->getPostalCode();
  531. $country = $address->getCountryCode();
  532. $invoice->setShipAddress($address1, $address2, $address3, $address4, $address5, $city, $state, $province, $postal_code, $country);
  533. }
  534. foreach ($payments as $payment) {
  535. if ($gateway = $payment->getPaymentGateway()) {
  536. $paymentMethod = $gateway->getPlugin()->getDisplayLabel();
  537. }
  538. }
  539. if (!empty($paymentMethod)) {
  540. $invoice->setPaymentMethodName($paymentMethod);
  541. }
  542. /** @var \Drupal\commerce_order\Entity\OrderItem $item */
  543. foreach ($order->getItems() as $item) {
  544. $line = $isInvoice ? new \QuickBooks_QBXML_Object_Invoice_InvoiceLine() : new \QuickBooks_QBXML_Object_SalesReceipt_SalesReceiptLine();
  545. /** @var \Drupal\commerce_product\Entity\ProductVariationInterface $purchasedItem */
  546. $purchasedItem = $item->getPurchasedEntity();
  547. $line->setItemName($purchasedItem->getSku());
  548. $line->setDescription($purchasedItem->label());
  549. $line->setQuantity($item->getQuantity());
  550. $line->setAmount($item->getUnitPrice()->getNumber());
  551. if ($isInvoice) {
  552. $invoice->addInvoiceLine($line);
  553. }
  554. else {
  555. $invoice->addListItem('SalesReceiptLineAdd', $line);
  556. }
  557. }
  558.  
  559. /** @var \Drupal\commerce_order\Adjustment $adjustment */
  560. foreach ($order->getAdjustments() as $adjustment) {
  561. switch ($adjustment->getType()) {
  562. case 'tax':
  563. $taxName = $this->config->get('tax')['tax_name'];
  564. $invoice->setSalesTaxItemFullName($taxName);
  565. break;
  566.  
  567. case 'shipping':
  568. $line = $isInvoice ? new \QuickBooks_QBXML_Object_Invoice_InvoiceLine() : new \QuickBooks_QBXML_Object_SalesReceipt_SalesReceiptLine();
  569. $shippingName = $this->config->get('shipping')['shipping_service'];
  570. $shippingDescription = $this->config->get('shipping')['shipping_service_description'];
  571. $line->setItemName($shippingName);
  572. $line->setDescription($shippingDescription);
  573. $line->setQuantity(1);
  574. $line->setAmount($adjustment->getAmount()->getNumber());
  575. if ($isInvoice) {
  576. $invoice->addInvoiceLine($line);
  577. }
  578. else {
  579. $invoice->addListItem('SalesReceiptLineAdd', $line);
  580. }
  581. break;
  582. }
  583. }
  584.  
  585. return $isInvoice ? $invoice->asXML(\QUICKBOOKS_ADD_INVOICE)->asXML(\QuickBooks_XML::XML_DROP, '') : $invoice->asXML(QUICKBOOKS_ADD_SALESRECEIPT)->asXML(\QuickBooks_XML::XML_DROP, '');
  586. }
  587.  
  588. /**
  589. * Parse payment entities into a template-ready object.
  590. *
  591. * @return string
  592. * An xml export of payment data.
  593. */
  594. protected function preparePaymentExport() {
  595. $receivePayment = new \QuickBooks_QBXML_Object_ReceivePayment();
  596.  
  597. $paymentId = $this->row->getSourceProperty('payment_id');
  598. /** @var \Drupal\commerce_payment\Entity\Payment $payment */
  599. $payment = $this->entityTypeManager->getStorage('commerce_payment')->load($paymentId);
  600. $orderId = $payment->getOrderId();
  601. /** @var \Drupal\commerce_order\Entity\Order $order */
  602. $order = $this->entityTypeManager->getStorage('commerce_order')->load($orderId);
  603. /** @var \Drupal\migrate\Plugin\Migration $customerMigration */
  604. $customerMigration = $this->migrationPluginManager->createInstance('qbe_customer');
  605. /** @var \Drupal\profile\Entity\Profile $billingProfile */
  606. $billingProfile = $order->getBillingProfile();
  607. if ($db_row = $customerMigration->getIdMap()->getRowBySource(['profile_id' => $billingProfile->id()])) {
  608. $receivePayment->setCustomerListID($db_row['destid1']);
  609. }
  610. $paymentPrefix = $this->config->get('id_prefixes')['payment_prefix'];
  611. if ($paymentId = $payment->getRemoteId()) {
  612. $receivePayment->setRefNumber($paymentPrefix . $paymentId);
  613. }
  614. else {
  615. $receivePayment->setRefNumber($paymentPrefix . $payment->id());
  616. }
  617. $receivePayment->setPaymentMethodFullName($payment->getPaymentGateway()->label());
  618. $receivePayment->setTransactionDate($payment->getCompletedTime());
  619. $transactionAdd = new \QuickBooks_QBXML_Object_ReceivePayment_AppliedToTxn();
  620. /** @var \Drupal\migrate\Plugin\Migration $orderMigration */
  621. $orderMigration = $this->migrationPluginManager->createInstance('qbe_order');
  622. if ($db_row = $orderMigration->getIdMap()->getRowBySource(['order_id' => $order->id()])) {
  623. $transactionAdd->setTxnID($db_row['destid1']);
  624. $transactionAdd->setPaymentAmount($payment->getAmount()->getNumber());
  625. $receivePayment->addAppliedToTxn($transactionAdd);
  626. }
  627. else {
  628. $receivePayment->setIsAutoApply(TRUE);
  629. }
  630.  
  631. return $receivePayment->asQBXML(\QUICKBOOKS_ADD_RECEIVEPAYMENT, \QuickBooks_XML::XML_DROP, '');
  632. }
  633.  
  634. /**
  635. * Parse product variation entities into a template-ready object.
  636. *
  637. * @return string
  638. * An xml export of product variation data.
  639. */
  640. protected function prepareProductVariationExport() {
  641. $inventoryItem = new \QuickBooks_QBXML_Object_InventoryItem();
  642. $variationId = $this->row->getSourceProperty('variation_id');
  643. /** @var \Drupal\commerce_product\Entity\ProductVariation $variation */
  644. $variation = $this->entityTypeManager->getStorage('commerce_product_variation')->load($variationId);
  645. $inventoryItem->setName($variation->label());
  646. $inventoryItem->setSalesPrice($variation->getPrice()->getNumber());
  647. /** @var \Drupal\migrate\Plugin\Migration $productMigration */
  648. $productMigration = $this->migrationPluginManager->createInstance('qbe_product');
  649. /** @var \Drupal\Core\Language\LanguageManagerInterface $languageManager */
  650. $languageManager = \Drupal::service('language_manager');
  651. $langcode = $languageManager->getDefaultLanguage()->getId();
  652. if ($db_row = $productMigration->getIdMap()->getRowBySource(['product_id' => $variation->getProductId(), 'langcode' => $langcode])) {
  653. $inventoryItem->set('ParentRef ListID', $db_row['destid1']);
  654. }
  655. return $inventoryItem->asQBXML(\QUICKBOOKS_ADD_INVENTORYITEM, \QuickBooks_XML::XML_DROP, '');
  656. }
  657.  
  658. /**
  659. * Parse product entities into a template-ready object.
  660. *
  661. * @return string
  662. * An xml export of product data.
  663. */
  664. protected function prepareProductExport() {
  665. $inventoryItem = new \QuickBooks_QBXML_Object_InventoryItem();
  666. $productId = $this->row->getSourceProperty('product_id');
  667. /** @var \Drupal\commerce_product\Entity\Product $product */
  668. $product = $this->entityTypeManager->getStorage('commerce_product')->load($productId);
  669. $inventoryItem->setName($product->label());
  670. return $inventoryItem->asQBXML(\QUICKBOOKS_ADD_INVENTORYITEM, \QuickBooks_XML::XML_DROP, '');
  671. }
  672.  
  673. }
Add Comment
Please, Sign In to add comment