public function getHtml() { $transHtml = array(); $request = $this->controller->getRequest(); if ($this->controller instanceof CheckoutController && $request->getActionName() == 'completed') { $session = new Session(); if ($orderID = $session->get('completedOrderID')) { $order = CustomerOrder::getInstanceByID((int) $session->get('completedOrderID'), CustomerOrder::LOAD_DATA); $order->loadAll(); $orderArray = $order->toArray(); $data = array($order->getID(), '', $orderArray['total'][$orderArray['Currency']['ID']], $order->getTaxAmount(), $orderArray['ShippingAddress']['city'], $orderArray['ShippingAddress']['stateName'], $orderArray['ShippingAddress']['countryID']); $transHtml[] = 'pageTracker._addTrans' . $this->getJSParams($data); foreach ($orderArray['cartItems'] as $item) { $data = array($order->getID(), $item['Product']['sku'], $item['Product']['name'], $item['Product']['Category']['name'], $item['price'], $item['count']); $transHtml[] = 'pageTracker._addItem' . $this->getJSParams($data); } } $transHtml[] = 'pageTracker._trackTrans();'; } return '<script type="text/javascript"> var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); document.write(unescape("%3Cscript src=\'" + gaJsHost + "google-analytics.com/ga.js\' type=\'text/javascript\'%3E%3C/script%3E")); </script> <script type="text/javascript"> var pageTracker = _gat._getTracker("' . $this->getValue('code') . '"); pageTracker._initData(); pageTracker._trackPageview(); ' . implode("\n", $transHtml) . ' </script>'; }
function testTransactionCurrencyConverting() { $eur = Currency::getNewInstance('EUR'); $eur->rate->set('3.4528'); $eur->save(); $this->products[0]->setPrice($this->usd, '9.99'); $this->order->addProduct($this->products[0], 1); $this->order->save(); $this->order->changeCurrency($this->usd); //$this->order->finalize(); ActiveRecord::clearPool(); $order = CustomerOrder::getInstanceByID($this->order->getID(), true); $order->loadAll(); $details = new LiveCartTransaction($order, $eur); ActiveRecord::clearPool(); $order = CustomerOrder::getInstanceByID($this->order->getID(), true); $order->loadAll(); $this->assertEquals($details->amount->get(), '2.89'); $result = new TransactionResult(); $result->amount->set($details->amount->get()); $result->currency->set($details->currency->get()); $transaction = Transaction::getNewInstance($order, $result); $transaction->type->set(Transaction::TYPE_SALE); $this->assertEquals($transaction->amount->get(), '9.99'); $this->assertEquals($transaction->realAmount->get(), '2.89'); $transaction->save(); $this->assertFalse((bool) $order->isFinalized->get()); $order->finalize(); $this->assertTrue((bool) $order->isFinalized->get()); $this->assertEquals($order->getPaidAmount(), '9.99'); $this->assertEquals($order->totalAmount->get(), '9.99'); $this->assertTrue((bool) $order->isPaid->get()); }
public function add_coupon() { $request = $this->application->getRequest(); $code = $request->get('couponCode'); $orderID = $request->get('orderID'); $response = new LiveCartSimpleXMLElement('<response datetime="' . date('c') . '"></response>'); if (strlen($code)) { $order = CustomerOrder::getInstanceByID($orderID, CustomerOrder::LOAD_DATA); $condition = DiscountCondition::getInstanceByCoupon($code); if ($condition) { if (!$order->hasCoupon($code)) { $coupon = OrderCoupon::getNewInstance($order, $code); $coupon->save(); $order->getCoupons(true); if ($order->hasCoupon($code)) { $order->loadAll(); $order->getTotal(true); $order->totalAmount->set($order->getTotal(true)); $order->getTaxAmount(); $order->save(); $response->addChild('message', 'Coupon ' . $code . ' was successfully added'); } else { throw new Exception("Cant add coupon " . $code); } } else { throw new Exception("The coupon " . $code . " already added"); } } else { throw new Exception("Cant add coupon " . $code); } $order->getCoupons(true); } else { throw new Exception("Incorrect coupon code" . $code); } return new SimpleXMLResponse($response); }
/** * @role update */ public function update() { $order = CustomerOrder::getInstanceByID((int) $this->request->get('ID')); return $this->save($order); }
public function cancel() { $order = CustomerOrder::getInstanceByID($this->getRequestID()); $order->cancel(); return $this->statusResponse($order->getID(), 'canceled'); }
public function addCoupon() { ClassLoader::import('application.model.discount.DiscountCondition'); $response = $this->getRequest(); $code = $this->request->get('coupon'); $msg = '_coupon_not_found'; $error = true; if (strlen($code)) { $order = CustomerOrder::getInstanceByID($response->get('id'), CustomerOrder::LOAD_DATA); $condition = DiscountCondition::getInstanceByCoupon($code); if ($condition) { if (!$order->hasCoupon($code)) { $coupon = OrderCoupon::getNewInstance($order, $code); $coupon->save(); $order->getCoupons(true); if ($order->hasCoupon($code)) { $msg = '_coupon_added'; $this->recalculateDiscounts(); $error = false; } else { $msg = '_cant_add_coupon'; } } else { $msg = '_coupon_already_added'; } } $order->getCoupons(true); } $this->loadLanguageFile('Order'); return new JSONResponse(null, $error ? 'failure' : 'success', $this->makeText($msg, array($code))); }
public function testUserCheckoutWithDifferentAddresses() { $this->order->addProduct($this->products[0], 1); $this->order->save(); $this->assertTrue($this->order->isShippingRequired()); $this->controller->setOrder($this->reloadOrder($this->order)); $request = $this->controller->getRequest(); $request->set('sameAsBilling', ''); $request->set('email', '*****@*****.**'); // shipping address not entered at all $request->set('billing_firstName', 'First'); $request->set('billing_lastName', 'Last'); $request->set('billing_companyName', 'CMP'); $request->set('billing_address1', 'Address 1'); $request->set('billing_state_text', 'State'); $request->set('billing_city', 'Some City'); $request->set('billing_country', 'LV'); $request->set('billing_postalCode', 'LV-1234'); $request->set('billing_phone', '1234'); $response = $this->controller->processCheckoutRegistration(); // last name was not entered, so we get back to user/checkout // with a bunch of errors for each shipping address field $this->assertIsA($response, 'ActionRedirectResponse'); $this->assertEqual($response->getControllerName(), 'user'); $this->assertEqual($response->getActionName(), 'checkout'); $this->assertTrue(1 < count($this->controller->checkout()->get('form')->getValidator()->getErrorList())); // let's forget the last name again $request->set('shipping_firstName', 'Recipient'); $request->set('shipping_companyName', 'CMP'); $request->set('shipping_address1', 'Rec Street'); $request->set('shipping_city', 'Rec City'); $request->set('shipping_state_text', 'State'); $request->set('shipping_country', 'LT'); $request->set('shipping_postalCode', 'LT-4321'); $request->set('shipping_phone', '4321'); $this->assertEqual($response->getControllerName(), 'user'); $this->assertEqual($response->getActionName(), 'checkout'); // enter that last name at last $request->set('shipping_lastName', 'Last'); $response = $this->controller->processCheckoutRegistration(); $this->assertIsA($response, 'ActionRedirectResponse'); $this->assertEqual($response->getControllerName(), 'checkout'); $this->assertEqual($response->getActionName(), 'shipping'); // verify user data $user = SessionUser::getUser(); $user->reload(true); $this->assertEquals($user->firstName->get(), 'First'); $this->assertEquals($user->defaultShippingAddress->get()->userAddress->get()->firstName->get(), 'Recipient'); $this->assertEquals($user->defaultBillingAddress->get()->userAddress->get()->countryID->get(), 'LV'); $this->assertEquals($user->defaultShippingAddress->get()->userAddress->get()->countryID->get(), 'LT'); // order address ActiveRecord::clearPool(); $order = CustomerOrder::getInstanceByID($this->order->getID(), true); $order->loadAll(); $this->assertEquals($order->shippingAddress->get()->countryID->get(), 'LT'); }
/** * @role login */ public function completed() { if ($this->request->isValueSet('id')) { return new ActionRedirectResponse('checkout', 'completeExternal', array('id' => $this->request->get('id'))); } $order = CustomerOrder::getInstanceByID((int) $this->session->get('completedOrderID'), CustomerOrder::LOAD_DATA); $order->loadAll(); $response = new ActionResponse(); $response->set('order', $order->toArray()); $response->set('url', $this->router->createUrl(array('controller' => 'user', 'action' => 'viewOrder', 'id' => $this->session->get('completedOrderID')), true)); if (!$order->isPaid->get()) { $transactions = $order->getTransactions()->toArray(); $response->set('transactions', $transactions); } else { $response->set('files', ProductFile::getOrderFiles(select(eq('CustomerOrder.ID', $order->getID())))); } return $response; }
public function create() { $request = $this->getRequest(); $query = $request->get('query'); if (strlen($query)) { $products = $this->getProductsFromSearchQuery($query); } else { $products = new ARSet(); $products->add(Product::getInstanceById((int) $this->request->get('productID'), true)); } $saveResponse = array('errors' => array(), 'items' => array()); $composite = new CompositeJSONResponse(); $order = CustomerOrder::getInstanceByID((int) $this->request->get('orderID'), true); $order->loadAll(); foreach ($products as $product) { if ($product->isDownloadable()) { $shipment = $order->getDownloadShipment(); } else { if ((int) $this->request->get('shipmentID')) { $shipment = Shipment::getInstanceById('Shipment', (int) $this->request->get('shipmentID'), true, array('Order' => 'CustomerOrder', 'ShippingService', 'ShippingAddress' => 'UserAddress', 'Currency')); } } if (empty($shipment)) { $shipment = $order->getShipments()->get(0); } if (!$shipment) { $shipment = Shipment::getNewInstance($order); } if (!$shipment->order->get()) { $shipment->order->set($order); } $history = new OrderHistory($order, $this->user); $existingItem = false; foreach ($shipment->getItems() as $item) { if ($item->getProduct() === $product) { if (!$product->getOptions(true)) { $existingItem = $item; } break; } } if ($existingItem) { $item = $existingItem; if ($product->isDownloadable()) { return new JSONResponse(false, 'failure', $this->translate('_downloadable_item_already_exists_in_this_order')); } else { $item->count->set($item->count->get() + 1); } } else { $currency = $shipment->getCurrency(); $item = OrderedItem::getNewInstance($order, $product); $item->count->set(1); $item->price->set($currency->round($item->reduceBaseTaxes($product->getPrice($currency->getID())))); $order->addItem($item); $shipment->addItem($item); $shipment->save(); } $resp = $this->save($item, $shipment, $existingItem ? true : false); if (array_key_exists('errors', $resp)) { $saveResponse['errors'] = array_merge($saveResponse['errors'], $resp['errors']); } else { if (array_key_exists('item', $resp)) { $saveResponse['items'][] = $resp['item']; } } } // for each product if (count($saveResponse['errors']) == 0) { unset($saveResponse['errors']); } if (isset($saveResponse['errors'])) { $response = new JSONResponse(array('errors' => $validator->getErrorList()), 'failure', $this->translate('_unable_to_update_items_quantity')); } else { $response = new JSONResponse($saveResponse, 'success', $this->translate('_item_has_been_successfuly_saved')); } $composite->addResponse('data', $response, $this, 'create'); $ids = array(); foreach ($saveResponse['items'] as $item) { $ids[] = $item['ID']; } $composite->addAction('html', 'backend.orderedItem', 'items'); $this->request->set('item_ids', implode(',', $ids)); $history->saveLog(); return $composite; }
private function assertInvoices($ids, $assertionRules = array()) { foreach ($assertionRules as $key => $rule) { if (is_array($rule) == false) { $assertionRules[$key] = array($rule, ''); } } $invoices = array(); if (count($ids)) { foreach ($ids as $id) { $invoice = CustomerOrder::getInstanceByID($id, true); $invoice->loadAll(); $invoices[] = $invoice; } } foreach ($assertionRules as $key => $rule) { switch ($key) { case 'count': $value = $rule[0]; $message = $rule[1]; $this->assertEquals($value, count($ids), $message); break; case 'totalPrice': $value = $rule[0]; $message = $rule[1]; $total = 0; foreach ($invoices as $invoice) { $total += $invoice->getTotal(true); } $this->assertEquals($value, $total, $message); break; case 'orderedItemCount': $value = $rule[0]; $message = $rule[1]; $total = 0; foreach ($invoices as $invoice) { $total += count($invoice->getOrderedItems()); } $this->assertEquals($value, $total, $message); break; case 'periods': $periodsInDb = array(); foreach ($invoices as $invoice) { $start = $invoice->startDate->get(); $end = $invoice->endDate->get(); $key = sprintf('%s - %s', trim($start) ? date('Y-m-d', strtotime($start)) : 'NULL', trim($end) ? date('Y-m-d', strtotime($end)) : 'NULL'); if (array_key_exists($key, $periodsInDb)) { $periodsInDb[$key]++; } else { $periodsInDb[$key] = 1; } } foreach ($rule as $period) { $periodKey = sprintf('%s - %s', $period[0], $period[1]); $message = count($period) >= 3 ? $period[2] : 'Period "' . $periodKey . '" not found'; $this->assertTrue(array_key_exists($periodKey, $periodsInDb), $message . '. Not asserted period(s) left: ' . $this->_periodsToString($periodsInDb)); $periodsInDb[$periodKey]--; if ($periodsInDb[$periodKey] == 0) { unset($periodsInDb[$periodKey]); } } $this->assertFalse((bool) count($periodsInDb), 'Required period(s): ' . $this->_periodsToString($periodsInDb) . ' was not found'); break; case 'rebillsLeft': $rebillsLeftInDb = array(); foreach ($invoices as $invoice) { $key = '_' . $invoice->rebillsLeft->get(); if (array_key_exists($key, $rebillsLeftInDb)) { $rebillsLeftInDb[$key]++; } else { $rebillsLeftInDb[$key] = 1; } } foreach ($rule as $rebillsLeft) { $rebillsLeft = '_' . $rebillsLeft; $this->assertTrue(array_key_exists($rebillsLeft, $rebillsLeftInDb), 'rebillsLeft: ' . str_replace('_', '', $rebillsLeft) . ' not found. RebillsLeft in database(' . count(array_keys($rebillsLeftInDb)) . '): ' . str_replace('_', '', implode(',', array_keys($rebillsLeftInDb)))); $rebillsLeftInDb[$rebillsLeft]--; if ($rebillsLeftInDb[$rebillsLeft] == 0) { unset($rebillsLeftInDb[$rebillsLeft]); } } $this->assertFalse((bool) count($rebillsLeftInDb), 'Required rebillLeft counts: ' . $this->_periodsToString($rebillsLeftInDb) . ' was not found'); break; } } }
public static function transformArray($array, ARSchema $schema) { $array = parent::transformArray($array, $schema); $array['formattedPrice'] = ''; if (!empty($array['OrderedItem']['customerOrderID'])) { $order = CustomerOrder::getInstanceByID($array['OrderedItem']['customerOrderID']); $currency = $order->getCurrency(); $array['formattedPrice'] = $currency->getFormattedPrice($array['priceDiff']); } // get uploaded file name if (!empty($array['optionText']) && strpos($array['optionText'], '___')) { $array['fileName'] = self::getFileName($array['optionText']); $array = array_merge($array, self::getImagePaths($array['optionText'])); } return $array; }
protected function set_OrderedItem_products($instance, $value, $record, CsvImportProfile $profile) { if (!$value) { return; } $productProfile = new CsvImportProfile('OrderedItem'); $productProfile->setField(0, 'OrderedItem.sku'); $productProfile->setField(1, 'OrderedItem.count'); $productProfile->setField(2, 'OrderedItem.price'); $productProfile->setField(3, 'OrderedItem.shipment'); foreach (explode(';', $value) as $product) { $item = explode(':', $product); $this->set_OrderedItem_sku($instance, $item[0], $item, $productProfile); } ActiveRecordModel::clearPool(); $instance = CustomerOrder::getInstanceByID($instance->getID()); $instance->loadAll(); $instance->isFinalized->set(false); $instance->finalize(array('customPrice' => true, 'allowRefinalize' => true)); $instance->save(); }
public function testTaxAmountChange() { $tax = Tax::getNewInstance('GST'); $tax->save(); // shipment delivery zone $zone = DeliveryZone::getNewInstance(); $zone->name->set('Canada'); $zone->isEnabled->set(true); $zone->save(); $country = DeliveryZoneCountry::getNewInstance($zone, 'US'); $country->save(); // taxes TaxRate::getNewInstance($zone, $tax, 10)->save(); $this->order->save(true); $shipment = Shipment::getNewInstance($this->order); $shipment->save(); $this->order->addShipment($shipment); $item = $this->order->addProduct($this->products[0], 1, false, $shipment); // $100 $shipment->recalculateAmounts(); $this->order->save(); $this->assertEqual($shipment->taxAmount->get(), 10); $this->order->updateCount($item, 2); $shipment->recalculateAmounts(); $this->assertEqual($shipment->taxAmount->get(), 20); $this->order->save(); $shipment->save(); // there should only be one ShipmentTax instance for this shipment $this->assertEqual($shipment->getRelatedRecordSet('ShipmentTax')->size(), 1); // reload order and add more items ActiveRecord::clearPool(); $order = CustomerOrder::getInstanceByID($this->order->getID(), true); $order->loadAll(); $shipment = $order->getShipments()->get(0); $order->addProduct($this->products[1], 1, false, $shipment); // $200 $shipment->recalculateAmounts(false); $shipment->save(); // @todo: fix failing assertion // 2 ShipmentTax records are created for the same tax type (1st is not deleted, before the 2nd is created) $this->assertEquals(1, $shipment->getRelatedRecordSet('ShipmentTax')->size(), 'expecting one ShipmentTax'); $order->save(); $this->order->finalize(); /* debug echo "\n Order is finalized!\n"; foreach($shipment->getRelatedRecordSet('ShipmentTax') as $item) { echo 'shipment tax id:', $item->getID(), ', type:', $item->type->get(), ', amount:', $item->getAmount(), ' ('. $item->shipmentID->get()->getTaxAmount() .')', ', shipment id:', $item->shipmentID->get()->getID(), ', taxRate id:', $item->taxRateID->get()->getID(), ', taxClass:', implode(';', $item->taxRateID->get()->taxID->get()->name->get()).'('. $item->taxRateID->get()->taxID->get()->getID() .')', ', zone:', $item->taxRateID->get()->deliveryZoneID->get()->name->get(),'(', $item->taxRateID->get()->deliveryZoneID->get()->getID() ,')', // blame canada!! "\n"; } */ $this->assertEquals(1, $order->getShipments()->size(), 'expecting one shipment'); $this->assertEqual(40, $shipment->getRelatedRecordSet('ShipmentTax')->get(0)->shipmentID->get()->getTaxAmount(), 40); // @todo: fix failing assertion $this->assertEquals(1, $shipment->getRelatedRecordSet('ShipmentTax')->size(), 'expecting one ShipmentTax'); $this->assertEqual($shipment->getRelatedRecordSet('ShipmentTax')->get(0)->amount->get(), 40); }
private function createOrder($array) { $cart = $array['SHOPPING-CART'][0]['ITEMS'][0]['ITEM']; $orderID = $cart[0]['MERCHANT-PRIVATE-ITEM-DATA'][0]['ORDER-ID'][0]['VALUE']; $gcIDs = $prices = array(); foreach ($cart as $item) { if (!isset($item['MERCHANT-PRIVATE-ITEM-DATA'])) { continue; } $itemID = $item['MERCHANT-PRIVATE-ITEM-DATA'][0]['ITEM-ID'][0]['VALUE']; $gcIDs[$itemID] = true; $prices[$itemID] = $item['UNIT-PRICE'][0]; } $order = CustomerOrder::getInstanceByID($orderID, true); $order->setPaymentMethod('GoogleCheckout'); $order->loadAll(); // remove items that are not in Google cart foreach ($order->getOrderedItems() as $item) { if (!isset($gcIDs[$item->getID()])) { $order->removeItem($item); } } return $order; }