Пример #1
0
 protected function getInstance($record, CsvImportProfile $profile)
 {
     CustomerOrder::allowEmpty(true);
     $fields = $profile->getSortedFields();
     if (isset($fields['CustomerOrder']['ID'])) {
         $id = $record[$fields['CustomerOrder']['ID']];
         $this->setLastImportedRecordName($id);
         $order = CustomerOrder::getInstanceByID($id, true);
     } else {
         if (isset($fields['CustomerOrder']['invoiceNumber'])) {
             $id = $record[$fields['CustomerOrder']['invoiceNumber']];
             if (!$id) {
                 return null;
             }
             $this->setLastImportedRecordName($id);
             $order = CustomerOrder::getInstanceByInvoiceNumber($id);
             if (!$order) {
                 $order = CustomerOrder::getNewInstance(User::getNewInstance('*****@*****.**'));
                 $order->invoiceNumber->set($id);
                 $order->save();
                 $order->finalize();
             }
         } else {
             return null;
         }
     }
     if ($order) {
         $order->loadAll();
         return $order;
     }
 }
Пример #2
0
 /**
  * Get CustomerOrder instance from session
  *
  * @return CustomerOrder
  */
 public static function getOrder()
 {
     if (self::$instance) {
         return self::$instance;
     }
     $session = new Session();
     $id = $session->get('CustomerOrder');
     if ($id) {
         try {
             $instance = CustomerOrder::getInstanceById($id, true);
             if (!$instance->getOrderedItems()) {
                 $instance->loadItems();
             }
             $instance->isSyncedToSession = true;
         } catch (ARNotFoundException $e) {
             unset($instance);
         }
     }
     if (!isset($instance)) {
         $userId = SessionUser::getUser()->getID();
         // get the last unfinalized order by this user
         if ($userId > 0) {
             $f = new ARSelectFilter(new EqualsCond(new ARFieldHandle('CustomerOrder', 'userID'), $userId));
             $f->mergeCondition(new NotEqualsCond(new ARFieldHandle('CustomerOrder', 'isFinalized'), true));
             $f->setOrder(new ARFieldHandle('CustomerOrder', 'ID'), 'DESC');
             $f->setLimit(1);
             $orders = ActiveRecordModel::getRecordSet('CustomerOrder', $f);
             if ($orders->size()) {
                 $instance = $orders->get(0);
             }
         }
     }
     if (!isset($instance)) {
         $instance = CustomerOrder::getNewInstance(User::getNewInstance(0));
         $instance->user->set(NULL);
     }
     if (!$instance->user->get() && SessionUser::getUser()->getID() > 0) {
         $instance->setUser(SessionUser::getUser());
         $instance->save();
     }
     if ($instance->isFinalized->get()) {
         $session->unsetValue('CustomerOrder');
         return self::getOrder();
     }
     // fixes issue when trying to add OrderedItem to unsaved(without ID) CustomerOrder.
     // ~ but i don't know if returning unsaved CustomerOrder is expected behaviour.
     if ($instance->isExistingRecord() == false) {
         $instance->save(true);
     }
     self::setOrder($instance);
     return $instance;
 }
Пример #3
0
 protected function initOrder()
 {
     // set up currency
     $this->setUpCurrency();
     $this->usd->decimalCount->set(2);
     $this->usd->clearRoundingRules();
     $this->usd->save();
     // initialize order
     ActiveRecordModel::executeUpdate('DELETE FROM User WHERE email="*****@*****.**"');
     $user = User::getNewInstance('*****@*****.**');
     $user->save();
     $this->user = $user;
     $address = UserAddress::getNewInstance();
     $address->countryID->set('US');
     $state = State::getInstanceById(1, State::LOAD_DATA);
     $address->state->set(State::getInstanceById(1));
     $address->postalCode->set(90210);
     $address->save();
     $billing = BillingAddress::getNewInstance($user, $address);
     $billing->save();
     $address = clone $address;
     $address->save();
     $shipping = ShippingAddress::getNewInstance($user, $address);
     $shipping->save();
     $this->order = CustomerOrder::getNewInstance($user);
     $this->order->shippingAddress->set($shipping->userAddress->get());
     $this->order->billingAddress->set($billing->userAddress->get());
     // set up products
     $product = Product::getNewInstance(Category::getInstanceById(Category::ROOT_ID), 'test1');
     $product->save();
     $product->setPrice('USD', 100);
     $product->stockCount->set(20);
     $product->isEnabled->set(1);
     $product->save();
     $this->products[] = $product;
     $product = Product::getNewInstance(Category::getInstanceById(Category::ROOT_ID), 'test2');
     $product->save();
     $product->setPrice('USD', 200);
     $product->stockCount->set(20);
     $product->isEnabled->set(1);
     $product->save();
     $this->products[] = $product;
     $product = Product::getNewInstance(Category::getInstanceById(Category::ROOT_ID), 'test3');
     $product->save();
     $product->setPrice('USD', 400);
     $product->isSeparateShipment->set(true);
     $product->stockCount->set(20);
     $product->isEnabled->set(1);
     $product->save();
     $this->products[] = $product;
 }
Пример #4
0
 private function createOrder()
 {
     $user = User::getNewInstance('*****@*****.**');
     $user->save();
     $currency = Currency::getInstanceByID('USD');
     $product = Product::getNewInstance(Category::getRootNode());
     $product->isEnabled->set(true);
     $product->stockCount->set(100);
     $product->setPrice($currency, 100);
     $product->setValueByLang('name', null, 'Test name');
     $product->setValueByLang('shortDescription', null, 'Really short description');
     $product->save();
     $order = CustomerOrder::getNewInstance($user);
     $order->addProduct($product, 1);
     $order->save();
     return $order;
 }
Пример #5
0
    public function getNextCustomerOrder()
    {
        if (!($data = $this->loadRecord('SELECT *, ' . $this->getTablePrefix() . 'orders.orders_id AS id, ' . $this->getTablePrefix() . 'orders_total.value FROM ' . $this->getTablePrefix() . 'orders
												LEFT JOIN ' . $this->getTablePrefix() . 'orders_total ON (' . $this->getTablePrefix() . 'orders.orders_id=' . $this->getTablePrefix() . 'orders_total.orders_id AND class="ot_shipping")
												LEFT JOIN ' . $this->getTablePrefix() . 'customers ON (' . $this->getTablePrefix() . 'orders.customers_id=' . $this->getTablePrefix() . 'customers.customers_id)
												WHERE ' . $this->getTablePrefix() . 'customers.customers_id IS NOT NULL'))) {
            return null;
        }
        $order = CustomerOrder::getNewInstance(User::getInstanceById($this->getRealId('User', $data['customers_id'])));
        $order->currency->set(Currency::getInstanceById($data['currency']));
        $order->dateCompleted->set($data['date_purchased']);
        // products
        $tax = 0;
        foreach ($this->getDataBySql('SELECT *, ' . $this->getTablePrefix() . 'orders_products.products_quantity AS quant FROM ' . $this->getTablePrefix() . 'orders_products LEFT JOIN ' . $this->getTablePrefix() . 'products ON (' . $this->getTablePrefix() . 'orders_products.products_id=' . $this->getTablePrefix() . 'products.products_id) WHERE ' . $this->getTablePrefix() . 'orders_id=' . $data['id'] . ' AND ' . $this->getTablePrefix() . 'products.products_id IS NOT NULL') as $prod) {
            $product = Product::getInstanceById($this->getRealId('Product', $prod['products_id']));
            if (!$prod['quant']) {
                continue;
            }
            $item = $order->addProduct($product, $prod['quant'], true);
            $item->price->set($prod['products_price']);
            $tax += $prod['products_tax'];
        }
        // addresses
        $order->shippingAddress->set($this->getUserAddress($data, 'delivery_'));
        $order->billingAddress->set($this->getUserAddress($data, 'billing_'));
        // assume that all orders are paid and shipped
        $order->status->set(CustomerOrder::STATUS_SHIPPED);
        $order->isPaid->set(true);
        $data['taxAmount'] = $tax;
        $order->rawData = $data;
        return $order;
    }
Пример #6
0
 public function generateTestInvoices()
 {
     return;
     ClassLoader::import('application.model.category.*');
     ClassLoader::import('application.model.product.*');
     $config = ActiveRecordModel::getApplication()->getConfig();
     $config->set('RECURRING_BILLING_PAYMENT_DUE_DATE_DAYS', 7);
     $config->save();
     // data
     $userID = 110;
     $product1ID = 339;
     $recurringProductPeriodID = 19;
     // ~
     // create first order
     $user = User::getInstanceByID($userID, true);
     $product1 = Product::getInstanceByID($product1ID, true);
     $order = CustomerOrder::getNewInstance($user);
     $order->save(true);
     $rpp = RecurringProductPeriod::getInstanceByID($recurringProductPeriodID);
     $item = $order->addProduct($product1, 1, true);
     $item->save();
     $recurringItem = RecurringItem::getNewInstance($rpp, $item);
     $recurringItem->setupPrice->set(100);
     $recurringItem->periodPrice->set(25);
     $recurringItem->save();
     $order->finalize();
     // generate invoices
     echo '<pre>Invoices for {CustomerOrder ID:' . $order->getID() . '}:', "\n";
     $now = time();
     for ($ts = $now; $ts < strtotime('+20 months', $now); $ts = $ts + 60 * 60 * 24) {
         $z = CustomerOrder::generateRecurringInvoices(date('Y-m-d', $ts));
         foreach ($z as $id) {
             echo '{CustomerOrder ID:' . $id . '}', "\n";
         }
     }
     die('-done-</pre>');
 }
Пример #7
0
 /**
  * @role create
  */
 public function create()
 {
     ActiveRecord::beginTransaction();
     $user = User::getInstanceByID((int) $this->request->get('customerID'), true, true);
     $user->loadAddresses();
     $order = CustomerOrder::getNewInstance($user);
     $status = CustomerOrder::STATUS_NEW;
     $order->status->set($status);
     $order->isFinalized->set(0);
     $order->capturedAmount->set(0);
     $order->totalAmount->set(0);
     $order->dateCompleted->set(new ARSerializableDateTime());
     $order->currency->set($this->application->getDefaultCurrency());
     foreach (array('billingAddress' => 'defaultBillingAddress', 'shippingAddress' => 'defaultShippingAddress') as $orderField => $userField) {
         if ($user->{$userField}->get()) {
             $user->{$userField}->get()->userAddress->get()->load();
             $address = clone $user->{$userField}->get()->userAddress->get();
             $address->save();
             $order->{$orderField}->set($address);
         }
     }
     $response = $this->save($order);
     ActiveRecord::commit();
     return $response;
 }
Пример #8
0
 /**
  *  "Close" the order for modifications and fix its state
  *
  *  1) fix current product prices and total (so the total doesn't change if product prices change)
  *  2) save created shipments
  *
  *  @return CustomerOrder New order instance containing wishlist items
  */
 public function finalize($options = array())
 {
     if ($this->isFinalized->get() && empty($options['allowRefinalize'])) {
         return;
     }
     self::beginTransaction();
     $this->event('before-finalize');
     $this->loadAll();
     $currency = $this->getCurrency();
     foreach ($this->getShipments() as $shipment) {
         if ($shipment->isExistingRecord()) {
             $shipment->deleteRecordSet('ShipmentTax', new ARDeleteFilter());
         }
         // clone shipping addresses
         if ($shipment->shippingAddress->get()) {
             $shippingAddress = clone $shipment->shippingAddress->get();
             $shippingAddress->save();
             $shipment->shippingAddress->set($shippingAddress);
         }
         $shipment->order->set($this);
         $shipment->save();
     }
     $reserveProducts = self::getApplication()->isInventoryTracking();
     foreach ($this->getShoppingCartItems() as $item) {
         if (empty($options['customPrice'])) {
             $item->price->set($item->getSubTotalBeforeTax() / $item->getCount());
         }
         $item->name->set($item->getProduct()->getParent()->name->get());
         $item->setValueByLang('name', 'sku', $item->getProduct()->sku->get());
         $item->save();
         // create sub-items for bundled products
         if ($item->getProduct()->isBundle()) {
             foreach ($item->getProduct()->getBundledProducts() as $bundled) {
                 $bundledItem = OrderedItem::getNewInstance($this, $bundled->relatedProduct->get(), $bundled->getCount());
                 $bundledItem->parent->set($item);
                 $bundledItem->save();
             }
         }
         // reserve products if inventory is enabled
         if ($reserveProducts) {
             $item->reserve();
             $item->save();
         }
     }
     if (!$this->shippingAddress->get() && $this->user->get() && $this->user->get()->defaultShippingAddress->get() && $this->isShippingRequired()) {
         $this->shippingAddress->set($this->user->get()->defaultShippingAddress->get()->userAddress->get());
     }
     if (!$this->billingAddress->get() && $this->user->get() && $this->user->get()->defaultBillingAddress->get()) {
         $this->billingAddress->set($this->user->get()->defaultBillingAddress->get()->userAddress->get());
     }
     // clone billing/shipping addresses
     if (!$this->isFinalized->get()) {
         foreach (array('billingAddress', 'shippingAddress') as $address) {
             if ($this->{$address}->get()) {
                 $this->{$address}->get()->load();
                 $this->{$address}->get()->getSpecification();
                 $cloned = clone $this->{$address}->get();
                 $cloned->save();
                 $cloned->loadEav();
                 $this->{$address}->set($cloned);
             }
         }
     }
     // move wish list items to a separate order
     if ($this->getWishListItems()) {
         $wishList = CustomerOrder::getNewInstance($this->user->get());
         foreach ($this->getWishListItems() as $item) {
             $wishList->addItem($item);
         }
         $wishList->save();
     } else {
         $wishList = null;
     }
     // set order total
     $this->totalAmount->set($this->getTotal(true));
     // save shipment taxes
     foreach ($this->shipments as $shipment) {
         $shipment->save();
     }
     // save discounts
     foreach ($this->orderDiscounts as $discount) {
         $discount->save();
     }
     // @todo: remove the 0.99 multiplicator for currency conversion "tolerance" (a cent going missing when converting amounts between currencies back and forth)
     if (round($this->totalAmount->get(), 2) * 0.99 <= round($this->getPaidAmount(), 2)) {
         $this->isPaid->set(true);
     }
     $this->dateCompleted->set(new ARSerializableDateTime());
     $this->isFinalized->set(true);
     // @todo: fix order total calculation
     $shipments = $this->shipments;
     unset($this->shipments);
     if (!$this->invoiceNumber->get()) {
         $generator = InvoiceNumberGenerator::getGenerator($this);
         $saved = false;
         while (!$saved) {
             try {
                 $this->invoiceNumber->set($generator->getNumber());
                 $this->save();
                 $saved = true;
             } catch (SQLException $e) {
             }
         }
     }
     $this->event('after-finalize');
     self::commit();
     // @todo: see above
     $this->shipments = $shipments;
     // force updating array representation
     $this->resetArrayData();
     return $wishList;
 }
Пример #9
0
 public function testTaxClassesWithDefaultZoneAndMultipleTaxes()
 {
     $order = CustomerOrder::getNewInstance($this->user);
     $zone = $order->getDeliveryZone();
     $this->assertTrue($zone->isDefault());
     // default tax level
     TaxRate::getNewInstance($zone, $this->tax, 10)->save();
     $newTax = Tax::getNewInstance('test');
     $newTax->save();
     // diferent tax rate for books
     $books = TaxClass::getNewInstance('Books');
     $books->save();
     $booksRate = TaxRate::getNewInstance($zone, $this->tax, 5);
     $booksRate->taxClass->set($books);
     $booksRate->save();
     $booksRate = TaxRate::getNewInstance($zone, $newTax, 20);
     $booksRate->taxClass->set($books);
     $booksRate->save();
     // price = 100
     $cd = $this->product;
     $book = Product::getNewInstance(Category::getRootNode());
     $book->setPrice('USD', 50);
     $book->isEnabled->set(true);
     $book->taxClass->set($books);
     $book->save();
     $order->addProduct($cd, 1, true);
     $order->addProduct($book, 1, true);
     $order->currency->set($this->currency);
     $order->save();
     $this->assertEqual($order->getTaxAmount(), 19.41);
     $this->assertEqual($order->getTotal(true), 150);
     $service = ShippingService::getNewInstance($order->getDeliveryZone(), 'def', ShippingService::SUBTOTAL_BASED);
     $service->save();
     $shippingRate = ShippingRate::getNewInstance($service, 0, 10000000);
     $shippingRate->flatCharge->set(100);
     $shippingRate->save();
     $shipment = $order->getShipments()->get(0);
     $rates = $order->getDeliveryZone()->getShippingRates($shipment);
     $shipment->setAvailableRates($rates);
     $shipment->setRateId($rates->get(0)->getServiceID());
     $shipment->save();
     $this->assertEqual($order->getTotal(true), 250);
     $this->assertEqual((string) $order->getTaxAmount(), (string) 28.5);
 }
Пример #10
0
 public function testGetNextRebillDate()
 {
     // config
     $config = ActiveRecordModel::getApplication()->getConfig();
     $config->set('RECURRING_BILLING_GENERATE_INVOICE', 0);
     // generate when period starts!
     $config->save();
     // two products
     $product1 = $this->products[0];
     $price1 = 10.01;
     $period1 = $this->createRecurringProductPeriod($product1, 1, RecurringProductPeriod::TYPE_PERIOD_MONTH, 6);
     // each month, 6 times
     // one empty order
     $order = CustomerOrder::getNewInstance($this->user);
     $order->save(true);
     // added products
     list($orderedItem1, $recurringItem1) = $this->addRecurringProduct($order, $product1, 1, $period1, 0, $price1);
     $order->save();
     $order->startDate->set('2011-01-01 00:00:00');
     $order->finalize();
     $order->save();
     $date = $order->getNextRebillDate();
     $this->assertEquals('2011-02-01', $date['date_short']);
     $ids = CustomerOrder::generateRecurringInvoices('2011-02-01');
     // 1
     $date = $order->getNextRebillDate();
     $this->assertEquals(1, count($ids));
     $this->assertEquals('2011-03-01', $date['date_short']);
     $ids = CustomerOrder::generateRecurringInvoices('2011-03-01');
     // 2
     $date = $order->getNextRebillDate();
     $this->assertEquals(1, count($ids));
     $this->assertEquals('2011-04-01', $date['date_short']);
     $ids = CustomerOrder::generateRecurringInvoices('2011-04-01');
     // 3
     $date = $order->getNextRebillDate();
     $this->assertEquals(1, count($ids));
     $this->assertEquals('2011-05-01', $date['date_short']);
     $ids = CustomerOrder::generateRecurringInvoices('2011-05-01');
     // 4
     $date = $order->getNextRebillDate();
     $this->assertEquals(1, count($ids));
     $this->assertEquals('2011-06-01', $date['date_short']);
     $ids = CustomerOrder::generateRecurringInvoices('2011-06-01');
     // 5
     $date = $order->getNextRebillDate();
     $this->assertEquals(1, count($ids));
     $this->assertEquals('2011-07-01', $date['date_short']);
     $ids = CustomerOrder::generateRecurringInvoices('2011-07-01');
     // 6
     $date = $order->getNextRebillDate();
     $this->assertEquals(1, count($ids));
     $this->assertEquals(null, $date);
     $ids = CustomerOrder::generateRecurringInvoices('2011-08-01');
     // 7
     $date = $order->getNextRebillDate();
     $this->assertEquals(0, count($ids));
     $this->assertEquals(null, $date);
 }
Пример #11
0
 /**
  *  "Close" the order for modifications and fix its state
  *
  *  1) fix current product prices and total (so the total doesn't change if product prices change)
  *  2) save created shipments
  *
  *  @return CustomerOrder New order instance containing wishlist items
  */
 public function finalize($options = array())
 {
     $rebillsLeft = 0;
     if ($this->isFinalized->get() && empty($options['allowRefinalize'])) {
         return;
     }
     self::beginTransaction();
     $this->event('before-finalize');
     $currency = $this->getCurrency();
     $this->loadAll();
     foreach ($this->getShipments() as $shipment) {
         if ($shipment->isExistingRecord()) {
             $shipment->deleteRecordSet('ShipmentTax', new ARDeleteFilter());
         }
         $shipment->order->set($this);
         $shipment->save();
         // clone shipping addresses
         if ($shipment->shippingAddress->get()) {
             $shippingAddress = clone $shipment->shippingAddress->get();
             $shippingAddress->save();
             $shipment->shippingAddress->set($shippingAddress);
         }
     }
     $reserveProducts = self::getApplication()->isInventoryTracking();
     $rebillsLeft = 0;
     $groupedRebillsLeft = array();
     $isFirstOrder = !$this->parentID->get();
     foreach ($this->getShoppingCartItems() as $item) {
         // workround for failing tests.
         //if (!empty($options['customPrice']))
         //{
         $item->price->set($item->getSubTotalBeforeTax() / $item->getCount());
         //}
         $item->name->set($item->getProduct()->getParent()->name->get());
         $item->setValueByLang('name', 'sku', $item->getProduct()->sku->get());
         $item->save();
         // create sub-items for bundled products
         if ($item->getProduct()->isBundle()) {
             foreach ($item->getProduct()->getBundledProducts() as $bundled) {
                 $bundledItem = OrderedItem::getNewInstance($this, $bundled->relatedProduct->get(), $bundled->getCount());
                 $bundledItem->parent->set($item);
                 $bundledItem->save();
             }
         }
         // reserve products if inventory is enabled
         if ($reserveProducts) {
             $item->reserve();
             $item->save();
         }
         if ($isFirstOrder) {
             $ri = RecurringItem::getInstanceByOrderedItem($item);
             if ($ri && $ri->isExistingRecord()) {
                 $rebillCount = $ri->rebillCount->get();
                 // also here recurring item grouping
                 $key = sprintf('%s_%s_%s', $ri->periodType->get(), $ri->periodLength->get(), $rebillCount === null ? 'NULL' : $rebillCount);
                 if ($rebillCount !== null) {
                     $groupedRebillsLeft[$key] = $rebillCount;
                 } else {
                     $groupedRebillsLeft[$key] = -1;
                     // -1 means infinite rebill count
                 }
                 $this->isRecurring->set(true);
                 // orders with at least one recurring billing plan must have isRecurring flag, if already not set.
             }
         } else {
             $rparentItem = $item->recurringParentID->get();
             if ($rparentItem) {
                 $ri = RecurringItem::getInstanceByOrderedItem($rparentItem, true);
                 $ri->reload();
                 // if was bulk update, then cached data are outdated.
                 if ($ri && $ri->isExistingRecord()) {
                     // are RecurringItems grouped?
                     // probably yes..
                     $rebillsLeft = $ri->rebillCount->get() - $ri->processedRebillCount->get();
                 }
             }
         }
     }
     if ($isFirstOrder) {
         foreach ($groupedRebillsLeft as $value) {
             if ($value == -1) {
                 $rebillsLeft = -1;
                 break;
             } else {
                 $rebillsLeft += $value;
             }
         }
     }
     if (!$this->shippingAddress->get() && $this->user->get() && $this->user->get()->defaultShippingAddress->get() && $this->isShippingRequired()) {
         $this->shippingAddress->set($this->user->get()->defaultShippingAddress->get()->userAddress->get());
     }
     if (!$this->billingAddress->get() && $this->user->get() && $this->user->get()->defaultBillingAddress->get()) {
         $this->billingAddress->set($this->user->get()->defaultBillingAddress->get()->userAddress->get());
     }
     // clone billing/shipping addresses
     if (!$this->isFinalized->get()) {
         foreach (array('billingAddress', 'shippingAddress') as $address) {
             if ($this->{$address}->get()) {
                 $this->{$address}->get()->load();
                 $this->{$address}->get()->getSpecification();
                 $cloned = clone $this->{$address}->get();
                 $cloned->save();
                 $cloned->loadEav();
                 $this->{$address}->set($cloned);
             }
         }
     }
     // move wish list items to a separate order
     if ($this->getWishListItems()) {
         $wishList = CustomerOrder::getNewInstance($this->user->get());
         foreach ($this->getWishListItems() as $item) {
             $wishList->addItem($item);
         }
         $wishList->save();
     } else {
         $wishList = null;
     }
     // set order total
     $this->totalAmount->set($this->getTotal(true));
     // save shipment taxes
     foreach ($this->shipments as $shipment) {
         $shipment->save();
     }
     // save discounts
     foreach ($this->orderDiscounts as $discount) {
         $discount->save();
     }
     // @todo: remove the 0.99 multiplicator for currency conversion "tolerance" (a cent going missing when converting amounts between currencies back and forth)
     if (round($this->totalAmount->get(), 2) * 0.99 <= round($this->getPaidAmount(), 2)) {
         $this->isPaid->set(true);
     }
     $this->dateCompleted->set(new ARSerializableDateTime());
     $this->isFinalized->set(true);
     // @todo: fix order total calculation
     $shipments = $this->shipments;
     unset($this->shipments);
     if (!$this->invoiceNumber->get()) {
         $generator = InvoiceNumberGenerator::getGenerator($this);
         $saved = false;
         while (!$saved) {
             try {
                 $this->invoiceNumber->set($generator->getNumber());
                 $this->save();
                 $saved = true;
             } catch (SQLException $e) {
             }
         }
     }
     if ($this->isRecurring->get()) {
         $changed = false;
         if (!strlen($this->startDate->get())) {
             $this->startDate->set(date('Y-m-d H:i:s', time()));
             $changed = true;
         }
         if ($rebillsLeft != $this->rebillsLeft->get()) {
             $this->rebillsLeft->set($rebillsLeft);
             $changed = true;
         }
         if ($changed) {
             $this->save();
         }
     }
     $this->event('after-finalize');
     self::commit();
     // @todo: see above
     $this->shipments = $shipments;
     // force updating array representation
     $this->resetArrayData();
     return $wishList;
 }
Пример #12
0
 public function create()
 {
     $response = new LiveCartSimpleXMLElement('<response datetime="' . date('c') . '"></response>');
     $request = $this->application->getRequest();
     $orderID = $request->get('orderID');
     $currencyID = $request->get('currencyID');
     $amount = $request->get('amount');
     $method = $request->get('method');
     $gatewayTransactionID = $request->get('gatewayTransactionID');
     if (intval($orderID) <= 0) {
         throw new Exception('Order ID is required');
     }
     if (!isset($currencyID) || !isset($method) || !isset($gatewayTransactionID)) {
         throw new Exception('Complete required fields : currencyID, method, gatewayTransactionID');
     }
     $transaction_result = new TransactionResult();
     $transaction_result->currency->set($currencyID);
     // = $currencyID;
     $transaction_result->amount->set($amount);
     //= $amount;
     $transaction_result->gatewayTransactionID->set($gatewayTransactionID);
     // = $gatewayTransactionID;
     $transaction_result->setTransactionType(TransactionResult::TYPE_SALE);
     $order = CustomerOrder::getInstanceById($orderID);
     $order->loadAll();
     $order_array = $order->toArray();
     $user = User::getInstanceByID($order_array['userID']);
     $user->load();
     $order->user->set($user);
     if ($current_transaction = Transaction::getInstance($order, $gatewayTransactionID)) {
         $current_transaction->method->set($method);
         $current_transaction->save();
     } else {
         $new_transaction = Transaction::getNewInstance($order, $transaction_result);
         $new_transaction->method->set($method);
         $new_transaction->save();
         if (!$this->finalizeOrder($order, $user)) {
             // Create new order for current user
             $new_order = CustomerOrder::getNewInstance($user);
             $new_order->beginTransaction();
             $new_order->save();
             $new_order->commit();
         }
     }
     $parser = $this->getParser();
     $apiFieldNames = $parser->getApiFieldNames();
     $f = new ARSelectFilter();
     $f->mergeCondition(new EqualsCond(new ARFieldHandle('Transaction', 'orderID'), $orderID));
     $transactions = ActiveRecordModel::getRecordSetArray('Transaction', $f);
     $response = new LiveCartSimpleXMLElement('<response datetime="' . date('c') . '"></response>');
     if (false && count($transactions) == 0) {
         throw new Exception('Transactions not found');
     }
     while ($transaction = array_shift($transactions)) {
         $transaction_response = $response->addChild('transaction');
         foreach ($transaction as $k => $v) {
             if (in_array($k, $apiFieldNames)) {
                 $transaction_response->addChild($k, htmlentities($v));
             }
         }
     }
     return new SimpleXMLResponse($response);
 }
Пример #13
0
 public function getNextCustomerOrder()
 {
     if (!($data = $this->loadRecord('SELECT * FROM ' . $this->getTablePrefix() . 'orders WHERE customerID > 0'))) {
         return null;
     }
     $user = ActiveRecordModel::getInstanceByIDIfExists('User', $this->getRealId('User', $data['customerID'], false));
     if (!$user || !$user->isExistingRecord()) {
         return $this->getNextCustomerOrder();
     }
     $currCode = $data['currency_code'];
     if (!($currency = ActiveRecordModel::getInstanceByIDIfExists('Currency', $currCode, false))) {
         $currency = Currency::getNewInstance($currCode);
         $currency->save();
     }
     $order = CustomerOrder::getNewInstance($user);
     $order->currency->set($currency);
     $order->dateCompleted->set($data['order_time']);
     // products
     foreach ($this->getDataBySql('SELECT * FROM ' . $this->getTablePrefix() . 'ordered_carts WHERE orderID=' . $data['orderID']) as $item) {
         $product = null;
         // try to identify product by SKU
         preg_match('/\\[(.*)\\]/', $item['name'], $sku);
         if (isset($sku[1])) {
             $product = Product::getInstanceBySKU($sku[1]);
         }
         // if that doesn't work, then try to match the exact name
         if (!$product) {
             $productData = array_shift($this->getDataBySQL('SELECT productID FROM ' . $this->getTablePrefix() . 'products WHERE name="' . addslashes($item['name']) . '"'));
             if ($productData && is_array($productData)) {
                 $product = Product::getInstanceByID($this->getRealId('Product', $productData['productID']), Product::LOAD_DATA);
             }
         }
         if ($product) {
             $order->addProduct($product, $item['Quantity'], true);
             $orderedItem = array_shift($order->getItemsByProduct($product));
             $orderedItem->price->set($item['Price']);
         }
     }
     // addresses
     $order->shippingAddress->set($this->getUserAddress($data, 'shipping_'));
     $order->billingAddress->set($this->getUserAddress($data, 'billing_'));
     $order->status->set($this->getOrderStatus($data['statusID']));
     if ($order->status->get() == CustomerOrder::STATUS_SHIPPED) {
         $order->isPaid->set(true);
     }
     $order->rawData = $data;
     return $order;
 }
Пример #14
0
 public function testMustHavePurchasedToRate()
 {
     $user = User::getNewInstance('*****@*****.**');
     $user->save();
     self::getApplication()->getConfig()->set('ENABLE_REVIEWS', true);
     self::getApplication()->getConfig()->set('ENABLE_ANONYMOUS_RATINGS', false);
     self::getApplication()->getConfig()->set('REQUIRE_PURCHASE_TO_RATE', true);
     $this->request->set('rating_', 4);
     $this->request->set('ajax', 'true');
     $this->assertRatingError();
     $this->controller->setUser($user);
     // login not enough - should still fail
     $this->assertRatingError();
     ActiveRecordModel::executeUpdate('DELETE FROM Currency');
     $usd = Currency::getNewInstance('USD');
     $usd->save();
     $order = CustomerOrder::getNewInstance($user);
     $order->addProduct($this->product);
     $order->save();
     // order not completed - should still fail
     $this->assertRatingError();
     // order finalized - now works
     $order->finalize();
     $id = $this->product->getID();
     $this->setUp();
     $this->controller->setUser($user);
     $this->request->set('id', $id);
     $this->assertRatingError(false);
 }
Пример #15
0
 public function testOrderTotalsWithRoundedPrices()
 {
     $currency = Currency::getNewInstance('RON');
     $currency->setRoundingRule(0, Currency::TRIM, 0.09);
     $currency->save();
     $product = Product::getNewInstance(Category::getRootNode());
     $product->isEnabled->set(true);
     $product->setPrice($currency, 1.26);
     $product->save();
     $order = CustomerOrder::getNewInstance(SessionUser::getAnonymousUser());
     $order->addProduct($product);
     $order->save(true);
     $item = array_shift($order->getItemsByProduct($product));
     $this->assertEquals($product->getPrice($currency), 1.29);
     $this->assertEquals($item->getSubTotal(), 1.29);
     $item->count->set(2);
     $this->assertEquals($item->getSubTotal(), 2.58);
     $this->assertEquals($order->getTotal(true), 2.58);
     // add another currency to mix - no rounding rules
     $bgn = Currency::getNewInstance('BGN');
     $bgn->rate->set(2);
     $bgn->save();
     $item->count->set(2);
     $order->changeCurrency($bgn);
     $this->assertEquals($product->getPrice($bgn), 0.63);
     $this->assertEquals($item->getPrice(), 0.63);
     $this->assertSame($item->getCurrency(), $bgn);
     $this->assertEquals($item->getSubTotal(), 1.26);
     $this->assertEquals($order->getTotal(true), 1.26);
     // add rounding rules
     $bgn->clearRoundingRules();
     $bgn->setRoundingRule(0, Currency::TRIM, 0.07000000000000001);
     $order->changeCurrency($bgn);
     $this->assertEquals($product->getPrice($bgn), 0.67);
     $this->assertEquals($item->getSubTotal(), 1.34);
     $this->assertEquals($order->getTotal(true), 1.34);
 }
Пример #16
0
 public function create()
 {
     $request = $this->application->getRequest();
     $user = User::getInstanceByID($request->get('userID'));
     $user->load(true);
     $user->loadAddresses();
     $new_order = CustomerOrder::getNewInstance($user);
     $new_order->setUser($user);
     $new_order->loadAll();
     $new_order->getShipments();
     $new_order->getTotal(true);
     $new_order->save(true);
     $address = $user->defaultShippingAddress->get();
     if (!$address) {
         $address = $user->defaultBillingAddress->get();
     }
     if (!$new_order->shippingAddress->get() && $address) {
         $userAddress = $address->userAddress->get();
         $new_order->shippingAddress->set($userAddress);
         $new_order->save(true);
     }
     $address = $user->defaultBillingAddress->get();
     if (!$new_order->billingAddress->get() && $address) {
         $userAddress = $address->userAddress->get();
         $new_order->billingAddress->set($userAddress);
         $new_order->save(true);
     }
     $new_order->loadAll();
     return $this->apiActionGetOrdersBySelectFilter(select(eq(f('CustomerOrder.ID'), $new_order->getFieldValue('ID'))));
 }
Пример #17
0
 public function getNextCustomerOrder()
 {
     if (!($data = $this->loadRecord('SELECT ' . $this->getTablePrefix() . 'orders.*, ' . $this->getTablePrefix() . 'customers.email AS userEmail FROM ' . $this->getTablePrefix() . 'orders LEFT JOIN ' . $this->getTablePrefix() . 'customers ON ' . $this->getTablePrefix() . 'orders.login='******'customers.login'))) {
         return null;
     }
     if (!($user = User::getInstanceByEmail($data['userEmail']))) {
         return $this->getNextCustomerOrder();
     }
     $order = CustomerOrder::getNewInstance($user);
     $order->currency->set(Currency::getInstanceById($this->getDefaultCurrency()));
     $order->dateCompleted->set($data['date']);
     // products
     foreach ($this->getDataBySql('SELECT * FROM ' . $this->getTablePrefix() . 'order_details WHERE orderid=' . $data['orderid']) as $prod) {
         try {
             $product = Product::getInstanceById($this->getRealId('Product', $prod['productid']), true);
             $order->addProduct($product, $prod['amount'], true);
             $item = array_shift($order->getItemsByProduct($product));
             $item->price->set($prod['price']);
         } catch (ARNotFoundException $e) {
             // the product no longer exists
         }
     }
     // addresses
     $order->shippingAddress->set($this->getUserAddress($data, 's_'));
     $order->billingAddress->set($this->getUserAddress($data, 'b_'));
     // assume that all orders are paid and shipped
     $order->status->set(CustomerOrder::STATUS_SHIPPED);
     $order->isPaid->set(true);
     $order->rawData = $data;
     return $order;
 }
Пример #18
0
 private function validatePastOrderQtPriceOrderTotal($cnt, $total)
 {
     $order = CustomerOrder::getNewInstance($this->user);
     $pastOrders = $order->getBusinessRuleContext()->getPastOrders();
     $this->assertEquals(1, count($pastOrders['orders']));
     $this->assertEquals(1, count($order->getBusinessRuleContext()->getPastOrdersBetween(0, time())));
     $order->addProduct($this->product1, $cnt, true);
     $this->assertEquals($total, $order->getTotal(true));
 }