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