PageRenderTime 64ms CodeModel.GetById 31ms RepoModel.GetById 0ms app.codeStats 0ms

/wp-content/plugins/wp-lister-for-ebay/classes/model/TransactionsModel.php

https://bitbucket.org/sanders_nick/my-maxi-skirt
PHP | 366 lines | 222 code | 90 blank | 54 comment | 25 complexity | 28e425ad72a4669b5986ca29f2e76ae7 MD5 | raw file
Possible License(s): GPL-2.0, BSD-3-Clause, AGPL-1.0, GPL-3.0, LGPL-2.1
  1. <?php
  2. /**
  3. * TransactionsModel class
  4. *
  5. * responsible for managing transactions and talking to ebay
  6. *
  7. */
  8. // list of used EbatNs classes:
  9. // require_once 'EbatNs_ServiceProxy.php';
  10. // require_once 'EbatNs_DatabaseProvider.php';
  11. // require_once 'EbatNs_Logger.php';
  12. // require_once 'GetSellerTransactionsRequestType.php';
  13. // require_once 'GetSellerTransactionsResponseType.php';
  14. class TransactionsModel extends WPL_Model {
  15. var $_session;
  16. var $_cs;
  17. function TransactionsModel() {
  18. global $wpl_logger;
  19. $this->logger = &$wpl_logger;
  20. global $wpdb;
  21. $this->tablename = $wpdb->prefix . 'ebay_transactions';
  22. }
  23. function updateTransactions( $session, $days = null ) {
  24. $this->logger->info('updateTransactions('.$days.')');
  25. $this->initServiceProxy($session);
  26. // set request handler
  27. $this->_cs->setHandler( 'TransactionType', array( & $this, 'handleTransactionType' ) );
  28. // build request
  29. $req = new GetSellerTransactionsRequestType();
  30. // period 30 days, which is the maximum allowed
  31. $now = time();
  32. $lastdate = $this->getDateOfLastTransaction();
  33. $this->logger->info('getDateOfLastTransaction() returned: '.$lastdate);
  34. if ($lastdate) $lastdate = mysql2date('U', $lastdate);
  35. // if last date is older than 30 days, fall back to default
  36. if ( $lastdate < $now - 3600 * 24 * 30 ) {
  37. $this->logger->info('resetting lastdate - fall back default ');
  38. $lastdate = false;
  39. }
  40. // parameter $days has priority
  41. if ( $days ) {
  42. $req->NumberOfDays = $days;
  43. // default: transactions since last change
  44. } elseif ( $lastdate ) {
  45. $req->ModTimeFrom = gmdate( 'Y-m-d H:i:s', $lastdate );
  46. $req->ModTimeTo = gmdate( 'Y-m-d H:i:s', time() );
  47. // fallback: last 7 days (max allowed by ebay: 30 days)
  48. } else {
  49. $days = 7;
  50. $req->NumberOfDays = $days;
  51. }
  52. $this->logger->info('lastdate: '.$lastdate);
  53. $this->logger->info('ModTimeFrom: '.$req->ModTimeFrom);
  54. $this->logger->info('ModTimeTo: '.$req->ModTimeTo);
  55. $req->DetailLevel = $Facet_DetailLevelCodeType->ReturnAll;
  56. // download the data
  57. $res = $this->_cs->GetSellerTransactions( $req );
  58. // handle response and check if successful
  59. if ( $this->handleResponse($res) ) {
  60. $this->logger->info( "Transactions updated successfully." );
  61. } else {
  62. $this->logger->error( "Error on transactions update".print_r( $res, 1 ) );
  63. }
  64. }
  65. function updateSingleTransaction( $session, $id ) {
  66. $this->initServiceProxy($session);
  67. // get transaction item to update
  68. $transaction = $this->getItem( $id );
  69. // build request
  70. $req = new GetItemTransactionsRequestType();
  71. $req->ItemID = $transaction['item_id'];
  72. $req->TransactionID = $transaction['transaction_id'];
  73. $this->logger->info('ItemID: '.$req->ItemID);
  74. $this->logger->info('TransactionID: '.$req->TransactionID);
  75. $req->DetailLevel = $Facet_DetailLevelCodeType->ReturnAll;
  76. // download the data
  77. $res = $this->_cs->GetItemTransactions( $req );
  78. // handle response and check if successful
  79. if ( $this->handleResponse($res) ) {
  80. // since GetItemTransactions returns the Item object outside of the Transaction object,
  81. // we need to rearrange it before we pass it to handleTransactionType()
  82. $Transaction = $res->TransactionArray[0];
  83. $Transaction->Item = $res->Item;
  84. $this->handleTransactionType( 'TransactionType', $Transaction );
  85. $this->logger->info( sprintf("Transaction %s updated successfully.", $req->TransactionID ) );
  86. } else {
  87. $this->logger->error( "Error on transactions update".print_r( $res, 1 ) );
  88. }
  89. }
  90. function handleTransactionType( $type, & $Detail ) {
  91. //global $wpdb;
  92. //#type $Detail TransactionType
  93. $this->logger->debug( 'handleTransactionType()'.print_r( $Detail, 1 ) );
  94. // map TransactionType to DB columns
  95. $data = $this->mapItemDetailToDB( $Detail );
  96. if (!$data) return true;
  97. // check if item has variation
  98. $hasVariations = false;
  99. $VariationSpecifics = array();
  100. if ( is_object( @$Detail->Variation ) ) {
  101. foreach ($Detail->Variation->VariationSpecifics as $spec) {
  102. $VariationSpecifics[ $spec->Name ] = $spec->Value[0];
  103. }
  104. $hasVariations = true;
  105. }
  106. // handle variation
  107. if ( $hasVariations ) {
  108. // use variation title
  109. $data['item_title'] = $Detail->Variation->VariationTitle;
  110. }
  111. $this->insertOrUpdate( $data, $hasVariations, $VariationSpecifics );
  112. // this will remove item from result
  113. return true;
  114. }
  115. function insertOrUpdate( $data, $hasVariations, $VariationSpecifics ) {
  116. global $wpdb;
  117. // try to get existing transaction by transaction id
  118. $transaction = $this->getTransactionByTransactionID( $data['transaction_id'] );
  119. if ( $transaction ) {
  120. // update existing transaction
  121. $this->logger->info( 'update transaction #'.$data['transaction_id'].' for item #'.$data['item_id'] );
  122. $wpdb->update( $this->tablename, $data, array( 'transaction_id' => $data['transaction_id'] ) );
  123. } else {
  124. // create new transaction
  125. $this->logger->info( 'insert transaction #'.$data['transaction_id'].' for item #'.$data['item_id'] );
  126. $wpdb->insert( $this->tablename, $data );
  127. $id = $wpdb->insert_id;
  128. // update listing sold quantity and status
  129. // get current values from db
  130. $quantity_purchased = $data['quantity'];
  131. $quantity_total = $wpdb->get_var( 'SELECT quantity FROM '.$wpdb->prefix.'ebay_auctions WHERE ebay_id = '.$data['item_id'] );
  132. $quantity_sold = $wpdb->get_var( 'SELECT quantity_sold FROM '.$wpdb->prefix.'ebay_auctions WHERE ebay_id = '.$data['item_id'] );
  133. // increase the listing's quantity_sold
  134. $quantity_sold = $quantity_sold + $quantity_purchased;
  135. $wpdb->update( $wpdb->prefix.'ebay_auctions',
  136. array( 'quantity_sold' => $quantity_sold ),
  137. array( 'ebay_id' => $data['item_id'] )
  138. );
  139. // mark listing as sold when last item is sold
  140. if ( $quantity_sold == $quantity_total ) {
  141. $wpdb->update( $wpdb->prefix.'ebay_auctions',
  142. array( 'status' => 'sold', 'date_finished' => $data['date_created'], ),
  143. array( 'ebay_id' => $data['item_id'] )
  144. );
  145. $this->logger->info( 'marked item #'.$data['item_id'].' as SOLD ');
  146. }
  147. }
  148. }
  149. function mapItemDetailToDB( $Detail ) {
  150. //#type $Detail TransactionType
  151. $data['item_id'] = $Detail->Item->ItemID;
  152. $data['transaction_id'] = $Detail->TransactionID;
  153. $data['date_created'] = $Detail->CreatedDate;
  154. $data['price'] = $Detail->TransactionPrice->value;
  155. $data['quantity'] = $Detail->QuantityPurchased;
  156. $data['buyer_userid'] = $Detail->Buyer->UserID;
  157. $data['buyer_name'] = $Detail->Buyer->RegistrationAddress->Name;
  158. $data['buyer_email'] = $Detail->Buyer->Email;
  159. $data['eBayPaymentStatus'] = $Detail->Status->eBayPaymentStatus;
  160. $data['CheckoutStatus'] = $Detail->Status->CheckoutStatus;
  161. $data['ShippingService'] = $Detail->ShippingServiceSelected->ShippingService;
  162. //$data['ShippingAddress_Country'] = $Detail->Buyer->BuyerInfo->ShippingAddress->Country;
  163. //$data['ShippingAddress_Zip'] = $Detail->Buyer->BuyerInfo->ShippingAddress->PostalCode;
  164. $data['ShippingAddress_City'] = $Detail->Buyer->BuyerInfo->ShippingAddress->CityName;
  165. $data['PaymentMethod'] = $Detail->Status->PaymentMethodUsed;
  166. $data['CompleteStatus'] = $Detail->Status->CompleteStatus;
  167. $data['LastTimeModified'] = $Detail->Status->LastTimeModified;
  168. $listingsModel = new ListingsModel();
  169. $listingItem = $listingsModel->getItemByEbayID( $Detail->Item->ItemID );
  170. // skip items not found in listings
  171. if ( $listingItem ) {
  172. $data['item_title'] = $listingItem->auction_title;
  173. $this->logger->info( "Transaction for '".$data['item_title']."' - item #".$Detail->Item->ItemID );
  174. } else {
  175. $this->logger->info( "skipped transaction ".$Detail->TransactionID." for foreign item #".$Detail->Item->ItemID );
  176. return false;
  177. }
  178. // use buyer name from shipping address if registration address is empty
  179. if ( $data['buyer_name'] == '' ) {
  180. $data['buyer_name'] = $Detail->Buyer->BuyerInfo->ShippingAddress->Name;
  181. }
  182. // save GetSellerTransactions reponse in details
  183. $data['details'] = $this->encodeObject( $Detail );
  184. return $data;
  185. }
  186. /* the following methods could go into another class, since they use wpdb instead of EbatNs_DatabaseProvider */
  187. function getAll() {
  188. global $wpdb;
  189. $profiles = $wpdb->get_results( "
  190. SELECT *
  191. FROM $this->tablename
  192. ORDER BY id DESC
  193. ", ARRAY_A );
  194. return $profiles;
  195. }
  196. function getItem( $id ) {
  197. global $wpdb;
  198. $item = $wpdb->get_row( "
  199. SELECT *
  200. FROM $this->tablename
  201. WHERE id = '$id'
  202. ", ARRAY_A );
  203. // decode TransactionType object with eBay classes loaded
  204. $item['details'] = $this->decodeObject( $item['details'], false, true );
  205. return $item;
  206. }
  207. function getTransactionByTransactionID( $transaction_id ) {
  208. global $wpdb;
  209. $transaction = $wpdb->get_row( "
  210. SELECT *
  211. FROM $this->tablename
  212. WHERE transaction_id = '$transaction_id'
  213. ", ARRAY_A );
  214. return $transaction;
  215. }
  216. function getTransactionByOrderID( $wp_order_id ) {
  217. global $wpdb;
  218. $transaction = $wpdb->get_row( "
  219. SELECT *
  220. FROM $this->tablename
  221. WHERE wp_order_id = '$wp_order_id'
  222. ", ARRAY_A );
  223. return $transaction;
  224. }
  225. function getDateOfLastTransaction() {
  226. global $wpdb;
  227. return $wpdb->get_var( "
  228. SELECT LastTimeModified
  229. FROM $this->tablename
  230. ORDER BY LastTimeModified DESC LIMIT 1
  231. " );
  232. }
  233. function deleteItem( $id ) {
  234. global $wpdb;
  235. $wpdb->query( "
  236. DELETE
  237. FROM $this->tablename
  238. WHERE id = '$id'
  239. " );
  240. }
  241. function updateWpOrderID( $id, $wp_order_id ) {
  242. global $wpdb;
  243. $wpdb->query( "
  244. UPDATE $this->tablename
  245. SET wp_order_id = '$wp_order_id'
  246. WHERE id = '$id'
  247. " );
  248. }
  249. function getPageItems( $current_page, $per_page ) {
  250. global $wpdb;
  251. $orderby = (!empty($_REQUEST['orderby'])) ? $_REQUEST['orderby'] : 'id'; //If no sort, default to title
  252. $order = (!empty($_REQUEST['order'])) ? $_REQUEST['order'] : 'desc'; //If no order, default to asc
  253. $offset = ( $current_page - 1 ) * $per_page;
  254. // get items
  255. $items = $wpdb->get_results("
  256. SELECT *
  257. FROM $this->tablename
  258. ORDER BY $orderby $order
  259. LIMIT $offset, $per_page
  260. ", ARRAY_A);
  261. // get total items count - if needed
  262. if ( ( $current_page == 1 ) && ( count( $items ) < $per_page ) ) {
  263. $this->total_items = count( $items );
  264. } else {
  265. $this->total_items = $wpdb->get_var("
  266. SELECT COUNT(*)
  267. FROM $this->tablename
  268. ORDER BY $orderby $order
  269. ");
  270. }
  271. // foreach( $items as &$profile ) {
  272. // $profile['details'] = $this->decodeObject( $profile['details'] );
  273. // }
  274. return $items;
  275. }
  276. }