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

Language PHP Lines 367
MD5 Hash 28e425ad72a4669b5986ca29f2e76ae7 Estimated Cost $5,537 (why?)
Repository https://bitbucket.org/sanders_nick/my-maxi-skirt.git View Raw File
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
<?php
/**
 * TransactionsModel class
 *
 * responsible for managing transactions and talking to ebay
 * 
 */

// list of used EbatNs classes:

// require_once 'EbatNs_ServiceProxy.php';
// require_once 'EbatNs_DatabaseProvider.php';
// require_once 'EbatNs_Logger.php';

// require_once 'GetSellerTransactionsRequestType.php';
// require_once 'GetSellerTransactionsResponseType.php';

class TransactionsModel extends WPL_Model {
	var $_session;
	var $_cs;

	function TransactionsModel() {
		global $wpl_logger;
		$this->logger = &$wpl_logger;

		global $wpdb;
		$this->tablename = $wpdb->prefix . 'ebay_transactions';
	}


	function updateTransactions( $session, $days = null ) {
		$this->logger->info('updateTransactions('.$days.')');

		$this->initServiceProxy($session);

		// set request handler
		$this->_cs->setHandler( 'TransactionType', array( & $this, 'handleTransactionType' ) );

		// build request
		$req = new GetSellerTransactionsRequestType();

		// period 30 days, which is the maximum allowed
		$now = time();
		$lastdate = $this->getDateOfLastTransaction();
		$this->logger->info('getDateOfLastTransaction() returned: '.$lastdate);
		if ($lastdate) $lastdate = mysql2date('U', $lastdate);

		// if last date is older than 30 days, fall back to default
		if ( $lastdate < $now - 3600 * 24 * 30 ) {
			$this->logger->info('resetting lastdate - fall back default ');
			$lastdate = false;
		} 

		// parameter $days has priority
		if ( $days ) {
			$req->NumberOfDays = $days;

		// default: transactions since last change
		} elseif ( $lastdate ) {
			$req->ModTimeFrom = gmdate( 'Y-m-d H:i:s', $lastdate );
			$req->ModTimeTo   = gmdate( 'Y-m-d H:i:s', time() );

		// fallback: last 7 days (max allowed by ebay: 30 days)
		} else {
			$days = 7;
			$req->NumberOfDays = $days;
		}

		$this->logger->info('lastdate: '.$lastdate);
		$this->logger->info('ModTimeFrom: '.$req->ModTimeFrom);
		$this->logger->info('ModTimeTo: '.$req->ModTimeTo);

		$req->DetailLevel = $Facet_DetailLevelCodeType->ReturnAll;

		// download the data
		$res = $this->_cs->GetSellerTransactions( $req );

		// handle response and check if successful
		if ( $this->handleResponse($res) ) {
			$this->logger->info( "Transactions updated successfully." );
		} else {
			$this->logger->error( "Error on transactions update".print_r( $res, 1 ) );			
		}
	}

	function updateSingleTransaction( $session, $id ) {

		$this->initServiceProxy($session);

		// get transaction item to update
		$transaction = $this->getItem( $id );

		// build request
		$req = new GetItemTransactionsRequestType();
		$req->ItemID 		= $transaction['item_id'];
		$req->TransactionID = $transaction['transaction_id'];

		$this->logger->info('ItemID: '.$req->ItemID);
		$this->logger->info('TransactionID: '.$req->TransactionID);

		$req->DetailLevel = $Facet_DetailLevelCodeType->ReturnAll;

		// download the data
		$res = $this->_cs->GetItemTransactions( $req );

		// handle response and check if successful
		if ( $this->handleResponse($res) ) {

			// since GetItemTransactions returns the Item object outside of the Transaction object, 
			// we need to rearrange it before we pass it to handleTransactionType()
			$Transaction = $res->TransactionArray[0];
			$Transaction->Item = $res->Item;
			$this->handleTransactionType( 'TransactionType', $Transaction );

			$this->logger->info( sprintf("Transaction %s updated successfully.", $req->TransactionID ) );
		} else {
			$this->logger->error( "Error on transactions update".print_r( $res, 1 ) );			
		}
	}

	function handleTransactionType( $type, & $Detail ) {
		//global $wpdb;
		//#type $Detail TransactionType
		$this->logger->debug( 'handleTransactionType()'.print_r( $Detail, 1 ) );

		// map TransactionType to DB columns
		$data = $this->mapItemDetailToDB( $Detail );
		if (!$data) return true;


		// check if item has variation 
		$hasVariations = false;
		$VariationSpecifics = array();
        if ( is_object( @$Detail->Variation ) ) {
            foreach ($Detail->Variation->VariationSpecifics as $spec) {
                $VariationSpecifics[ $spec->Name ] = $spec->Value[0];
            }
			$hasVariations = true;
        } 

		// handle variation
		if ( $hasVariations ) {
			
			// use variation title
			$data['item_title'] = $Detail->Variation->VariationTitle;

		}


		$this->insertOrUpdate( $data, $hasVariations, $VariationSpecifics );

		// this will remove item from result
		return true;
	}
	function insertOrUpdate( $data, $hasVariations, $VariationSpecifics ) {
		global $wpdb;

		// try to get existing transaction by transaction id
		$transaction = $this->getTransactionByTransactionID( $data['transaction_id'] );
		if ( $transaction ) {
			// update existing transaction
			$this->logger->info( 'update transaction #'.$data['transaction_id'].' for item #'.$data['item_id'] );
			$wpdb->update( $this->tablename, $data, array( 'transaction_id' => $data['transaction_id'] ) );
		} else {
			// create new transaction
			$this->logger->info( 'insert transaction #'.$data['transaction_id'].' for item #'.$data['item_id'] );
			$wpdb->insert( $this->tablename, $data );
			$id = $wpdb->insert_id;


			// update listing sold quantity and status

			// get current values from db
			$quantity_purchased = $data['quantity'];
			$quantity_total = $wpdb->get_var( 'SELECT quantity FROM '.$wpdb->prefix.'ebay_auctions WHERE ebay_id = '.$data['item_id'] );
			$quantity_sold = $wpdb->get_var( 'SELECT quantity_sold FROM '.$wpdb->prefix.'ebay_auctions WHERE ebay_id = '.$data['item_id'] );

			// increase the listing's quantity_sold
			$quantity_sold = $quantity_sold + $quantity_purchased;
			$wpdb->update( $wpdb->prefix.'ebay_auctions', 
				array( 'quantity_sold' => $quantity_sold ), 
				array( 'ebay_id' => $data['item_id'] ) 
			);

			// mark listing as sold when last item is sold
			if ( $quantity_sold == $quantity_total ) {
				$wpdb->update( $wpdb->prefix.'ebay_auctions', 
					array( 'status' => 'sold', 'date_finished' => $data['date_created'], ), 
					array( 'ebay_id' => $data['item_id'] ) 
				);
				$this->logger->info( 'marked item #'.$data['item_id'].' as SOLD ');
			}



		}

	}

	function mapItemDetailToDB( $Detail ) {
		//#type $Detail TransactionType

		$data['item_id']                   = $Detail->Item->ItemID;
		$data['transaction_id']            = $Detail->TransactionID;
		$data['date_created']              = $Detail->CreatedDate;
		$data['price']                     = $Detail->TransactionPrice->value;
		$data['quantity']                  = $Detail->QuantityPurchased;
		$data['buyer_userid']              = $Detail->Buyer->UserID;
		$data['buyer_name']                = $Detail->Buyer->RegistrationAddress->Name;
		$data['buyer_email']               = $Detail->Buyer->Email;
		
		$data['eBayPaymentStatus']         = $Detail->Status->eBayPaymentStatus;
		$data['CheckoutStatus']            = $Detail->Status->CheckoutStatus;
		$data['ShippingService']           = $Detail->ShippingServiceSelected->ShippingService;
		//$data['ShippingAddress_Country'] = $Detail->Buyer->BuyerInfo->ShippingAddress->Country;
		//$data['ShippingAddress_Zip']     = $Detail->Buyer->BuyerInfo->ShippingAddress->PostalCode;
		$data['ShippingAddress_City']      = $Detail->Buyer->BuyerInfo->ShippingAddress->CityName;
		$data['PaymentMethod']             = $Detail->Status->PaymentMethodUsed;
		$data['CompleteStatus']            = $Detail->Status->CompleteStatus;
		$data['LastTimeModified']          = $Detail->Status->LastTimeModified;

		$listingsModel = new ListingsModel();
		$listingItem = $listingsModel->getItemByEbayID( $Detail->Item->ItemID );

		// skip items not found in listings
		if ( $listingItem ) {
			$data['item_title'] = $listingItem->auction_title;
			$this->logger->info( "Transaction for '".$data['item_title']."' - item #".$Detail->Item->ItemID );
		} else {
			$this->logger->info( "skipped transaction ".$Detail->TransactionID." for foreign item #".$Detail->Item->ItemID );			
			return false;
		}


		// use buyer name from shipping address if registration address is empty
		if ( $data['buyer_name'] == '' ) {
			$data['buyer_name']            = $Detail->Buyer->BuyerInfo->ShippingAddress->Name;
		}


        // save GetSellerTransactions reponse in details
		$data['details'] = $this->encodeObject( $Detail );

		return $data;
	}





	/* the following methods could go into another class, since they use wpdb instead of EbatNs_DatabaseProvider */

	function getAll() {
		global $wpdb;
		$profiles = $wpdb->get_results( "
			SELECT *
			FROM $this->tablename
			ORDER BY id DESC
		", ARRAY_A );

		return $profiles;
	}

	function getItem( $id ) {
		global $wpdb;

		$item = $wpdb->get_row( "
			SELECT *
			FROM $this->tablename
			WHERE id = '$id'
		", ARRAY_A );

		// decode TransactionType object with eBay classes loaded
		$item['details'] = $this->decodeObject( $item['details'], false, true );

		return $item;
	}

	function getTransactionByTransactionID( $transaction_id ) {
		global $wpdb;

		$transaction = $wpdb->get_row( "
			SELECT *
			FROM $this->tablename
			WHERE transaction_id = '$transaction_id'
		", ARRAY_A );

		return $transaction;
	}
	function getTransactionByOrderID( $wp_order_id ) {
		global $wpdb;

		$transaction = $wpdb->get_row( "
			SELECT *
			FROM $this->tablename
			WHERE wp_order_id = '$wp_order_id'
		", ARRAY_A );

		return $transaction;
	}

	function getDateOfLastTransaction() {
		global $wpdb;
		return $wpdb->get_var( "
			SELECT LastTimeModified
			FROM $this->tablename
			ORDER BY LastTimeModified DESC LIMIT 1
		" );
	}

	function deleteItem( $id ) {
		global $wpdb;
		$wpdb->query( "
			DELETE
			FROM $this->tablename
			WHERE id = '$id'
		" );
	}

	function updateWpOrderID( $id, $wp_order_id ) {
		global $wpdb;
		$wpdb->query( "
			UPDATE $this->tablename
			SET wp_order_id = '$wp_order_id'
			WHERE id = '$id'
		" );
	}


	function getPageItems( $current_page, $per_page ) {
		global $wpdb;

        $orderby = (!empty($_REQUEST['orderby'])) ? $_REQUEST['orderby'] : 'id'; //If no sort, default to title
        $order = (!empty($_REQUEST['order'])) ? $_REQUEST['order'] : 'desc'; //If no order, default to asc
        $offset = ( $current_page - 1 ) * $per_page;

        // get items
		$items = $wpdb->get_results("
			SELECT *
			FROM $this->tablename
			ORDER BY $orderby $order
            LIMIT $offset, $per_page
		", ARRAY_A);

		// get total items count - if needed
		if ( ( $current_page == 1 ) && ( count( $items ) < $per_page ) ) {
			$this->total_items = count( $items );
		} else {
			$this->total_items = $wpdb->get_var("
				SELECT COUNT(*)
				FROM $this->tablename
				ORDER BY $orderby $order
			");			
		}

		// foreach( $items as &$profile ) {
		// 	$profile['details'] = $this->decodeObject( $profile['details'] );
		// }

		return $items;
	}




}
Back to Top