annamaria-daneswood-25102012 /administrator/components/com_virtuemart/classes/ps_order_booking.php

Language PHP Lines 484
MD5 Hash 0e36e1e3ad0dd29eff6a9e15800a462c Estimated Cost $8,489 (why?)
Repository https://bitbucket.org/dgough/annamaria-daneswood-25102012.git View Raw File View Project SPDX
  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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
<?php
if( !defined( '_VALID_MOS' ) && !defined( '_JEXEC' ) ) die( 'Direct Access to '.basename(__FILE__).' is not allowed.' );

class ps_order_booking {
	
	var $order_id;
	
	function validate_add(&$d) {
		
		if(!$d['property_id']){
			$GLOBALS['vmLogger']->err('You must supply a property id.');
		}
		
		return true;
	}
	
	function validate_update(&$d) {
		global $VM_LANG;
		
		if(!$d['property_id']){
			$GLOBALS['vmLogger']->err('You must supply a property id.');
		}
				
		return true;		
	}
	
	function get_order_number($user_id) {

		/* Generated a unique order number */

		$str = session_id();
		$str .= (string)time();

		$order_number = $user_id .'_'. md5($str);

		return($order_number);
	}
	
	function add(&$d) {
		global $VM_LANG, $ps_booking, $mosConfig_offset;
		
		$timestamp = time() + ($mosConfig_offset*60*60);
		
		$db = new ps_DB;
		$ps_vendor_id = $_SESSION["ps_vendor_id"];
		
		if (!$this->validate_add($d)) {
			return false;
		}
		
		if ($d['user_id']) {
			$dbui = new ps_DB();
			$dbui->query('select user_info_id from #__{vm}_user_info where user_id='.$d['user_id'].' and address_type=\'BT\'');
			$dbui->next_record();
		}
				
		// Get the IP Address
		if (!empty($_SERVER['REMOTE_ADDR'])) {
			$ip = $_SERVER['REMOTE_ADDR'];
		}
		else {
			$ip = 'unknown';
		}

		
		// Collect all fields and values to store them!
		$fields = array(
			'user_id' => $d['user_id'], 
			'vendor_id' => $_SESSION["ps_vendor_id"], 
			'order_number' => $this->get_order_number($d['user_id']), 
			'user_info_id' =>  $dbui->f('user_info_id'), 
			'ship_method_id' => @urldecode($d["shipping_rate_id"]),
			'order_total' => $ps_booking->total, 
			'order_subtotal' => $ps_booking->subtotal, 
			'order_tax' => $ps_booking->tax, 
			'order_currency' => $GLOBALS['product_currency'], 
			'order_status' => $d['order_status'], 
			'cdate' => $timestamp,
			'mdate' => $timestamp,
			'customer_note' => htmlspecialchars(strip_tags($d['order_comment']), ENT_QUOTES ),	//Probably should provide a notes field
			'ip_address' => $ip
			);

		// Insert the main order information
		$db->buildQuery( 'INSERT', '#__{vm}_orders', $fields );
		
		if (!$db->query()){
			$GLOBALS['vmLogger']->err('Unable to update the order details');
			return false;
		} else {
			$this->order_id = $db->last_insert_id();
		}
		
		if (isset($this->order_id) && $this->order_id!='') {
			/**
			 * Set the booking details
			 */
			$fields = array('order_id' => $this->order_id,
							'property_id' => $ps_booking->property_id,
							'people' => $ps_booking->people,
							'arrival' => $ps_booking->dateFrom,
							'departure' => $ps_booking->dateTo,
							'total' => $ps_booking->total,
							'subtotal' => $ps_booking->subtotal,
							'tax_total' => $ps_booking->tax,
							'tax_state' => $ps_booking->tax_state,
							'tax_resort' => $ps_booking->tax_resort,
							'original' => $ps_booking->original,
							'insurance' => $ps_booking->securityDeposit,
							'cleaning' => $ps_booking->cleaning
							);
			
			$db->buildQuery('INSERT', '#__{vm}_order_booking', $fields);
			
			if( !$db->query() ){
				$GLOBALS['vmLogger']->err('Unable to add the booking details');
				return false;
			}
		} else {
			$GLOBALS['vmLogger']->err('Unable to add the booking details');
			return false;
		}
				
				
		/**
		 * Loop through and save the stage payment info
		 */		
		
		$payment_stages = $ps_booking->getStagePayment();			
		foreach($payment_stages->stages as $payment){
				
			// Payment number is encrypted using mySQL encryption functions.
			$fields = array(
						'order_id' => $this->order_id,						
						'payment_amount' => $payment->payment_amount,
						'payment_due' => $payment->payment_due,							
						'payment_stage' => $payment->payment_stage							
					  );							
			
			//Add to DB
			$db->buildQuery( 'INSERT', '#__{vm}_order_payment', $fields, '' );
			$db->query();
		}
		
		
		/**
		 * Update the Order History
		 */
		
		$notify_customer = empty($d['notify_customer']) ? "N" : $d['notify_customer'];
		if ($notify_customer=="Y" ) {
			$notify_customer=1;
		} else {
			$notify_customer=0;
		}
		
		//Set the timestamp
		$timestamp = time() + ($mosConfig_offset*60*60);
		
		$fields = array( 'order_id' => $this->order_id,
						'order_status_code' => $d["order_status"],
						'date_added' => date("Y-m-d G:i:s", $timestamp),
						'customer_notified' => $notify_customer,
						'comments' => $d['order_comment'],
						'booking_serialized' => serialize($ps_booking)
						);
		
		$db->buildQuery('INSERT', '#__{vm}_order_history', $fields );
		
		if (!$db->query()) {
			$GLOBALS['vmLogger']->err('Unable to update the order history');
			return false;
		}
		return true;
	}
	
	/**
	 * Updates an Order Status
	 *
	 * @param array $d
	 * @return boolean
	 */
	function update(&$d) {
		global $VM_LANG, $ps_booking, $mosConfig_offset;
		
		$timestamp = time() + ($mosConfig_offset*60*60);
		
		$db = new ps_DB;
		$ps_vendor_id = $_SESSION["ps_vendor_id"];
		
		if (!$this->validate_update($d)) {
			return false;
		}
		
		/**
		 * Update the final stage payment if required
		 */
		
		require_once(CLASSPATH.'ps_payments.php');
		$psp = new ps_payments();
		
		$stages = $psp->getStagePayments(null, $d['order_id']);
		$final_stage = $stages->stages[ count( $stages->stages ) - 1 ];
		$final_cleared = $final_stage->payment_submitted;
		
		if ($final_cleared) {
			$GLOBALS['vmLogger']->err('Unable to update the final payment stage, payment already recieved');
		} else {
			
			$old_total = 0;
			
			foreach ($stages->stages as $p_stage) {
				$old_total += $p_stage->payment_amount;
			}
			
			if ($old_total != $ps_booking->total) {
				
				$difference = $old_total - $ps_booking->total;
				
				if ($difference > $final_stage->payment_amount) {
					$difference = $final_stage->payment_amount - 1;
					$_REQUEST['use_new_price'] = 1;
					$_REQUEST['new_total'] = $old_total - ($final_stage->payment_amount + 1);
					$ps_booking->setPrice();
					$GLOBALS['vmLogger']->err('Price reduction greater than final stage payment amount. Final stage payment set to 1');
				}
				
				$new_payment = $final_stage->payment_amount - $difference;
				
				$stage_field = array('payment_amount' => $new_payment);
				
				$db->buildQuery('UPDATE', '#__{vm}_order_payment', $stage_field, "WHERE payment_id=".$final_stage->payment_id);
				
				if (!$db->query()) {
					$GLOBALS['vmLogger']->err('Unable to update the stage payment details');
					return false;
				}
				
			}
			
		}
		
		/**
		 * update the orders table
		 */
		$order_fields = array('order_total' => $ps_booking->total,
							'order_subtotal' => $ps_booking->subtotal,
							'order_tax' => $ps_booking->tax,
							'order_status' => $d['order_status'],
							'mdate' => $timestamp
							);
		
		$db->buildQuery('UPDATE', '#__{vm}_orders', $order_fields, "WHERE order_id=".$d['order_id'] );
		
		if (!$db->query()){
			$GLOBALS['vmLogger']->err('Unable to update the order details');
			return false;
		}

		
		/**
		 * Update the booking details
		 */
		$fields = array('arrival' => $ps_booking->dateFrom,
						'departure' => $ps_booking->dateTo,
						'people' => vmGet($d,'people'),
						'total' => $ps_booking->total,
						'subtotal' => $ps_booking->subtotal,
						'tax_total' => $ps_booking->tax,
						'tax_state' => $ps_booking->tax_state,
						'tax_resort' => $ps_booking->tax_resort,
						'original' => $ps_booking->original
						);
		
		$db->buildQuery('UPDATE', '#__{vm}_order_booking', $fields, "WHERE order_id=".$d['order_id'] );
		
		if( !$db->query() ){
			$GLOBALS['vmLogger']->err('Unable to update the booking details');
			return false;			
		}
				
		/**
		 * Update the Order History
		 */
		
		$notify_customer = empty($d['notify_customer']) ? "N" : $d['notify_customer'];
		if( $notify_customer=="Y" ) {
			$notify_customer=1; 
		}
		else {
			$notify_customer=0;
		}
		
		//Set the timestamp
		$timestamp = time() + ($mosConfig_offset*60*60);
		
		$fields = array( 'order_id' => $d["order_id"],
									'order_status_code' => $d["order_status"],
									'date_added' => date("Y-m-d G:i:s", $timestamp),
									'customer_notified' => $notify_customer,
									'comments' => $d['order_comment'],
									'booking_serialized' => serialize($ps_booking)
						);
					
		$db->buildQuery('INSERT', '#__{vm}_order_history', $fields );
		
		if (!$db->query()) {
			$GLOBALS['vmLogger']->err('Unable to update the order history');
			return false;
		} 
		return true;
	}
	
	
	/**
	* Controller for Deleting Records.
	*/
	function delete(&$d) {

		if (!$this->validate_delete($d)) {
			return False;
		}
		$record_id = $d["order_status_id"];

		if( is_array( $record_id)) {
			foreach( $record_id as $record) {
				if( !$this->delete_record( $record, $d ))
				return false;
			}
			return true;
		}
		else {
			return $this->delete_record( $record_id, $d );
		}
	}
	
	function delete_record( $record_id, &$d ) {
		global $db;
		$ps_vendor_id = $_SESSION["ps_vendor_id"];

		$q = 'DELETE FROM `'.$this->_table_name.'` WHERE order_status_id='.(int)$record_id;
		$q .= " AND vendor_id='$ps_vendor_id'";
		
		return $db->query($q);
	}
	
	
	function countOrders($state = '', $vbDateFrom = '', $vbDateTo = '', $property_id = ''){
		
		$db = new ps_DB();
		
		$count = "SELECT count(*) as num_rows FROM #__{vm}_orders AS `order`
				  LEFT JOIN #__{vm}_order_booking AS booking ON booking.order_id = order.order_id
				  LEFT JOIN #__hp_properties AS p ON p.id = booking.property_id 
				  LEFT JOIN #__{vm}_user_info AS u ON u.user_id = order.user_id
				  WHERE order.order_id = booking.order_id AND ";
		$count .= $this->getOrdersQuery($state, $vbDateFrom, $vbDateTo, $property_id);
		
		$db->query($count);
		$db->next_record();
		
		return $db->f("num_rows");		
	}
	
	
	function getOrders($state = '', $vbDateFrom = '', $vbDateTo = '', $property_id = '', $showAllProps = 0, $onlyEnding = false){
		
		global $limitstart, $limit, $page;

		$db = new ps_DB();
				
		$list  = "SELECT `order`.*, ui.first_name, ui.last_name, booking.*, p.name as property, IF((booking.departure BETWEEN '$vbDateFrom' AND '$vbDateTo'), 1, 0) AS ends_now
				FROM #__{vm}_orders AS `order` 
				LEFT JOIN #__{vm}_order_user_info AS ui ON ui.user_id = order.user_id AND ui.order_id = order.order_id AND ui.address_type = 'BT'
				LEFT JOIN #__{vm}_order_booking AS booking ON booking.order_id = order.order_id 				
				LEFT JOIN #__{vm}_user_info AS u ON u.user_id = order.user_id 
				LEFT JOIN #__hp_properties AS p ON p.id = booking.property_id 
				WHERE ";		//Organic ADD
		
		$list .= $this->getOrdersQuery($state, $vbDateFrom, $vbDateTo, $property_id, $showAllProps, $onlyEnding) . ($page == 'order.booking_list' ? " LIMIT $limitstart, " . $limit : ''); 		
		$db->query($list);	
				
		return $db;
	}
	
	function getOrdersQuery($state = '', $vbDateFrom = '', $vbDateTo = '', $property_id = '', $showAllProps = 0, $onlyEnding = false){
		
		global $keyword;
		$q = "";
		
		if (!empty($keyword)) {
		        $q  .= "(order.order_id LIKE '%$keyword%' ";
		        $q .= "OR order.order_status LIKE '%$keyword%' ";
		        $q .= "OR ui.first_name LIKE '%$keyword%' ";
		        $q .= "OR ui.last_name LIKE '%$keyword%' ";
				$q .= "OR CONCAT(ui.`first_name`, ' ', ui.`last_name`) LIKE '%$keyword%' ";
		        $q .= "OR u.first_name LIKE '%$keyword%' ";
		        $q .= "OR u.last_name LIKE '%$keyword%' ";
				$q .= "OR CONCAT(u.`first_name`, ' ', u.`last_name`) LIKE '%$keyword%' ";
				$q .= "OR p.name LIKE '%$keyword%' ";
		        $q .= ") AND ";
		}
		
		if (!empty($state)) {
			$q .= "order_status = '$state' AND ";
		}
		
		if(!empty($property_id)){	
			$q .= "p.id = $property_id AND ";
		}

		$q .= "order.vendor_id='".$_SESSION['ps_vendor_id']."' ";
		$q .= $showAllProps ? '' : "AND booking.property_id IN(".implode(',',$this->getAllowedProperties()).") "; /* Organic add, only show agents bookings */
		if(($vbDateFrom && $vbDateTo)){
			$q .= "AND ((booking.departure BETWEEN '$vbDateFrom' AND '$vbDateTo')
						".(
						$onlyEnding ? '' : " OR
						('$vbDateFrom' BETWEEN booking.arrival AND booking.departure) OR						
						(booking.arrival BETWEEN '$vbDateFrom' AND '$vbDateTo') OR
						('$vbDateTo' BETWEEN booking.arrival AND booking.departure)
					 	").")";
		}
		$q .= "ORDER BY booking.arrival ASC ";
		
		return $q;
	}
	
	
	function getAllowedProperties(){
		
		global $my, $vmuser, $perm;
		
		$db = new ps_DB();
		$prop_ids = array();
				
		//Get either all properties or only for this agent/owner
		if(in_array($vmuser->gid, array(23,24,25,31))){
			$q = "SELECT p.id from #__hp_properties AS p"
			.($vmuser->gid == 31 ? ", #__hp_agents as a WHERE a.id = p.agent AND a.user = '$my->id'" : '');
			$db->query($q);
			while($db->next_record()){
				$prop_ids[] = $db->f("id");
			}
		}else if($perm->check( "maintenance")){
			$q = "SELECT properties FROM #__{vm}_maintenance_props WHERE user_id = $my->id";
			$db->query($q);
			$db->next_record();
			$prop_ids = explode(',',$db->f('properties'));
		}		
		
		return $prop_ids;		
	}

	
	function getPropertiesList($selected = 0, $name = 'property_id', $extra = ''){
		
		$props = ps_order_booking::getAllowedProperties();
		if(count($props) > 1){
			$q = "SELECT * FROM #__hp_properties WHERE published = 1 AND id IN (".implode(',',$props).") ORDER BY name";
			$dbp = new ps_DB();
			$dbp->query($q);
			$props = array(0=>'-- Select Property --');
			while($dbp->next_record()){
				$props[$dbp->f('id')] = $dbp->f('name');
			}
			return ps_html::selectList($name, $selected, $props,1,'', "id='$name' $extra");
		}		
	}
	
	function validateOwner(){
		
		global $my, $vmuser;

		if(in_array($vmuser->gid, array(23,24,25,31))){			
			return true;
		}else{
			$GLOBALS['vmLogger']->err( 'You do not have permission to manage bookings.' );
			return false;
		}
				
	}
}

?>
Back to Top