codistoconnect - Version 1.90.27

Version Notes

Release 1.90.27

Download this release

Release Info

Developer Codisto
Extension codistoconnect
Version 1.90.27
Comparing to
See all releases


Code changes from version 1.90.26 to 1.90.27

app/code/community/Codisto/Sync/controllers/IndexController.php.save ADDED
@@ -0,0 +1,1991 @@
1
+ <?php
2
+ /**
3
+ * Codisto eBay Sync Extension
4
+ *
5
+ * NOTICE OF LICENSE
6
+ *
7
+ * This source file is subject to the Open Software License (OSL 3.0)
8
+ * that is bundled with this package in the file LICENSE.txt.
9
+ * It is also available through the world-wide-web at this URL:
10
+ * http://opensource.org/licenses/osl-3.0.php
11
+ * If you did not receive a copy of the license and are unable to
12
+ * obtain it through the world-wide-web, please send an email
13
+ * to license@magentocommerce.com so we can send you a copy immediately.
14
+ *
15
+ * @category Codisto
16
+ * @package Codisto_Sync
17
+ * @copyright Copyright (c) 2015 On Technology Pty. Ltd. (http://codisto.com/)
18
+ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
19
+ */
20
+
21
+ class Codisto_Sync_IndexController extends Mage_Core_Controller_Front_Action
22
+ {
23
+ public function calcAction()
24
+ {
25
+ set_time_limit(0);
26
+ ignore_user_abort(false);
27
+
28
+ $output = '';
29
+
30
+ try
31
+ {
32
+ $request = $this->getRequest();
33
+ $response = $this->getResponse();
34
+
35
+ $storeId = $request->getQuery('storeid') == null ? 0 : (int)$request->getQuery('storeid');
36
+
37
+ if($storeId == 0)
38
+ {
39
+ // jump the storeid to first non admin store
40
+ $stores = Mage::getModel('core/store')->getCollection()
41
+ ->addFieldToFilter('is_active', array('neq' => 0))
42
+ ->addFieldToFilter('store_id', array('gt' => 0))
43
+ ->setOrder('store_id', 'ASC');
44
+
45
+ $firstStore = $stores->getFirstItem();
46
+ if(is_object($firstStore) && $firstStore->getId())
47
+ $storeId = $firstStore->getId();
48
+ }
49
+
50
+ $store = Mage::app()->getStore($storeId);
51
+
52
+ $currencyCode = $request->getPost('CURRENCY');
53
+ if(!$currencyCode)
54
+ $currencyCode = $store->getCurrentCurrencyCode();
55
+
56
+ $place = $request->getPost('PLACE');
57
+ if(!$place)
58
+ $place = '';
59
+ $postalcode = $request->getPost('POSTALCODE');
60
+ $division = $request->getPost('DIVISION');
61
+ $countrycode = $request->getPost('COUNTRYCODE');
62
+ $regionid = null;
63
+ $regioncode = null;
64
+
65
+ if($countrycode == 'AU')
66
+ {
67
+ $pc = $postalcode{0};
68
+
69
+ if ($pc == 2 || $pc == 1) {
70
+ $regiontext = 'NSW';
71
+ } else if ($pc == 3 || $pc == 8) {
72
+ $regiontext = 'VIC';
73
+ } else if ($pc == 4) {
74
+ $regiontext = 'QLD';
75
+ } else if ($pc == 5) {
76
+ $regiontext = 'SA';
77
+ } else if ($pc == 6) {
78
+ $regiontext = 'WA';
79
+ } else if ($pc == 7) {
80
+ $regiontext = 'TAS';
81
+ }
82
+
83
+ $pc3 = $postalcode{0} . $postalcode{1};
84
+ if ($pc3 == '08' || $pc3 == '09') {
85
+ $regiontext = 'NT';
86
+ }
87
+
88
+ if ($postalcode == '0872') {
89
+ $regiontext = 'SA';
90
+ } else if ($postalcode == '2611' || $postalcode == '3500' || $postalcode == '3585' || $postalcode == '3586' || $postalcode == '3644' || $postalcode == '3707') {
91
+ $regiontext = 'NSW';
92
+ } else if ($postalcode == '2620') {
93
+ $regiontext = 'ACT';
94
+ }
95
+
96
+ if (intval($postalcode) >= 2600 && intval($postalcode) <= 2618) {
97
+ $regiontext = 'ACT';
98
+ }
99
+
100
+ $region = Mage::getModel('directory/region')->loadByCode($regiontext, $countrycode);
101
+ if($region)
102
+ {
103
+ $regionid = $region->getId();
104
+ $regioncode = $region->getCode();
105
+ }
106
+ }
107
+ else
108
+ {
109
+ $region = Mage::getModel('directory/region')->loadByName($division, $countrycode);
110
+ if($region)
111
+ {
112
+ $regionid = $region->getId();
113
+ $regioncode = $region->getCode();
114
+ }
115
+ }
116
+
117
+ $total = 0;
118
+ $itemqty = 0;
119
+ $totalweight = 0;
120
+
121
+ $quote = Mage::getModel('sales/quote');
122
+ $quote->setIsSuperMode(true);
123
+
124
+ for($inputidx = 0; ; $inputidx++)
125
+ {
126
+ if(!$request->getPost('PRODUCTCODE('.$inputidx.')'))
127
+ break;
128
+
129
+ $productid = (int)$request->getPost('PRODUCTID('.$inputidx.')');
130
+ if(!$productid)
131
+ {
132
+ $productcode = $request->getPost('PRODUCTCODE('.$inputidx.')');
133
+ $productid = Mage::getModel('catalog/product')->getIdBySku($productcode);
134
+ }
135
+ else
136
+ {
137
+ $sku = Mage::getResourceSingleton('catalog/product')->getProductsSku(array($productid));
138
+ if(empty($sku))
139
+ {
140
+ $productcode = $request->getPost('PRODUCTCODE('.$inputidx.')');
141
+ $productid = Mage::getModel('catalog/product')->getIdBySku($productcode);
142
+ }
143
+ }
144
+
145
+ $productqty = $request->getPost('PRODUCTQUANTITY('.$inputidx.')');
146
+ if(!$productqty && $productqty !=0)
147
+ $productqty = 1;
148
+
149
+ $productprice = floatval($request->getPost('PRODUCTPRICE('.$inputidx.')'));
150
+ $productpriceincltax = floatval($request->getPost('PRODUCTPRICEINCTAX('.$inputidx.')'));
151
+ $producttax = floatval($request->getPost('PRODUCTTAX('.$inputidx.')'));
152
+
153
+ if($productid)
154
+ {
155
+ $product = Mage::getModel('catalog/product')->load($productid);
156
+
157
+ if($product)
158
+ {
159
+ $product->setIsSuperMode(true);
160
+
161
+ $taxpercent = $productprice == 0 ? 0 : round($productpriceincltax / $productprice - 1.0, 2) * 100;
162
+
163
+ $item = Mage::getModel('sales/quote_item');
164
+ $item->setStoreId($store->getId());
165
+ $item->setQuote($quote);
166
+
167
+ $item->setData('product', $product);
168
+ $item->setProductId($productid);
169
+ $item->setProductType('simple');
170
+ $item->setIsRecurring(false);
171
+ $item->setTaxClassId($product->getTaxClassId());
172
+ $item->setBaseCost($product->getCost());
173
+ $item->setSku($product->getSku());
174
+ $item->setName($product->getName());
175
+ $item->setIsVirtual(0);
176
+ $item->setIsQtyDecimal(0);
177
+ $item->setNoDiscount(true);
178
+ $item->setWeight($product->getWeight());
179
+ $item->setData('qty', $productqty);
180
+ $item->setPrice($productprice);
181
+ $item->setBasePrice($productprice);
182
+ $item->setCustomPrice($productprice);
183
+ $item->setDiscountPercent(0);
184
+ $item->setDiscountAmount(0);
185
+ $item->setBaseDiscountAmount(0);
186
+ $item->setTaxPercent($taxpercent);
187
+ $item->setTaxAmount($producttax);
188
+ $item->setBaseTaxAmount($producttax);
189
+ $item->setRowTotal($productprice * $productqty);
190
+ $item->setBaseRowTotal($productprice * $productqty);
191
+ $item->setRowTotalWithDiscount($productprice * $productqty);
192
+ $item->setRowWeight($product->getWeight() * $productqty);
193
+ $item->setOriginalCustomPrice($productprice);
194
+ $item->setPriceInclTax($productpriceincltax);
195
+ $item->setBasePriceInclTax($productpriceincltax);
196
+ $item->setRowTotalInclTax($productpriceincltax * $productqty);
197
+ $item->setBaseRowTotalInclTax($productpriceincltax * $productqty);
198
+ $item->setWeeeTaxApplied(serialize(array()));
199
+
200
+ $total += $productpriceincltax * $productqty;
201
+ $itemqty += $productqty;
202
+ $totalweight += $product->getWeight() * $productqty;
203
+
204
+ $quote->getItemsCollection()->addItem($item);
205
+ }
206
+ }
207
+ }
208
+
209
+ $quote->save();
210
+
211
+ $checkoutSession = Mage::getSingleton('checkout/session');
212
+ $checkoutSession->replaceQuote($quote);
213
+ $checkoutSession->setData('destination_type', 'residence');
214
+
215
+ $currency = Mage::getModel('directory/currency')->load($currencyCode);
216
+
217
+ $shippingRequest = Mage::getModel('shipping/rate_request');
218
+ $shippingRequest->setAllItems($quote->getAllItems());
219
+ $shippingRequest->setDestCountryId($countrycode);
220
+ if($regionid)
221
+ $shippingRequest->setDestRegionId($regionid);
222
+ if($regioncode)
223
+ $shippingRequest->setDestRegionCode($regioncode);
224
+ if($place)
225
+ $shippingRequest->setDestCity($place);
226
+ $shippingRequest->setDestPostcode($postalcode);
227
+ $shippingRequest->setPackageValue($total);
228
+ $shippingRequest->setPackageValueWithDiscount($total);
229
+ $shippingRequest->setPackageWeight($totalweight);
230
+ $shippingRequest->setPackageQty($itemqty);
231
+ $shippingRequest->setPackagePhysicalValue($total);
232
+ $shippingRequest->setFreeMethodWeight(0);
233
+ $shippingRequest->setStoreId($store->getId());
234
+ $shippingRequest->setWebsiteId($store->getWebsiteId());
235
+ $shippingRequest->setFreeShipping(0);
236
+ $shippingRequest->setBaseCurrency($currency);
237
+ $shippingRequest->setPackageCurrency($currency);
238
+ $shippingRequest->setBaseSubtotalInclTax($total);
239
+
240
+ $shippingResult = Mage::getModel('shipping/shipping')->collectRates($shippingRequest)->getResult();
241
+
242
+ $shippingRates = $shippingResult->getAllRates();
243
+
244
+ $outputidx = 0;
245
+ foreach($shippingRates as $shippingRate)
246
+ {
247
+ if($shippingRate instanceof Mage_Shipping_Model_Rate_Result_Method)
248
+ {
249
+ $isPickup = $shippingRate->getPrice() == 0 &&
250
+ (preg_match('/(?:^|\W|_)pick\s*up(?:\W|_|$)/i', strval($shippingRate->getMethod())) ||
251
+ preg_match('/(?:^|\W|_)pick\s*up(?:\W|_|$)/i', strval($shippingRate->getCarrierTitle())) ||
252
+ preg_match('/(?:^|\W|_)pick\s*up(?:\W|_|$)/i', strval($shippingRate->getMethodTitle())));
253
+
254
+ if(!$isPickup)
255
+ {
256
+ $output .= 'FREIGHTNAME('.$outputidx.')='.rawurlencode($shippingRate->getMethodTitle()).'&FREIGHTCHARGEINCTAX('.$outputidx.')='.$shippingRate->getPrice().'&';
257
+ $outputidx++;
258
+ }
259
+ }
260
+ }
261
+
262
+ try
263
+ {
264
+ $quote
265
+ ->setIsActive(false)
266
+ ->delete();
267
+ }
268
+ catch(Exception $e)
269
+ {
270
+
271
+ }
272
+
273
+ }
274
+ catch(Exception $e)
275
+ {
276
+
277
+ }
278
+
279
+ $response->clearAllHeaders();
280
+ //@codingStandardsIgnoreStart
281
+ if(function_exists('http_response_code'))
282
+ http_response_code(200);
283
+ //@codingStandardsIgnoreEnd
284
+ $response->setHttpResponseCode(200);
285
+ $response->setRawHeader('HTTP/1.0 200 OK');
286
+ $response->setRawHeader('Status: 200 OK');
287
+ $response->setHeader('Expires', 'Thu, 01 Jan 1970 00:00:00 GMT', true);
288
+ $response->setHeader('Cache-Control', 'no-cache, must-revalidate', true);
289
+ $response->setHeader('Pragma', 'no-cache', true);
290
+ $response->setBody($output);
291
+ }
292
+
293
+ public function indexAction()
294
+ {
295
+ set_time_limit(0);
296
+ ignore_user_abort(false);
297
+
298
+ $request = $this->getRequest();
299
+ $response = $this->getResponse();
300
+ $method = isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : 'GET';
301
+ $contenttype = isset($_SERVER['CONTENT_TYPE']) ? $_SERVER['CONTENT_TYPE'] : '';
302
+ $server = $request->getServer();
303
+
304
+ if($method == 'POST')
305
+ {
306
+ $helper = Mage::helper('codistosync');
307
+
308
+ if($contenttype == 'text/xml')
309
+ {
310
+ $xml = simplexml_load_string(file_get_contents('php://input'));
311
+
312
+ $ordercontent = $xml->entry->content->children('http://api.codisto.com/schemas/2009/');
313
+
314
+ $storeId = @count($ordercontent->storeid) ? (int)$ordercontent->storeid : 0;
315
+
316
+ if(!$helper->getConfig($storeId))
317
+ {
318
+ $response->clearAllHeaders();
319
+ //@codingStandardsIgnoreStart
320
+ if(function_exists('http_response_code'))
321
+ http_response_code(500);
322
+ //@codingStandardsIgnoreEnd
323
+ $response->setHttpResponseCode(500);
324
+ $response->setRawHeader('HTTP/1.0 500 Security Error');
325
+ $response->setRawHeader('Status: 500 Security Error');
326
+ $response->setHeader('Expires', 'Thu, 01 Jan 1970 00:00:00 GMT', true);
327
+ $response->setHeader('Cache-Control', 'no-cache, must-revalidate', true);
328
+ $response->setHeader('Pragma', 'no-cache', true);
329
+ $response->setBody('Config Error');
330
+ return;
331
+ }
332
+
333
+ if($helper->checkRequestHash(Mage::getStoreConfig('codisto/hostkey', $storeId), $server))
334
+ {
335
+ $productsToReindex = array();
336
+ $ordersProcessed = array();
337
+ $invoicesProcessed = array();
338
+
339
+ $connection = Mage::getSingleton('core/resource')->getConnection('core_write');
340
+
341
+ try
342
+ {
343
+ $connection->addColumn(
344
+ Mage::getConfig()->getTablePrefix() . 'sales_flat_order',
345
+ 'codisto_orderid',
346
+ 'varchar(10)'
347
+ );
348
+ }
349
+ catch(Exception $e)
350
+ {
351
+
352
+ }
353
+
354
+ if($storeId == 0)
355
+ {
356
+ // jump the storeid to first non admin store
357
+ $stores = Mage::getModel('core/store')->getCollection()
358
+ ->addFieldToFilter('is_active', array('neq' => 0))
359
+ ->addFieldToFilter('store_id', array('gt' => 0))
360
+ ->setOrder('store_id', 'ASC');
361
+
362
+ $stores->setPageSize(1)->setCurPage(1);
363
+ $firstStore = $stores->getFirstItem();
364
+ if(is_object($firstStore) && $firstStore->getId())
365
+ $storeId = $firstStore->getId();
366
+ }
367
+
368
+ $store = Mage::app()->getStore($storeId);
369
+
370
+ Mage::app()->setCurrentStore($store);
371
+
372
+ $quote = null;
373
+
374
+ for($Retry = 0; ; $Retry++)
375
+ {
376
+ $productsToReindex = array();
377
+
378
+ try
379
+ {
380
+ $quote = Mage::getModel('sales/quote');
381
+
382
+ $this->ProcessQuote($quote, $xml, $store);
383
+ }
384
+ catch(Exception $e)
385
+ {
386
+ $response = $this->getResponse();
387
+
388
+ $response->clearAllHeaders();
389
+ //@codingStandardsIgnoreStart
390
+ if(function_exists('http_response_code'))
391
+ http_response_code(200);
392
+ //@codingStandardsIgnoreEnd
393
+ $response->setHttpResponseCode(200);
394
+ $response->setRawHeader('HTTP/1.0 200 OK');
395
+ $response->setRawHeader('Status: 200 OK');
396
+ $response->setHeader('Content-Type', 'application/json');
397
+ $response->setHeader('Expires', 'Thu, 01 Jan 1970 00:00:00 GMT', true);
398
+ $response->setHeader('Cache-Control', 'no-cache, must-revalidate', true);
399
+ $response->setHeader('Pragma', 'no-cache', true);
400
+ $response->setBody(Zend_Json::encode(array( 'ack' => 'failed', 'code' => $e->getCode(), 'message' => $e->getMessage(), 'trace' => $e->getTraceAsString())));
401
+ break;
402
+ }
403
+
404
+ $connection->query('SET TRANSACTION ISOLATION LEVEL SERIALIZABLE');
405
+ $connection->beginTransaction();
406
+
407
+ try
408
+ {
409
+ $order = Mage::getModel('sales/order')->getCollection()->addAttributeToFilter('codisto_orderid', $ordercontent->orderid)->getFirstItem();
410
+
411
+ if($order && $order->getId())
412
+ {
413
+ $this->ProcessOrderCreate($quote, $xml, $productsToReindex, $ordersProcessed, $invoicesProcessed, $store);
414
+
415
+ // $this->ProcessOrderCreate($quote, $order, $xml, $productsToReindex, $ordersProcessed, $invoicesProcessed, $store);
416
+ }
417
+ else
418
+ {
419
+ $this->ProcessOrderCreate($quote, $xml, $productsToReindex, $ordersProcessed, $invoicesProcessed, $store);
420
+ }
421
+
422
+ $connection->commit();
423
+ break;
424
+ }
425
+ catch(Exception $e)
426
+ {
427
+ if($Retry < 5)
428
+ {
429
+ if($e->getCode() == 40001)
430
+ {
431
+ $connection->rollback();
432
+ sleep($Retry * 10);
433
+ continue;
434
+ }
435
+ }
436
+
437
+ $response = $this->getResponse();
438
+
439
+ $response->clearAllHeaders();
440
+ //@codingStandardsIgnoreStart
441
+ if(function_exists('http_response_code'))
442
+ http_response_code(200);
443
+ //@codingStandardsIgnoreEnd
444
+ $response->setHttpResponseCode(200);
445
+ $response->setRawHeader('HTTP/1.0 200 OK');
446
+ $response->setRawHeader('Status: 200 OK');
447
+ $response->setHeader('Content-Type', 'application/json');
448
+ $response->setHeader('Expires', 'Thu, 01 Jan 1970 00:00:00 GMT', true);
449
+ $response->setHeader('Cache-Control', 'no-cache, must-revalidate', true);
450
+ $response->setHeader('Pragma', 'no-cache', true);
451
+ $response->setBody(Zend_Json::encode(array( 'ack' => 'failed', 'code' => $e->getCode(), 'message' => $e->getMessage(), 'trace' => $e->getTraceAsString())));
452
+
453
+ $connection->rollback();
454
+ break;
455
+ }
456
+ }
457
+
458
+ try
459
+ {
460
+ if(!empty($ordersProcessed))
461
+ {
462
+ Mage::getResourceModel('sales/order')->updateGridRecords($ordersProcessed);
463
+ }
464
+ }
465
+ catch (Exception $e)
466
+ {
467
+
468
+ }
469
+
470
+ try
471
+ {
472
+ if(!empty($invoicesProcessed))
473
+ {
474
+ Mage::getResourceModel('sales/order_invoice')->updateGridRecords($invoicesProcessed);
475
+ }
476
+ }
477
+ catch (Exception $e)
478
+ {
479
+
480
+ }
481
+
482
+ try
483
+ {
484
+
485
+ if(!empty($productsToReindex))
486
+ {
487
+ Mage::getResourceSingleton('cataloginventory/indexer_stock')->reindexProducts($productsToReindex);
488
+ Mage::getResourceSingleton('catalog/product_indexer_price')->reindexProductIds($productsToReindex);
489
+ }
490
+
491
+ }
492
+ catch (Exception $e)
493
+ {
494
+
495
+ }
496
+ }
497
+ else
498
+ {
499
+ $response->clearAllHeaders();
500
+ //@codingStandardsIgnoreStart
501
+ if(function_exists('http_response_code'))
502
+ http_response_code(400);
503
+ //@codingStandardsIgnoreEnd
504
+ $response->setHttpResponseCode(400);
505
+ $response->setRawHeader('HTTP/1.0 400 Security Error');
506
+ $response->setRawHeader('Status: 400 Security Error');
507
+ $response->setHeader('Expires', 'Thu, 01 Jan 1970 00:00:00 GMT', true);
508
+ $response->setHeader('Cache-Control', 'no-cache, must-revalidate', true);
509
+ $response->setHeader('Pragma', 'no-cache', true);
510
+ $response->setBody('Security Error');
511
+ return;
512
+ }
513
+ }
514
+ else
515
+ {
516
+ $response->clearAllHeaders();
517
+ //@codingStandardsIgnoreStart
518
+ if(function_exists('http_response_code'))
519
+ http_response_code(400);
520
+ //@codingStandardsIgnoreEnd
521
+ $response->setHttpResponseCode(400);
522
+ $response->setRawHeader('HTTP/1.0 400 Invalid Content Type');
523
+ $response->setRawHeader('Status: 400 Invalid Content Type');
524
+ $response->setHeader('Expires', 'Thu, 01 Jan 1970 00:00:00 GMT', true);
525
+ $response->setHeader('Cache-Control', 'no-cache, must-revalidate', true);
526
+ $response->setHeader('Pragma', 'no-cache', true);
527
+ $response->setBody('Invalid Content Type');
528
+ return;
529
+ }
530
+ }
531
+ else
532
+ {
533
+ include_once Mage::getBaseDir() . '/errors/404.php';
534
+ }
535
+ }
536
+
537
+ private function ProcessOrderCreate($quote, $xml, &$productsToReindex, &$orderids, &$invoiceids, $store)
538
+ {
539
+ $ordercontent = $xml->entry->content->children('http://api.codisto.com/schemas/2009/');
540
+
541
+ $paypaltransactionid = $ordercontent->orderpayments[0]->orderpayment->transactionid;
542
+ $ordernumberformat = (string)$ordercontent->ordernumberformat;
543
+
544
+ $ordertotal = floatval($ordercontent->ordertotal[0]);
545
+ $ordersubtotal = floatval($ordercontent->ordersubtotal[0]);
546
+ $ordertaxtotal = floatval($ordercontent->ordertaxtotal[0]);
547
+
548
+ $ordersubtotal = $store->roundPrice($ordersubtotal);
549
+ $ordersubtotalincltax = $store->roundPrice($ordersubtotal + $ordertaxtotal);
550
+ $ordertotal = $store->roundPrice($ordertotal);
551
+
552
+ $ebaysalesrecordnumber = (string)$ordercontent->ebaysalesrecordnumber;
553
+ if(!$ebaysalesrecordnumber)
554
+ $ebaysalesrecordnumber = '';
555
+
556
+ $ebayusername = (string)$ordercontent->ebayusername;
557
+ if(!$ebayusername)
558
+ $ebayusername = '';
559
+
560
+ $quoteConverter = Mage::getModel('sales/convert_quote');
561
+
562
+ $quote->reserveOrderId();
563
+ $order = $quoteConverter->addressToOrder($quote->getShippingAddress());
564
+ $order->setBillingAddress($quoteConverter->addressToOrderAddress($quote->getBillingAddress()));
565
+ $order->setShippingAddress($quoteConverter->addressToOrderAddress($quote->getShippingAddress()));
566
+ $order->setPayment($quoteConverter->paymentToOrderPayment($quote->getPayment()));
567
+ $order->setCustomer($quote->getCustomer());
568
+ $order->setCodistoOrderid($ordercontent->orderid);
569
+
570
+ if(preg_match('/\{ordernumber\}/', $ordernumberformat))
571
+ {
572
+ $incrementId = preg_replace('/\{ordernumber\}/', (string)$order->getIncrementId(), $ordernumberformat);
573
+ $order->setIncrementId($incrementId);
574
+ }
575
+ else
576
+ {
577
+ $incrementId = $ordernumberformat.''.(string)$order->getIncrementId();
578
+ $order->setIncrementId($incrementId);
579
+ }
580
+
581
+ $weight_total = 0;
582
+
583
+ $quoteItems = $quote->getItemsCollection()->getItems();
584
+ $quoteIdx = 0;
585
+
586
+ foreach($ordercontent->orderlines->orderline as $orderline)
587
+ {
588
+ if($orderline->productcode[0] != 'FREIGHT')
589
+ {
590
+ $adjustStock = true;
591
+
592
+ $product = null;
593
+
594
+ $productcode = $orderline->productcode[0];
595
+ if($productcode == null)
596
+ $productcode = '';
597
+ else
598
+ $productcode = (string)$productcode;
599
+
600
+ $productname = $orderline->productname[0];
601
+ if($productname == null)
602
+ $productname = '';
603
+ else
604
+ $productname = (string)$productname;
605
+
606
+ $productid = $orderline->externalreference[0];
607
+ if($productid != null)
608
+ {
609
+ $productid = intval($productid);
610
+
611
+ $product = Mage::getModel('catalog/product')->load($productid);
612
+ if($product->getId())
613
+ {
614
+ $productcode = $product->getSku();
615
+ $productname = $product->getName();
616
+ }
617
+ else
618
+ {
619
+ $product = null;
620
+ }
621
+ }
622
+
623
+ if(!$product)
624
+ {
625
+ $product = Mage::getModel('catalog/product');
626
+ $adjustStock = false;
627
+ }
628
+
629
+ $qty = (int)$orderline->quantity[0];
630
+ $subtotalinctax = floatval($orderline->linetotalinctax[0]);
631
+ $subtotal = floatval($orderline->linetotal[0]);
632
+
633
+ $price = floatval($orderline->price[0]);
634
+ $priceinctax = floatval($orderline->priceinctax[0]);
635
+ $taxamount = $priceinctax - $price;
636
+ $taxpercent = $price == 0 ? 0 : round($priceinctax / $price - 1.0, 2) * 100;
637
+ $weight = floatval($orderline->weight[0]);
638
+ if($weight == 0)
639
+ $weight = 1;
640
+
641
+ $weight_total += $weight;
642
+
643
+ $orderItem = $quoteConverter->itemToOrderItem($quoteItems[$quoteIdx]);
644
+
645
+ $quoteIdx++;
646
+
647
+ $orderItem->setStoreId($store->getId());
648
+ $orderItem->setData('product', $product);
649
+
650
+ if($productid)
651
+ $orderItem->setProductId($productid);
652
+
653
+ if($productid)
654
+ $orderItem->setBaseCost($product->getCost());
655
+
656
+ if($productid)
657
+ {
658
+ $orderItem->setOriginalPrice($product->getFinalPrice());
659
+ $orderItem->setBaseOriginalPrice($product->getFinalPrice());
660
+ }
661
+ else
662
+ {
663
+ $orderItem->setOriginalPrice($priceinctax);
664
+ $orderItem->setBaseOriginalPrice($priceinctax);
665
+ }
666
+
667
+ $orderItem->setIsVirtual(false);
668
+ $orderItem->setProductType('simple');
669
+ $orderItem->setSku($productcode);
670
+ $orderItem->setName($productname);
671
+ $orderItem->setIsQtyDecimal(false);
672
+ $orderItem->setNoDiscount(true);
673
+ $orderItem->setQtyOrdered($qty);
674
+ $orderItem->setPrice($price);
675
+ $orderItem->setPriceInclTax($priceinctax);
676
+ $orderItem->setBasePrice($price);
677
+ $orderItem->setBasePriceInclTax($priceinctax);
678
+ $orderItem->setTaxPercent($taxpercent);
679
+ $orderItem->setTaxAmount($taxamount);
680
+ $orderItem->setTaxBeforeDiscount($taxamount);
681
+ $orderItem->setBaseTaxBeforeDiscount($taxamount);
682
+ $orderItem->setDiscountAmount(0);
683
+ $orderItem->setWeight($weight);
684
+ $orderItem->setBaseRowTotal($subtotal);
685
+ $orderItem->setBaseRowTotalInclTax($subtotalinctax);
686
+ $orderItem->setRowTotal($subtotal);
687
+ $orderItem->setRowTotalInclTax($subtotalinctax);
688
+ $orderItem->setWeeeTaxApplied(serialize(array()));
689
+
690
+ $order->addItem($orderItem);
691
+
692
+ if($ordercontent->orderstate != 'cancelled')
693
+ {
694
+ if($adjustStock)
695
+ {
696
+ $stockItem = $product->getStockItem();
697
+ if(!$stockItem)
698
+ {
699
+ $stockItem = Mage::getModel('cataloginventory/stock_item')
700
+ ->loadByProduct($product)
701
+ ->setStoreId($store->getId());
702
+ }
703
+
704
+ $typeId = $product->getTypeId();
705
+ if(!$typeId)
706
+ $typeId = 'simple';
707
+
708
+ if(Mage::helper('catalogInventory')->isQty($typeId))
709
+ {
710
+ if($stockItem->canSubtractQty())
711
+ {
712
+ $productsToReindex[$product->getId()] = $product->getId();
713
+
714
+ $stockItem->subtractQty($orderItem->getQtyOrdered());
715
+ $stockItem->save();
716
+ }
717
+ }
718
+ }
719
+ }
720
+ }
721
+ }
722
+
723
+ $quote->setInventoryProcessed(true);
724
+
725
+ $order->setQuote($quote);
726
+
727
+ $freightservice = 'Freight';
728
+ $freighttotal = 0.0;
729
+ $freighttotalextax = 0.0;
730
+ $freighttax = 0.0;
731
+ $taxpercent = 0.0;
732
+ $taxrate = 1.0;
733
+
734
+ foreach($ordercontent->orderlines->orderline as $orderline)
735
+ {
736
+ if($orderline->productcode[0] == 'FREIGHT')
737
+ {
738
+ $freighttotal += floatval($orderline->linetotalinctax[0]);
739
+ $freighttotalextax += floatval($orderline->linetotal[0]);
740
+ $freighttax = $freighttotal - $freighttotalextax;
741
+ $freightservice = (string)$orderline->productname[0];
742
+ }
743
+ }
744
+
745
+ if(strtolower($freightservice) != 'freight')
746
+ {
747
+ $order->setShippingDescription($freightservice);
748
+ }
749
+
750
+ $ordersubtotal -= $freighttotalextax;
751
+ $ordersubtotalincltax -= $freighttotal;
752
+ $ordertaxtotal -= $freighttax;
753
+
754
+ $order->setBaseShippingAmount($freighttotal);
755
+ $order->setShippingAmount($freighttotal);
756
+
757
+ $order->setBaseShippingInclTax($freighttotal);
758
+ $order->setShippingInclTax($freighttotal);
759
+
760
+ $order->setBaseShippingTaxAmount($freighttax);
761
+ $order->setShippingTaxAmount($freighttax);
762
+
763
+ $order->setBaseSubtotal($ordersubtotal);
764
+ $order->setSubtotal($ordersubtotal);
765
+
766
+ $order->setBaseSubtotalInclTax($ordersubtotalincltax);
767
+ $order->setSubtotalInclTax($ordersubtotalincltax);
768
+
769
+ $order->setBaseTaxAmount($ordertaxtotal);
770
+ $order->setTaxAmount($ordertaxtotal);
771
+
772
+
773
+ $order->setDiscountAmount(0.0);
774
+ $order->setShippingDiscountAmount(0.0);
775
+ $order->setBaseShippingDiscountAmount(0.0);
776
+
777
+ $order->setBaseHiddenTaxAmount(0.0);
778
+ $order->setHiddenTaxAmount(0.0);
779
+ $order->setBaseHiddenShippingTaxAmnt(0.0);
780
+ $order->setHiddenShippingTaxAmount(0.0);
781
+
782
+ $order->setBaseGrandTotal($ordertotal);
783
+ $order->setGrandTotal($ordertotal);
784
+
785
+ $order->setWeight($weight_total);
786
+
787
+ $order->setBaseSubtotalInvoiced(0.0);
788
+ $order->setBaseTaxInvoiced(0.0);
789
+ $order->setBaseTotalInvoiced(0.0);
790
+ $order->setSubtotalInvoiced(0.0);
791
+ $order->setTaxInvoiced(0.0);
792
+ $order->setTotalInvoiced(0.0);
793
+
794
+ $order->setBaseTotalDue($ordertotal);
795
+ $order->setTotalDue($ordertotal);
796
+ $order->setDue($ordertotal);
797
+
798
+ $order->save();
799
+
800
+ try
801
+ {
802
+ $order->place();
803
+ }
804
+ catch(Exception $e)
805
+ {
806
+ $order->addStatusToHistory(Mage_Sales_Model_Order::STATE_PROCESSING, "Exception Occurred Placing Order : ".$e->getMessage());
807
+ }
808
+
809
+ /* cancelled, processing, captured, inprogress, complete */
810
+ if($ordercontent->orderstate == 'cancelled') {
811
+
812
+ $order->setData('state', Mage_Sales_Model_Order::STATE_CANCELED);
813
+ $order->setData('status', Mage_Sales_Model_Order::STATE_CANCELED);
814
+ $order->addStatusToHistory(Mage_Sales_Model_Order::STATE_CANCELED, "eBay Order $ebaysalesrecordnumber has been cancelled");
815
+
816
+ } else if($ordercontent->orderstate == 'inprogress' || $ordercontent->orderstate == 'processing') {
817
+
818
+ $order->setData('state', Mage_Sales_Model_Order::STATE_PROCESSING);
819
+ $order->setData('status', Mage_Sales_Model_Order::STATE_PROCESSING);
820
+ $order->addStatusToHistory(Mage_Sales_Model_Order::STATE_PROCESSING, "eBay Order $ebaysalesrecordnumber is in progress");
821
+
822
+ } else if ($ordercontent->orderstate == 'complete') {
823
+
824
+ $order->setData('state', Mage_Sales_Model_Order::STATE_COMPLETE);
825
+ $order->setData('status', Mage_Sales_Model_Order::STATE_COMPLETE);
826
+ $order->addStatusToHistory(Mage_Sales_Model_Order::STATE_COMPLETE, "eBay Order $ebaysalesrecordnumber is complete");
827
+
828
+ } else {
829
+
830
+ $order->setData('state', Mage_Sales_Model_Order::STATE_PENDING_PAYMENT);
831
+ $order->setData('status', Mage_Sales_Model_Order::STATE_PENDING_PAYMENT);
832
+ $order->addStatusToHistory(Mage_Sales_Model_Order::STATE_PENDING_PAYMENT, "eBay Order $ebaysalesrecordnumber has been captured");
833
+
834
+ }
835
+
836
+ $order->setBaseTotalPaid(0);
837
+ $order->setTotalPaid(0);
838
+ $order->setBaseTotalDue(0);
839
+ $order->setTotalDue(0);
840
+ $order->setDue(0);
841
+
842
+ $payment = $order->getPayment();
843
+
844
+ $payment->setMethod('ebay');
845
+ $payment->resetTransactionAdditionalInfo();
846
+ $payment->setTransactionId(0);
847
+
848
+ $transaction = $payment->addTransaction(Mage_Sales_Model_Order_Payment_Transaction::TYPE_PAYMENT, null, false, '');
849
+ if($paypaltransactionid)
850
+ {
851
+ $transaction->setTxnId($paypaltransactionid);
852
+ $payment->setLastTransId($paypaltransactionid);
853
+ }
854
+
855
+ $payment->setAdditionalInformation('ebaysalesrecordnumber', $ebaysalesrecordnumber);
856
+ $payment->setAdditionalInformation('ebayuser', $ebayusername);
857
+
858
+ if($ordercontent->paymentstatus == 'complete')
859
+ {
860
+ $payment->setBaseAmountPaid($ordertotal);
861
+ $payment->setAmountPaid($ordertotal);
862
+ $payment->setBaseAmountAuthorized($ordertotal);
863
+ $payment->setBaseAmountPaidOnline($ordertotal);
864
+ $payment->setAmountAuthorized($ordertotal);
865
+ $payment->setIsTransactionClosed(1);
866
+
867
+ }
868
+ else
869
+ {
870
+ $payment->setBaseAmountPaid(0.0);
871
+ $payment->setAmountPaid(0.0);
872
+ $payment->setBaseAmountAuthorized($ordertotal);
873
+ $payment->setBaseAmountPaidOnline($ordertotal);
874
+ $payment->setAmountAuthorized($ordertotal);
875
+ $payment->setIsTransactionClosed(0);
876
+ }
877
+
878
+ $quote->setIsActive(false)->save();
879
+
880
+ Mage::dispatchEvent('checkout_type_onepage_save_order', array('order'=>$order, 'quote'=>$quote));
881
+ Mage::dispatchEvent('sales_model_service_quote_submit_before', array('order'=>$order, 'quote'=>$quote));
882
+
883
+ $payment->save();
884
+
885
+ $order->save();
886
+
887
+ Mage::dispatchEvent('sales_model_service_quote_submit_success', array('order'=>$order, 'quote'=>$quote));
888
+ Mage::dispatchEvent('sales_model_service_quote_submit_after', array('order'=>$order, 'quote'=>$quote));
889
+
890
+
891
+ if($ordercontent->paymentstatus == 'complete')
892
+ {
893
+ $invoice = Mage::getModel('sales/service_order', $order)->prepareInvoice();
894
+
895
+ if($invoice->getTotalQty())
896
+ {
897
+ $invoice->setRequestedCaptureCase(Mage_Sales_Model_Order_Invoice::CAPTURE_OFFLINE);
898
+ $invoice->register();
899
+ }
900
+ $invoice->save();
901
+
902
+ if(!in_array($invoice->getId(), $invoiceids))
903
+ $invoiceids[] = $invoice->getId();
904
+
905
+ $order->setBaseSubtotalInvoiced($ordersubtotal);
906
+ $order->setBaseTaxInvoiced($ordertaxtotal);
907
+ $order->setBaseTotalInvoiced($ordertotal);
908
+ $order->setSubtotalInvoiced($ordersubtotal);
909
+ $order->setTaxInvoiced($ordertaxtotal);
910
+ $order->setTotalInvoiced($ordertotal);
911
+ $order->save();
912
+
913
+ Mage::dispatchEvent('sales_order_payment_pay', array('payment' => $payment, 'invoice' => $invoice));
914
+ }
915
+
916
+ $response = $this->getResponse();
917
+
918
+ $response->clearAllHeaders();
919
+ //@codingStandardsIgnoreStart
920
+ if(function_exists('http_response_code'))
921
+ http_response_code(200);
922
+ //@codingStandardsIgnoreEnd
923
+ $response->setHttpResponseCode(200);
924
+ $response->setRawHeader('HTTP/1.0 200 OK');
925
+ $response->setRawHeader('Status: 200 OK');
926
+ $response->setHeader('Content-Type', 'application/json');
927
+ $response->setHeader('Expires', 'Thu, 01 Jan 1970 00:00:00 GMT', true);
928
+ $response->setHeader('Cache-Control', 'no-cache, must-revalidate', true);
929
+ $response->setHeader('Pragma', 'no-cache', true);
930
+ $response->setBody(Zend_Json::encode(array( 'ack' => 'ok', 'orderid' => $order->getIncrementId())));
931
+
932
+ if(!in_array($order->getId(), $orderids))
933
+ $orderids[] = $order->getId();
934
+ }
935
+
936
+ private function ProcessOrderSync($quote, $order, $xml, &$productsToReindex, &$orderids, &$invoiceids, $store)
937
+ {
938
+ $orderstatus = $order->getStatus();
939
+ $ordercontent = $xml->entry->content->children('http://api.codisto.com/schemas/2009/');
940
+
941
+ $paypaltransactionid = $ordercontent->orderpayments[0]->orderpayment->transactionid;
942
+
943
+ $quoteConverter = Mage::getModel('sales/convert_quote');
944
+
945
+ $customer = $quote->getCustomer();
946
+ if($customer)
947
+ $order->setCustomer($customer);
948
+
949
+ $orderBillingAddress = $order->getBillingAddress();
950
+ $quoteBillingAddress = $quote->getBillingAddress();
951
+
952
+ $orderBillingAddress->setPrefix($quoteBillingAddress->getPrefix());
953
+ $orderBillingAddress->setFirstname($quoteBillingAddress->getFirstname());
954
+ $orderBillingAddress->setMiddlename($quoteBillingAddress->getMiddlename());
955
+ $orderBillingAddress->setLastname($quoteBillingAddress->getLastname());
956
+ $orderBillingAddress->setSuffix($quoteBillingAddress->getSuffix());
957
+ $orderBillingAddress->setCompany($quoteBillingAddress->getCompany());
958
+ $orderBillingAddress->setStreet($quoteBillingAddress->getStreet());
959
+ $orderBillingAddress->setCity($quoteBillingAddress->getCity());
960
+ $orderBillingAddress->setRegion($quoteBillingAddress->getRegion());
961
+ $orderBillingAddress->setRegionId($quoteBillingAddress->getRegionId());
962
+ $orderBillingAddress->setPostcode($quoteBillingAddress->getPostcode());
963
+ $orderBillingAddress->setCountryId($quoteBillingAddress->getCountryId());
964
+ $orderBillingAddress->setTelephone($quoteBillingAddress->getTelephone());
965
+ $orderBillingAddress->setFax($quoteBillingAddress->getFax());
966
+ $orderBillingAddress->setEmail($quoteBillingAddress->getEmail());
967
+
968
+ $orderShippingAddress = $order->getShippingAddress();
969
+ $quoteShippingAddress = $quote->getShippingAddress();
970
+
971
+ $orderShippingAddress->setPrefix($quoteShippingAddress->getPrefix());
972
+ $orderShippingAddress->setFirstname($quoteShippingAddress->getFirstname());
973
+ $orderShippingAddress->setMiddlename($quoteShippingAddress->getMiddlename());
974
+ $orderShippingAddress->setLastname($quoteShippingAddress->getLastname());
975
+ $orderShippingAddress->setSuffix($quoteShippingAddress->getSuffix());
976
+ $orderShippingAddress->setCompany($quoteShippingAddress->getCompany());
977
+ $orderShippingAddress->setStreet($quoteShippingAddress->getStreet());
978
+ $orderShippingAddress->setCity($quoteShippingAddress->getCity());
979
+ $orderShippingAddress->setRegion($quoteShippingAddress->getRegion());
980
+ $orderShippingAddress->setRegionId($quoteShippingAddress->getRegionId());
981
+ $orderShippingAddress->setPostcode($quoteShippingAddress->getPostcode());
982
+ $orderShippingAddress->setCountryId($quoteShippingAddress->getCountryId());
983
+ $orderShippingAddress->setTelephone($quoteShippingAddress->getTelephone());
984
+ $orderShippingAddress->setFax($quoteShippingAddress->getFax());
985
+ $orderShippingAddress->setEmail($quoteShippingAddress->getEmail());
986
+
987
+ $ebaysalesrecordnumber = (string)$ordercontent->ebaysalesrecordnumber;
988
+ if(!$ebaysalesrecordnumber)
989
+ $ebaysalesrecordnumber = '';
990
+
991
+ $currencyCode = (string)$ordercontent->transactcurrency;
992
+ $ordertotal = floatval($ordercontent->ordertotal[0]);
993
+ $ordersubtotal = floatval($ordercontent->ordersubtotal[0]);
994
+ $ordertaxtotal = floatval($ordercontent->ordertaxtotal[0]);
995
+
996
+ $ordersubtotal = $store->roundPrice($ordersubtotal);
997
+ $ordersubtotalincltax = $store->roundPrice($ordersubtotal + $ordertaxtotal);
998
+ $ordertotal = $store->roundPrice($ordertotal);
999
+
1000
+ $freightcarrier = 'Post';
1001
+ $freightservice = 'Freight';
1002
+ $freighttotal = 0.0;
1003
+ $freighttotalextax = 0.0;
1004
+ $freighttax = 0.0;
1005
+ $taxpercent = 0.0;
1006
+ $taxrate = 1.0;
1007
+
1008
+ foreach($ordercontent->orderlines->orderline as $orderline)
1009
+ {
1010
+ if($orderline->productcode[0] == 'FREIGHT')
1011
+ {
1012
+ $freighttotal += floatval($orderline->linetotalinctax[0]);
1013
+ $freighttotalextax += floatval($orderline->linetotal[0]);
1014
+ $freighttax = $freighttotal - $freighttotalextax;
1015
+ $freightservice = (string)$orderline->productname[0];
1016
+ }
1017
+ }
1018
+
1019
+ if(strtolower($freightservice) != 'freight')
1020
+ {
1021
+ $order->setShippingDescription($freightservice);
1022
+ }
1023
+
1024
+ $ordersubtotal -= $freighttotalextax;
1025
+ $ordersubtotalincltax -= $freighttotal;
1026
+ $ordertaxtotal -= $freighttax;
1027
+
1028
+ $order->setBaseShippingAmount($freighttotal);
1029
+ $order->setShippingAmount($freighttotal);
1030
+
1031
+ $order->setBaseShippingInclTax($freighttotal);
1032
+ $order->setShippingInclTax($freighttotal);
1033
+
1034
+ $order->setBaseShippingTaxAmount($freighttax);
1035
+ $order->setShippingTaxAmount($freighttax);
1036
+
1037
+ $order->setBaseSubtotal($ordersubtotal);
1038
+ $order->setSubtotal($ordersubtotal);
1039
+
1040
+ $order->setBaseSubtotalInclTax($ordersubtotalincltax);
1041
+ $order->setSubtotalInclTax($ordersubtotalincltax);
1042
+
1043
+ $order->setBaseTaxAmount($ordertaxtotal);
1044
+ $order->setTaxAmount($ordertaxtotal);
1045
+
1046
+ $order->setDiscountAmount(0.0);
1047
+ $order->setShippingDiscountAmount(0.0);
1048
+ $order->setBaseShippingDiscountAmount(0.0);
1049
+
1050
+ $order->setBaseHiddenTaxAmount(0.0);
1051
+ $order->setHiddenTaxAmount(0.0);
1052
+ $order->setBaseHiddenShippingTaxAmnt(0.0);
1053
+ $order->setHiddenShippingTaxAmount(0.0);
1054
+
1055
+ $order->setBaseGrandTotal($ordertotal);
1056
+ $order->setGrandTotal($ordertotal);
1057
+
1058
+ $orderlineStockReserved = array();
1059
+ foreach($order->getAllItems() as $item)
1060
+ {
1061
+ $productId = $item->getProductId();
1062
+ if($productId || $productId == 0)
1063
+ {
1064
+ if(isset($orderlineStockReserved[$productId]))
1065
+ $orderlineStockReserved[$productId] += $item->getQtyOrdered();
1066
+ else
1067
+ $orderlineStockReserved[$productId] = $item->getQtyOrdered();
1068
+ }
1069
+ }
1070
+
1071
+ $visited = array();
1072
+
1073
+ $weight_total = 0;
1074
+
1075
+ $quoteItems = $quote->getItemsCollection()->getItems();
1076
+ $quoteIdx = 0;
1077
+
1078
+ $totalquantity = 0;
1079
+ foreach($ordercontent->orderlines->orderline as $orderline)
1080
+ {
1081
+ if($orderline->productcode[0] != 'FREIGHT')
1082
+ {
1083
+ $adjustStock = true;
1084
+
1085
+ $product = null;
1086
+
1087
+ $productcode = $orderline->productcode[0];
1088
+ if($productcode == null)
1089
+ $productcode = '';
1090
+ else
1091
+ $productcode = (string)$productcode;
1092
+
1093
+ $productname = $orderline->productname[0];
1094
+ if($productname == null)
1095
+ $productname = '';
1096
+ else
1097
+ $productname = (string)$productname;
1098
+
1099
+ $productid = $orderline->externalreference[0];
1100
+ if($productid != null)
1101
+ {
1102
+ $productid = intval($productid);
1103
+
1104
+ $product = Mage::getModel('catalog/product')->load($productid);
1105
+ if($product->getId())
1106
+ {
1107
+ $productcode = $product->getSku();
1108
+ $productname = $product->getName();
1109
+ }
1110
+ else
1111
+ {
1112
+ $product = Mage::getModel('catalog/product');
1113
+ }
1114
+ }
1115
+
1116
+ if(!$product)
1117
+ {
1118
+ $product = Mage::getModel('catalog/product');
1119
+ $adjustStock = false;
1120
+ }
1121
+
1122
+ $qty = (int)$orderline->quantity[0];
1123
+ $subtotalinctax = floatval($orderline->linetotalinctax[0]);
1124
+ $subtotal = floatval($orderline->linetotal[0]);
1125
+
1126
+ $totalquantity += $qty;
1127
+
1128
+ $price = floatval($orderline->price[0]);
1129
+ $priceinctax = floatval($orderline->priceinctax[0]);
1130
+ $taxamount = $priceinctax - $price;
1131
+ $taxpercent = $price == 0 ? 0 : round($priceinctax / $price - 1.0, 2) * 100;
1132
+ $weight = floatval($orderline->weight[0]);
1133
+ if($weight == 0)
1134
+ $weight = 1;
1135
+
1136
+ $weight_total += $weight;
1137
+
1138
+ $itemFound = false;
1139
+ foreach($order->getAllItems() as $item)
1140
+ {
1141
+ if(!isset($visited[$item->getId()]))
1142
+ {
1143
+ if($productid)
1144
+ {
1145
+ if($item->getProductId() == $productid)
1146
+ {
1147
+ $itemFound = true;
1148
+ $visited[$item->getId()] = true;
1149
+ break;
1150
+ }
1151
+ }
1152
+ else
1153
+ {
1154
+ if($item->getSku() == $productcode)
1155
+ {
1156
+ $itemFound = true;
1157
+ $visited[$item->getId()] = true;
1158
+ break;
1159
+ }
1160
+ }
1161
+ }
1162
+ }
1163
+
1164
+ if(!$itemFound)
1165
+ {
1166
+ $item = $quoteConverter->itemToOrderItem($quoteItems[$quoteIdx]);
1167
+ }
1168
+
1169
+ $quoteIdx++;
1170
+
1171
+ $item->setStoreId($store->getId());
1172
+
1173
+ $item->setData('product', $product);
1174
+
1175
+ if($productid)
1176
+ $item->setProductId($productid);
1177
+
1178
+ if($productid)
1179
+ $item->setBaseCost($product->getCost());
1180
+
1181
+ if($productid)
1182
+ {
1183
+ $item->setOriginalPrice($product->getFinalPrice());
1184
+ $item->setBaseOriginalPrice($product->getFinalPrice());
1185
+ }
1186
+ else
1187
+ {
1188
+ $item->setOriginalPrice($priceinctax);
1189
+ $item->setBaseOriginalPrice($priceinctax);
1190
+ }
1191
+
1192
+ $item->setIsVirtual(false);
1193
+ $item->setProductType('simple');
1194
+ $item->setSku($productcode);
1195
+ $item->setName($productname);
1196
+ $item->setIsQtyDecimal(false);
1197
+ $item->setNoDiscount(true);
1198
+ $item->setQtyOrdered($qty);
1199
+ $item->setPrice($price);
1200
+ $item->setPriceInclTax($priceinctax);
1201
+ $item->setBasePrice($price);
1202
+ $item->setBasePriceInclTax($priceinctax);
1203
+ $item->setTaxPercent($taxpercent);
1204
+ $item->setTaxAmount($taxamount);
1205
+ $item->setTaxBeforeDiscount($taxamount);
1206
+ $item->setBaseTaxBeforeDiscount($taxamount);
1207
+ $item->setDiscountAmount(0);
1208
+ $item->setWeight($weight);
1209
+ $item->setBaseRowTotal($subtotal);
1210
+ $item->setBaseRowTotalInclTax($subtotalinctax);
1211
+ $item->setRowTotal($subtotal);
1212
+ $item->setRowTotalInclTax($subtotalinctax);
1213
+ $item->setWeeeTaxApplied(serialize(array()));
1214
+
1215
+ if(!$itemFound)
1216
+ $order->addItem($item);
1217
+
1218
+ if($ordercontent->orderstate != 'cancelled')
1219
+ {
1220
+ if($adjustStock)
1221
+ {
1222
+ $stockItem = $product->getStockItem();
1223
+ if(!$stockItem)
1224
+ {
1225
+ $stockItem = Mage::getModel('cataloginventory/stock_item')
1226
+ ->loadByProduct($product)
1227
+ ->setStoreId($store->getId());
1228
+ }
1229
+
1230
+ $typeId = $product->getTypeId();
1231
+ if(!$typeId)
1232
+ $typeId = 'simple';
1233
+
1234
+ if(Mage::helper('catalogInventory')->isQty($typeId))
1235
+ {
1236
+ if($stockItem->canSubtractQty())
1237
+ {
1238
+ $stockReserved = isset($orderlineStockReserved[$productid]) ? $orderlineStockReserved[$productid] : 0;
1239
+
1240
+ $stockMovement = $qty - $stockReserved;
1241
+
1242
+ if($stockMovement > 0)
1243
+ {
1244
+ $productsToReindex[$product->getId()] = $product->getId();
1245
+
1246
+ $stockItem->subtractQty($stockMovement);
1247
+ $stockItem->save();
1248
+ }
1249
+ else if($stockMovement < 0)
1250
+ {
1251
+ $productsToReindex[$product->getId()] = $product->getId();
1252
+
1253
+ $stockMovement = abs($stockMovement);
1254
+
1255
+ $stockItem->addQty($stockMovement);
1256
+ $stockItem->save();
1257
+ }
1258
+ }
1259
+ }
1260
+ }
1261
+ }
1262
+ }
1263
+ }
1264
+
1265
+ $visited = array();
1266
+ foreach($order->getAllItems() as $item)
1267
+ {
1268
+ $itemFound = false;
1269
+
1270
+ $orderlineIndex = 0;
1271
+ foreach($ordercontent->orderlines->orderline as $orderline)
1272
+ {
1273
+ if(!isset($visited[$orderlineIndex]) &&
1274
+ $orderline->productcode[0] != 'FREIGHT')
1275
+ {
1276
+ $productcode = $orderline->productcode[0];
1277
+ if($productcode == null)
1278
+ $productcode = '';
1279
+ else
1280
+ $productcode = (string)$productcode;
1281
+
1282
+ $productname = $orderline->productname[0];
1283
+ if($productname == null)
1284
+ $productname = '';
1285
+ else
1286
+ $productname = (string)$productname;
1287
+
1288
+ $productid = $orderline->externalreference[0];
1289
+ if($productid != null)
1290
+ {
1291
+ $productid = intval($productid);
1292
+ }
1293
+
1294
+ if($productid)
1295
+ {
1296
+ if($item->getProductId() == $productid)
1297
+ {
1298
+ $itemFound = true;
1299
+ $visited[$orderlineIndex] = true;
1300
+ }
1301
+ }
1302
+ else
1303
+ {
1304
+ if($item->getSku() == $productcode)
1305
+ {
1306
+ $itemFound = true;
1307
+ $visited[$orderlineIndex] = true;
1308
+ }
1309
+ }
1310
+ }
1311
+
1312
+ $orderlineIndex++;
1313
+ }
1314
+
1315
+ if(!$itemFound)
1316
+ $item->delete();
1317
+ }
1318
+
1319
+ $order->setTotalQtyOrdered((int)$totalquantity);
1320
+ $order->setWeight($weight_total);
1321
+
1322
+ /* States: cancelled, processing, captured, inprogress, complete */
1323
+ if(($ordercontent->orderstate == 'captured' ||
1324
+ $ordercontent->paymentstatus != 'complete') &&
1325
+ ($orderstatus!=Mage_Sales_Model_Order::STATE_PROCESSING &&
1326
+ $orderstatus!=Mage_Sales_Model_Order::STATE_PENDING_PAYMENT &&
1327
+ $orderstatus!=Mage_Sales_Model_Order::STATE_NEW))
1328
+ {
1329
+
1330
+ $order->setState(Mage_Sales_Model_Order::STATE_PENDING_PAYMENT);
1331
+ $order->setStatus(Mage_Sales_Model_Order::STATE_PENDING_PAYMENT);
1332
+ $order->addStatusToHistory($order->getStatus(), "eBay Order $ebaysalesrecordnumber is pending payment");
1333
+ }
1334
+
1335
+ if($ordercontent->orderstate == 'cancelled' && $orderstatus!=Mage_Sales_Model_Order::STATE_CANCELED)
1336
+ {
1337
+ $order->setState(Mage_Sales_Model_Order::STATE_CANCELED);
1338
+ $order->setStatus(Mage_Sales_Model_Order::STATE_CANCELED);
1339
+ $order->addStatusToHistory($order->getStatus(), "eBay Order $ebaysalesrecordnumber has been cancelled");
1340
+ }
1341
+
1342
+ if(($ordercontent->orderstate == 'inprogress' || $ordercontent->orderstate == 'processing') &&
1343
+ $ordercontent->paymentstatus == 'complete' &&
1344
+ $orderstatus!=Mage_Sales_Model_Order::STATE_PROCESSING &&
1345
+ $orderstatus!=Mage_Sales_Model_Order::STATE_COMPLETE)
1346
+ {
1347
+ $order->setState(Mage_Sales_Model_Order::STATE_PROCESSING);
1348
+ $order->setStatus(Mage_Sales_Model_Order::STATE_PROCESSING);
1349
+ $order->addStatusToHistory($order->getStatus(), "eBay Order $ebaysalesrecordnumber is in progress");
1350
+ }
1351
+
1352
+ if($ordercontent->orderstate == 'complete' &&
1353
+ $orderstatus!=Mage_Sales_Model_Order::STATE_COMPLETE)
1354
+ {
1355
+
1356
+ $order->setData('state', Mage_Sales_Model_Order::STATE_COMPLETE);
1357
+ $order->setData('status', Mage_Sales_Model_Order::STATE_COMPLETE);
1358
+ $order->addStatusToHistory($order->getStatus(), "eBay Order $ebaysalesrecordnumber is complete");
1359
+ }
1360
+
1361
+ if(
1362
+ ($ordercontent->orderstate == 'cancelled' && $orderstatus!= Mage_Sales_Model_Order::STATE_CANCELED) ||
1363
+ ($ordercontent->orderstate != 'cancelled' && $orderstatus == Mage_Sales_Model_Order::STATE_CANCELED))
1364
+ {
1365
+ foreach($ordercontent->orderlines->orderline as $orderline)
1366
+ {
1367
+ if($orderline->productcode[0] != 'FREIGHT')
1368
+ {
1369
+ $catalog = Mage::getModel('catalog/product');
1370
+ $prodid = $catalog->getIdBySku((string)$orderline->productcode[0]);
1371
+
1372
+ if($prodid)
1373
+ {
1374
+ $product = Mage::getModel('catalog/product')->load($prodid);
1375
+ if($product)
1376
+ {
1377
+ $qty = $orderline->quantity[0];
1378
+ $totalquantity += $qty;
1379
+
1380
+ $stockItem = $product->getStockItem();
1381
+ if(!$stockItem)
1382
+ {
1383
+ $stockItem = Mage::getModel('cataloginventory/stock_item')
1384
+ ->loadByProduct($product)
1385
+ ->setStoreId($store->getId());
1386
+ }
1387
+
1388
+ $typeId = $product->getTypeId();
1389
+ if(!$typeId)
1390
+ $typeId = 'simple';
1391
+
1392
+ if(Mage::helper('catalogInventory')->isQty($typeId))
1393
+ {
1394
+ if($stockItem->canSubtractQty())
1395
+ {
1396
+ if($ordercontent->orderstate == 'cancelled') {
1397
+
1398
+ $productsToReindex[$product->getId()] = $product->getId();
1399
+
1400
+ $stockItem->addQty(intval($qty));
1401
+
1402
+ } else {
1403
+
1404
+ $productsToReindex[$product->getId()] = $product->getId();
1405
+
1406
+ $stockItem->subtractQty(intval($qty));
1407
+
1408
+ }
1409
+
1410
+ $stockItem->save();
1411
+ }
1412
+ }
1413
+ }
1414
+ }
1415
+
1416
+ }
1417
+ }
1418
+ }
1419
+
1420
+ if($ordercontent->paymentstatus == 'complete')
1421
+ {
1422
+ $order->setBaseTotalPaid($ordertotal);
1423
+ $order->setTotalPaid($ordertotal);
1424
+ $order->setBaseTotalDue(0.0);
1425
+ $order->setTotalDue(0.0);
1426
+ $order->setDue(0.0);
1427
+
1428
+ $payment = $order->getPayment();
1429
+
1430
+ if($paypaltransactionid)
1431
+ {
1432
+ $transaction = $payment->getTransaction(0);
1433
+ if($transaction)
1434
+ {
1435
+ $transaction->setTxnId($paypaltransactionid);
1436
+ $payment->setLastTransId($paypaltransactionid);
1437
+ }
1438
+ }
1439
+
1440
+ $payment->setMethod('ebay');
1441
+ $payment->setParentTransactionId(null)
1442
+ ->setIsTransactionClosed(1);
1443
+
1444
+ $payment->save();
1445
+ }
1446
+ else
1447
+ {
1448
+ $payment = $order->getPayment();
1449
+ $payment->setMethod('ebay');
1450
+ $payment->save();
1451
+ }
1452
+
1453
+ $order->save();
1454
+
1455
+ if(!$order->hasInvoices())
1456
+ {
1457
+ if($ordercontent->paymentstatus == 'complete' && $order->canInvoice())
1458
+ {
1459
+ $invoice = Mage::getModel('sales/service_order', $order)->prepareInvoice();
1460
+
1461
+ if($invoice->getTotalQty())
1462
+ {
1463
+ $invoice->setRequestedCaptureCase(Mage_Sales_Model_Order_Invoice::CAPTURE_OFFLINE);
1464
+ $invoice->register();
1465
+ }
1466
+ $invoice->save();
1467
+
1468
+ if(!in_array($invoice->getId(), $invoiceids))
1469
+ $invoiceids[] = $invoice->getId();
1470
+
1471
+ $order->setBaseSubtotalInvoiced($ordersubtotal);
1472
+ $order->setBaseTaxInvoiced($ordertaxtotal);
1473
+ $order->setBaseTotalInvoiced($ordertotal);
1474
+ $order->setSubtotalInvoiced($ordersubtotal);
1475
+ $order->setTaxInvoiced($ordertaxtotal);
1476
+ $order->setTotalInvoiced($ordertotal);
1477
+ $order->save();
1478
+
1479
+ Mage::dispatchEvent('sales_order_payment_pay', array('payment' => $payment, 'invoice' => $invoice));
1480
+ }
1481
+ }
1482
+
1483
+ $response = $this->getResponse();
1484
+
1485
+ $response->clearAllHeaders();
1486
+ //@codingStandardsIgnoreStart
1487
+ if(function_exists('http_response_code'))
1488
+ http_response_code(200);
1489
+ //@codingStandardsIgnoreEnd
1490
+ $response->setHttpResponseCode(200);
1491
+ $response->setRawHeader('HTTP/1.0 200 OK');
1492
+ $response->setRawHeader('Status: 200 OK');
1493
+ $response->setHeader('Content-Type', 'application/json');
1494
+ $response->setHeader('Expires', 'Thu, 01 Jan 1970 00:00:00 GMT', true);
1495
+ $response->setHeader('Cache-Control', 'no-cache, must-revalidate', true);
1496
+ $response->setHeader('Pragma', 'no-cache', true);
1497
+ $response->setBody(Zend_Json::encode(array( 'ack' => 'ok', 'orderid' => $order->getIncrementId())));
1498
+
1499
+ if(!in_array($order->getId(), $orderids))
1500
+ $orderids[] = $order->getId();
1501
+ }
1502
+
1503
+ private function ProcessQuote($quote, $xml, $store)
1504
+ {
1505
+ $connection = Mage::getSingleton('core/resource')->getConnection('core_write');
1506
+
1507
+ $ordercontent = $xml->entry->content->children('http://api.codisto.com/schemas/2009/');
1508
+
1509
+ $register_customer = (string)$ordercontent->register_customer == 'false' ? false : true;
1510
+
1511
+ $websiteId = $store->getWebsiteId();
1512
+
1513
+ $billing_address = $ordercontent->orderaddresses->orderaddress[0];
1514
+ $billing_first_name = $billing_last_name = '';
1515
+
1516
+ if(strpos($billing_address->name, ' ') !== false) {
1517
+ $billing_name = explode(' ', $billing_address->name, 2);
1518
+ $billing_first_name = $billing_name[0];
1519
+ $billing_last_name = $billing_name[1];
1520
+ } else {
1521
+ $billing_first_name = $billing_address->name;
1522
+ }
1523
+
1524
+ $shipping_address = $ordercontent->orderaddresses->orderaddress[1];
1525
+ $shipping_first_name = $shipping_last_name = '';
1526
+
1527
+ if(strpos($shipping_address->name, ' ') !== false) {
1528
+ $shipping_name = explode(' ', $shipping_address->name, 2);
1529
+ $shipping_first_name = $shipping_name[0];
1530
+ $shipping_last_name = $shipping_name[1];
1531
+ } else {
1532
+ $shipping_first_name = $shipping_address->name;
1533
+ }
1534
+
1535
+ $email = (string)$billing_address->email;
1536
+ if(!$email)
1537
+ $email = 'mail@example.com';
1538
+
1539
+ $regionCollection = $this->getRegionCollection($billing_address->countrycode);
1540
+
1541
+ $regionsel_id = 0;
1542
+ foreach($regionCollection as $region)
1543
+ {
1544
+ if(in_array($billing_address->division, array($region['code'], $region['name'])))
1545
+ {
1546
+
1547
+ $regionsel_id = $region['region_id'];
1548
+ }
1549
+ }
1550
+
1551
+ $addressBilling = array(
1552
+ 'email' => $email,
1553
+ 'prefix' => '',
1554
+ 'suffix' => '',
1555
+ 'company' => (string)$billing_address->companyname,
1556
+ 'firstname' => (string)$billing_first_name,
1557
+ 'middlename' => '',
1558
+ 'lastname' => (string)$billing_last_name,
1559
+ 'street' => (string)$billing_address->address1.($billing_address->address2 ? "\n".$billing_address->address2 : ''),
1560
+ 'city' => (string)$billing_address->place,
1561
+ 'postcode' => (string)$billing_address->postalcode,
1562
+ 'telephone' => (string)$billing_address->phone,
1563
+ 'fax' => '',
1564
+ 'country_id' => (string)$billing_address->countrycode,
1565
+ 'region_id' => $regionsel_id, // id from directory_country_region table
1566
+ 'region' => (string)$billing_address->division
1567
+ );
1568
+
1569
+ $regionsel_id_ship = 0;
1570
+ foreach($regionCollection as $region)
1571
+ {
1572
+ if(in_array($shipping_address->division, array($region['code'], $region['name'])))
1573
+ {
1574
+ $regionsel_id_ship = $region['region_id'];
1575
+ }
1576
+ }
1577
+
1578
+ $addressShipping = array(
1579
+ 'email' => $email,
1580
+ 'prefix' => '',
1581
+ 'suffix' => '',
1582
+ 'company' => (string)$shipping_address->companyname,
1583
+ 'firstname' => (string)$shipping_first_name,
1584
+ 'middlename' => '',
1585
+ 'lastname' => (string)$shipping_last_name,
1586
+ 'street' => (string)$shipping_address->address1.($shipping_address->address2 ? "\n".$shipping_address->address2 : ''),
1587
+ 'city' => (string)$shipping_address->place,
1588
+ 'postcode' => (string)$shipping_address->postalcode,
1589
+ 'telephone' => (string)$shipping_address->phone,
1590
+ 'fax' => '',
1591
+ 'country_id' => (string)$shipping_address->countrycode,
1592
+ 'region_id' => $regionsel_id_ship, // id from directory_country_region table
1593
+ 'region' => (string)$shipping_address->division
1594
+ );
1595
+
1596
+ $customer = null;
1597
+
1598
+ if($register_customer)
1599
+ {
1600
+ $customer = Mage::getModel('customer/customer');
1601
+ $customer->setWebsiteId($websiteId);
1602
+ $customer->setStoreId($store->getId());
1603
+
1604
+ for($Retry = 0; ; $Retry++)
1605
+ {
1606
+ try
1607
+ {
1608
+ $connection->query('SET TRANSACTION ISOLATION LEVEL SERIALIZABLE');
1609
+ $connection->beginTransaction();
1610
+
1611
+ $customer->loadByEmail($email);
1612
+
1613
+ if(!$customer->getId())
1614
+ {
1615
+ $ebayGroup = Mage::getModel('customer/group');
1616
+ $ebayGroup->load('eBay', 'customer_group_code');
1617
+ if(!$ebayGroup->getId())
1618
+ {
1619
+ $defaultGroup = Mage::getModel('customer/group')->load(1);
1620
+
1621
+ $ebayGroup->setCode('eBay');
1622
+ $ebayGroup->setTaxClassId($defaultGroup->getTaxClassId());
1623
+ $ebayGroup->save();
1624
+ }
1625
+
1626
+ $customerGroupId = $ebayGroup->getId();
1627
+
1628
+ $customer->setWebsiteId($websiteId);
1629
+ $customer->setStoreId($store->getId());
1630
+ $customer->setEmail($email);
1631
+ $customer->setFirstname((string)$billing_first_name);
1632
+ $customer->setLastname((string)$billing_last_name);
1633
+ $customer->setPassword('');
1634
+ $customer->setGroupId($customerGroupId);
1635
+ $customer->save();
1636
+ $customer->setConfirmation(null);
1637
+ $customer->save();
1638
+
1639
+ $customerId = $customer->getId();
1640
+
1641
+ $customerAddress = Mage::getModel('customer/address');
1642
+ $customerAddress->setData($addressBilling)
1643
+ ->setCustomerId($customer->getId())
1644
+ ->setIsDefaultBilling(1)
1645
+ ->setSaveInAddressBook(1);
1646
+ $customerAddress->save();
1647
+
1648
+
1649
+ $customerAddress->setData($addressShipping)
1650
+ ->setCustomerId($customer->getId())
1651
+ ->setIsDefaultShipping(1)
1652
+ ->setSaveInAddressBook(1);
1653
+ $customerAddress->save();
1654
+ }
1655
+ else
1656
+ {
1657
+ $customerId = $customer->getId();
1658
+ $customerGroupId = $customer->getGroupId();
1659
+ }
1660
+
1661
+ $connection->commit();
1662
+ break;
1663
+ }
1664
+ catch(Exception $e)
1665
+ {
1666
+ if($Retry < 5)
1667
+ {
1668
+ if($e->getCode() == 40001)
1669
+ {
1670
+ $connection->rollback();
1671
+ sleep($Retry * 10);
1672
+ continue;
1673
+ }
1674
+ }
1675
+
1676
+ $connection->rollback();
1677
+ throw $e;
1678
+ }
1679
+ }
1680
+ }
1681
+
1682
+ $currencyCode = $ordercontent->transactcurrency[0];
1683
+ $ordertotal = floatval($ordercontent->ordertotal[0]);
1684
+ $ordersubtotal = floatval($ordercontent->ordersubtotal[0]);
1685
+ $ordertaxtotal = floatval($ordercontent->ordertaxtotal[0]);
1686
+
1687
+ $ordersubtotal = $store->roundPrice($ordersubtotal);
1688
+ $ordersubtotalincltax = $store->roundPrice($ordersubtotal + $ordertaxtotal);
1689
+ $ordertotal = $store->roundPrice($ordertotal);
1690
+
1691
+ $quote->setIsSuperMode(true);
1692
+ $quote->setStore($store);
1693
+ $quote->setCheckoutMethod(Mage_Checkout_Model_Type_Onepage::METHOD_GUEST);
1694
+ $quote->save();
1695
+
1696
+ if($customer)
1697
+ {
1698
+ $quote->assignCustomer($customer);
1699
+ $quote->setCustomerId($customerId);
1700
+ $quote->setCustomerGroupId($customerGroupId);
1701
+ }
1702
+ else
1703
+ {
1704
+ $quote->setCustomerId(null);
1705
+ $quote->setCustomerEmail($email);
1706
+ $quote->setCustomerFirstName((string)$billing_first_name);
1707
+ $quote->setCustomerLastName((string)$billing_last_name);
1708
+ $quote->setCustomerIsGuest(true);
1709
+ $quote->setCustomerGroupId(Mage_Customer_Model_Group::NOT_LOGGED_IN_ID);
1710
+ }
1711
+
1712
+ $billingAddress = $quote->getBillingAddress();
1713
+ if($customer)
1714
+ $billingAddress->setCustomer($customer);
1715
+ $billingAddress->addData($addressBilling);
1716
+
1717
+ $shippingAddress = $quote->getShippingAddress();
1718
+ if($customer)
1719
+ $shippingAddress->setCustomer($customer);
1720
+ $shippingAddress->addData($addressShipping);
1721
+ $shippingAddress->implodeStreetAddress();
1722
+
1723
+ $totalitemcount = 0;
1724
+ $totalitemqty = 0;
1725
+
1726
+ foreach($ordercontent->orderlines->orderline as $orderline)
1727
+ {
1728
+ if($orderline->productcode[0] != 'FREIGHT')
1729
+ {
1730
+ $adjustStock = true;
1731
+
1732
+ $product = null;
1733
+ $productcode = (string)$orderline->productcode;
1734
+ if($productcode == null)
1735
+ $productcode = '';
1736
+ $productname = (string)$orderline->productname;
1737
+ if($productname == null)
1738
+ $productname = '';
1739
+
1740
+ $productid = $orderline->externalreference[0];
1741
+ if($productid != null)
1742
+ {
1743
+ $productid = intval($productid);
1744
+
1745
+ $product = Mage::getModel('catalog/product')->load($productid);
1746
+ if($product->getId())
1747
+ {
1748
+ $productcode = $product->getSku();
1749
+ $productname = $product->getName();
1750
+ }
1751
+ else
1752
+ {
1753
+ $product = null;
1754
+ }
1755
+ }
1756
+
1757
+ if(!$product)
1758
+ {
1759
+ $product = Mage::getModel('catalog/product');
1760
+ }
1761
+
1762
+ $product->setIsSuperMode(true);
1763
+
1764
+ $qty = (int)$orderline->quantity[0];
1765
+ $subtotalinctax = floatval($orderline->linetotalinctax[0]);
1766
+ $subtotal = floatval($orderline->linetotal[0]);
1767
+
1768
+ $totalitemcount += 1;
1769
+ $totalitemqty += $qty;
1770
+
1771
+ $price = floatval($orderline->price[0]);
1772
+ $priceinctax = floatval($orderline->priceinctax[0]);
1773
+ $taxamount = $priceinctax - $price;
1774
+ $taxpercent = $price == 0 ? 0 : round($priceinctax / $price - 1.0, 2) * 100;
1775
+ $weight = floatval($orderline->weight[0]);
1776
+
1777
+ $item = Mage::getModel('sales/quote_item');
1778
+ $item->setStoreId($store->getId());
1779
+ $item->setQuote($quote);
1780
+
1781
+ $item->setData('product', $product);
1782
+ $item->setProductId($productid);
1783
+ $item->setProductType('simple');
1784
+ $item->setIsRecurring(false);
1785
+
1786
+ if($productid)
1787
+ $item->setTaxClassId($product->getTaxClassId());
1788
+
1789
+ if($productid)
1790
+ $item->setBaseCost($product->getCost());
1791
+
1792
+ $item->setSku($productcode);
1793
+ $item->setName($productname);
1794
+ $item->setIsVirtual(false);
1795
+ $item->setIsQtyDecimal(false);
1796
+ $item->setNoDiscount(true);
1797
+ $item->setWeight($weight);
1798
+ $item->setData('qty', $qty);
1799
+ $item->setPrice($price);
1800
+ $item->setBasePrice($price);
1801
+ $item->setCustomPrice($price);
1802
+ $item->setDiscountPercent(0);
1803
+ $item->setDiscountAmount(0);
1804
+ $item->setBaseDiscountAmount(0);
1805
+ $item->setTaxPercent($taxpercent);
1806
+ $item->setTaxAmount($taxamount);
1807
+ $item->setBaseTaxAmount($taxamount);
1808
+ $item->setRowTotal($subtotal);
1809
+ $item->setBaseRowTotal($subtotal);
1810
+ $item->setRowTotalWithDiscount($subtotal);
1811
+ $item->setRowWeight($weight * $qty);
1812
+ $item->setOriginalCustomPrice($price);
1813
+ $item->setPriceInclTax($priceinctax);
1814
+ $item->setBasePriceInclTax($priceinctax);
1815
+ $item->setRowTotalInclTax($subtotalinctax);
1816
+ $item->setBaseRowTotalInclTax($subtotalinctax);
1817
+ $item->setWeeeTaxApplied(serialize(array()));
1818
+
1819
+ $quote->getItemsCollection()->addItem($item);
1820
+ }
1821
+ }
1822
+
1823
+ $freighttotal = 0.0;
1824
+ $freighttotalextax = 0.0;
1825
+ $freighttax = 0.0;
1826
+ $freightservice = '';
1827
+
1828
+ foreach($ordercontent->orderlines->orderline as $orderline)
1829
+ {
1830
+ if($orderline->productcode[0] == 'FREIGHT')
1831
+ {
1832
+ $freighttotal += floatval($orderline->linetotalinctax[0]);
1833
+ $freighttotalextax += floatval($orderline->linetotal[0]);
1834
+ $freighttax = (float)$freighttotal - $freighttotalextax;
1835
+ $freightservice = $orderline->productname[0];
1836
+ }
1837
+ }
1838
+
1839
+ $ordersubtotal -= $freighttotalextax;
1840
+ $ordersubtotalincltax -= $freighttotal;
1841
+ $ordertaxtotal -= $freighttax;
1842
+
1843
+ $quotePayment = $quote->getPayment();
1844
+ $quotePayment->setMethod('ebay');
1845
+ $quotePayment->save();
1846
+
1847
+ $quote->setBaseCurrencyCode($currencyCode);
1848
+ $quote->setStoreCurrencyCode($currencyCode);
1849
+ $quote->setQuoteCurrencyCode($currencyCode);
1850
+ $quote->setItemsCount($totalitemcount);
1851
+ $quote->setItemsQty($totalitemqty);
1852
+ $quote->setVirtualItemsQty(0);
1853
+ $quote->setGrandTotal($ordertotal);
1854
+ $quote->setBaseGrandTotal($ordertotal);
1855
+ $quote->setSubtotal($ordersubtotal);
1856
+ $quote->setBaseSubtotal($ordersubtotal);
1857
+ $quote->setSubtotal($ordersubtotal);
1858
+ $quote->setBaseSubtotalWithDiscount($ordersubtotal);
1859
+ $quote->setSubtotalWithDiscount($ordersubtotal);
1860
+ $quote->setData('trigger_recollect', 0);
1861
+ $quote->setTotalsCollectedFlag(true);
1862
+ $quote->save();
1863
+
1864
+ $customerInstruction = @count($ordercontent->instructions) ? strval($ordercontent->instructions) : '';
1865
+
1866
+ $checkoutSession = Mage::getSingleton('checkout/session');
1867
+ $checkoutSession->setCustomer($customer);
1868
+ $checkoutSession->replaceQuote($quote);
1869
+ $checkoutSession->setData('customer_comment', $customerInstruction);
1870
+ $checkoutSession->setData('destination_type', 'residence');
1871
+
1872
+ $shippingAddress = $quote->getShippingAddress();
1873
+ $shippingAddress->setSubtotal($ordersubtotal);
1874
+ $shippingAddress->setBaseSubtotal($ordersubtotal);
1875
+ $shippingAddress->setSubtotalWithDiscount($ordersubtotal);
1876
+ $shippingAddress->setBaseSubtotalWithDiscount($ordersubtotal);
1877
+ $shippingAddress->setTaxAmount($ordertaxtotal);
1878
+ $shippingAddress->setBaseTaxAmount($ordertaxtotal);
1879
+ $shippingAddress->setShippingTaxAmount($freighttax);
1880
+ $shippingAddress->setBaseShippingTaxAmount($freighttax);
1881
+ $shippingAddress->setDiscountAmount(0);
1882
+ $shippingAddress->setBaseDiscountAmount(0);
1883
+ $shippingAddress->setGrandTotal($ordertotal);
1884
+ $shippingAddress->setBaseGrandTotal($ordertotal);
1885
+ $shippingAddress->setAppliedTaxes(array());
1886
+ $shippingAddress->setShippingDiscountAmount(0);
1887
+ $shippingAddress->setBaseShippingDiscountAmount(0);
1888
+ $shippingAddress->setSubtotalInclTax($ordersubtotalincltax);
1889
+ $shippingAddress->setBaseSubtotalTotalInclTax($ordersubtotalincltax);
1890
+
1891
+ $freightcode = 'flatrate_flatrate';
1892
+ $freightcarrier = 'Post';
1893
+ $freightcarriertitle = 'Post';
1894
+ $freightmethod = 'Freight';
1895
+ $freightmethodtitle = 'Freight';
1896
+ $freightmethoddescription = '';
1897
+ $freighttotal = 0.0;
1898
+ $freighttotalextax = 0.0;
1899
+ $freighttax = 0.0;
1900
+ $taxpercent = 0.0;
1901
+ $taxrate = 1.0;
1902
+
1903
+ $freightcost = null;
1904
+ $freightRate = null;
1905
+
1906
+ try {
1907
+
1908
+ $shippingRequest = Mage::getModel('shipping/rate_request');
1909
+ $shippingRequest->setAllItems($quote->getAllItems());
1910
+ $shippingRequest->setDestCountryId($shippingAddress->getCountryId());
1911
+ $shippingRequest->setDestRegionId($shippingAddress->getRegionId());
1912
+ $shippingRequest->setDestRegionCode($shippingAddress->getRegionCode());
1913
+ $shippingRequest->setDestStreet($shippingAddress->getStreet(-1));
1914
+ $shippingRequest->setDestCity($shippingAddress->getCity());
1915
+ $shippingRequest->setDestPostcode($shippingAddress->getPostcode());
1916
+ $shippingRequest->setPackageValue($quote->getBaseSubtotal());
1917
+ $shippingRequest->setPackageValueWithDiscount($quote->getBaseSubtotalWithDiscount());
1918
+ $shippingRequest->setPackageWeight($quote->getWeight());
1919
+ $shippingRequest->setPackageQty($quote->getItemQty());
1920
+ $shippingRequest->setPackagePhysicalValue($quote->getBaseSubtotal());
1921
+ $shippingRequest->setFreeMethodWeight(0);
1922
+ $shippingRequest->setStoreId($store->getId());
1923
+ $shippingRequest->setWebsiteId($store->getWebsiteId());
1924
+ $shippingRequest->setFreeShipping(false);
1925
+ $shippingRequest->setBaseCurrency($currencyCode);
1926
+ $shippingRequest->setPackageCurrency($currencyCode);
1927
+ $shippingRequest->setBaseSubtotalInclTax($quote->getBaseSubtotalInclTax());
1928
+
1929
+ $shippingResult = Mage::getModel('shipping/shipping')->collectRates($shippingRequest)->getResult();
1930
+
1931
+ $shippingRates = $shippingResult->getAllRates();
1932
+
1933
+ foreach($shippingRates as $shippingRate)
1934
+ {
1935
+ if($shippingRate instanceof Mage_Shipping_Model_Rate_Result_Method)
1936
+ {
1937
+ if(is_null($freightcost) || (!is_null($shippingRate->getPrice()) && $shippingRate->getPrice() < $freightcost))
1938
+ {
1939
+ $isPickup = $shippingRate->getPrice() == 0 &&
1940
+ (preg_match('/(?:^|\W|_)pick\s*up(?:\W|_|$)/i', strval($shippingRate->getMethod())) ||
1941
+ preg_match('/(?:^|\W|_)pick\s*up(?:\W|_|$)/i', strval($shippingRate->getCarrierTitle())) ||
1942
+ preg_match('/(?:^|\W|_)pick\s*up(?:\W|_|$)/i', strval($shippingRate->getMethodTitle())));
1943
+
1944
+ if(!$isPickup)
1945
+ {
1946
+ $freightRate = Mage::getModel('sales/quote_address_rate')
1947
+ ->importShippingRate($shippingRate);
1948
+
1949
+ $freightcode = $freightRate->getCode();
1950
+ $freightcarrier = $freightRate->getCarrier();
1951
+ $freightcarriertitle = $freightRate->getCarrierTitle();
1952
+ $freightmethod = $freightRate->getMethod();
1953
+ $freightmethodtitle = $freightRate->getMethodTitle();
1954
+ $freightmethoddescription = $freightRate->getMethodDescription();
1955
+ }
1956
+ }
1957
+ }
1958
+ }
1959
+ }
1960
+ catch(Exception $e)
1961
+ {
1962
+
1963
+ }
1964
+
1965
+ if(!$freightRate)
1966
+ {
1967
+ $freightRate = Mage::getModel('sales/quote_address_rate');
1968
+ $freightRate->setCode($freightcode)
1969
+ ->setCarrier($freightcarrier)
1970
+ ->setCarrierTitle($freightcarriertitle)
1971
+ ->setMethod($freightmethod)
1972
+ ->setMethodTitle($freightmethodtitle)
1973
+ ->setMethodDescription($freightmethoddescription)
1974
+ ->setPrice($freighttotal);
1975
+ }
1976
+
1977
+ $shippingAddress->addShippingRate($freightRate);
1978
+ $shippingAddress->setShippingMethod($freightcode);
1979
+ $shippingAddress->setShippingDescription($freightmethodtitle);
1980
+ $shippingAddress->setShippingAmount($freighttotal);
1981
+ $shippingAddress->setBaseShippingAmount($freighttotal);
1982
+ $shippingAddress->save();
1983
+ }
1984
+
1985
+ private function getRegionCollection($countryCode)
1986
+ {
1987
+ $regionCollection = Mage::getModel('directory/region_api')->items($countryCode);