コード例 #1
0
 /**
  * Send customer an order receipt email.
  * Precondition: The order payment has been successful
  */
 public function sendReceipt()
 {
     $subject = sprintf(_t("OrderNotifier.RECEIPTSUBJECT", "Order #%d Receipt"), $this->order->Reference);
     $this->sendEmail('Order_ReceiptEmail', $subject, self::config()->bcc_receipt_to_admin);
     $this->order->ReceiptSent = SS_Datetime::now()->Rfc2822();
     $this->order->write();
 }
コード例 #2
0
 public function testSinglePageConfig()
 {
     ShopTest::setConfiguration();
     //start a new order
     $order = new Order();
     $order->write();
     $config = new SinglePageCheckoutComponentConfig($order);
     $components = $config->getComponents();
     //assertions!
     $fields = $config->getFormFields();
     //assertions!
     $required = $config->getRequiredFields();
     //assertions!
     //$validateData = $config->validateData($data);
     //assertions!
     $data = $config->getData();
     //assertions!
     $config->setData($data);
     //assertions!
     //form field generation
     //validate data
     //set data
     //get data
     $this->markTestIncomplete('Lots missing here');
 }
コード例 #3
0
 public function setData(Order $order, array $data)
 {
     if (isset($data['Notes'])) {
         $order->Notes = $data['Notes'];
     }
     //TODO: save this to an order log
     $order->write();
 }
コード例 #4
0
 public function createOrder()
 {
     $order = new Order();
     $order->write();
     $item1a = $this->mp3player->createItem(2);
     $item1a->write();
     $order->Items()->add($item1a);
     $item1b = $this->socks->createItem();
     $item1b->write();
     $order->Items()->add($item1b);
     return $order;
 }
コード例 #5
0
 function old_testValidateWrongCurrency()
 {
     $o = new Order();
     $o->Currency = 'USD';
     $o->write();
     $p = new Payment();
     $p->Money->setCurrency('EUR');
     //fails here
     $p->Money->setAmount(1.23);
     $p->OrderID = $o->ID;
     $validationResult = $p->validate();
     $this->assertContains('Currency of payment', $validationResult->message());
 }
コード例 #6
0
 /**
  * Add the member to the order, in case the member is not an admin.
  *
  * @param DataObject - $order Order
  * @return Boolean
  **/
 public function doStep(Order $order)
 {
     if (!$order->MemberID) {
         $member = Member::currentUser();
         if ($member) {
             if (!$member->IsShopAdmin()) {
                 $order->MemberID = $member->ID();
                 $order->write();
             }
         }
     }
     return true;
 }
コード例 #7
0
 public function testGetTotalStockInCarts()
 {
     $this->setStockFor($this->phone, 10);
     $order = new Order(array('Status' => 'Cart'));
     $order->write();
     $orderItem = new Product_OrderItem(array('ProductID' => $this->phone->ID, 'OrderID' => $order->ID, 'Quantity' => '5'));
     $orderItem->write();
     $this->assertEquals(5, $this->phone->getTotalStockInCarts());
     // test variations
     $this->setStockFor($this->ballRedSmall, 5);
     $orderItem = $orderItem->newClassInstance('ProductVariation_OrderItem');
     $orderItem->ProductVariationID = $this->ballRedSmall->ID;
     $orderItem->write();
     $this->assertEquals(5, $this->ballRedSmall->getTotalStockInCarts());
 }
コード例 #8
0
 /**
  * Get the current order from the session, if order does not exist create a new one.
  * 
  * @return Order The current order (cart)
  */
 static function get_current_order()
 {
     $orderID = Session::get('Cart.OrderID');
     $order = null;
     if ($orderID) {
         $order = DataObject::get_by_id('Order', $orderID);
     }
     if (!$orderID || !$order || !$order->exists()) {
         $order = new Order();
         $order->write();
         Session::set('Cart', array('OrderID' => $order->ID));
         Session::save();
     }
     return $order;
 }
コード例 #9
0
 public function testRun()
 {
     SS_Datetime::set_mock_now('2014-01-31 13:00:00');
     // less than two hours old
     $orderRunningRecent = new Order(array('Status' => 'Cart'));
     $orderRunningRecentID = $orderRunningRecent->write();
     DB::query('UPDATE "Order" SET "LastEdited" = \'2014-01-31 12:30:00\' WHERE "ID" = ' . $orderRunningRecentID);
     // three hours old
     $orderRunningOld = new Order(array('Status' => 'Cart'));
     $orderRunningOldID = $orderRunningOld->write();
     DB::query('UPDATE "Order" SET "LastEdited" = \'2014-01-31 10:00:00\' WHERE "ID" = ' . $orderRunningOldID);
     // three hours old
     $orderPaidOld = new Order(array('Status' => 'Paid'));
     $orderPaidOldID = $orderPaidOld->write();
     DB::query('UPDATE "Order" SET "LastEdited" = \'2014-01-31 10:00:00\' WHERE "ID" = ' . $orderPaidOldID);
     $task = new CartCleanupTaskTest_CartCleanupTaskFake();
     $response = $task->run(new SS_HTTPRequest('GET', '/'));
     $this->assertInstanceOf('Order', Order::get()->byID($orderRunningRecentID));
     $this->assertNull(Order::get()->byID($orderRunningOldID));
     $this->assertInstanceOf('Order', Order::get()->byID($orderPaidOldID));
     $this->assertEquals('1 old carts removed.', $task->log[count($task->log) - 1]);
     SS_Datetime::clear_mock_now();
 }
 /**
  * Action that gets called before we interface with our payment
  * method.
  *
  * This action is responsible for setting up an order and
  * saving it into the database (as well as a session) and also then
  * generating an order summary before the user performs any final
  * actions needed.
  *
  * This action is then mapped directly to the index action of the
  * Handler for the payment method that was selected by the user
  * in the "Postage and Payment" form.
  *
  */
 public function index()
 {
     $cart = ShoppingCart::get();
     // If shopping cart doesn't exist, redirect to base
     if (!$cart->getItems()->exists() || $this->getPaymentHandler() === null) {
         return $this->redirect(Director::BaseURL());
     }
     // Get billing and delivery details and merge into an array
     $billing_data = Session::get("Commerce.BillingDetailsForm.data");
     $delivery_data = Session::get("Commerce.DeliveryDetailsForm.data");
     $postage = PostageArea::get()->byID(Session::get('Commerce.PostageID'));
     if (!$postage || !$billing_data || !$delivery_data) {
         return $this->redirect(Checkout_Controller::create()->Link());
     }
     // Work out if an order prefix string has been set in siteconfig
     $config = SiteConfig::current_site_config();
     $order_prefix = $config->OrderPrefix ? $config->OrderPrefix . '-' : '';
     // Merge billand and delivery data into an array
     $data = array_merge((array) $billing_data, (array) $delivery_data);
     // Set discount info
     $data['DiscountAmount'] = $cart->DiscountAmount();
     // Get postage data
     $data['PostageType'] = $postage->Title;
     $data['PostageCost'] = $postage->Cost;
     $data['PostageTax'] = $config->TaxRate > 0 && $postage->Cost > 0 ? (double) $postage->Cost / 100 * $config->TaxRate : 0;
     // Set status
     $data['Status'] = 'incomplete';
     // Setup an order based on the data from the shopping cart and load data
     $order = new Order();
     $order->update($data);
     // If user logged in, track it against an order
     if (Member::currentUserID()) {
         $order->CustomerID = Member::currentUserID();
     }
     // Write so we can setup our foreign keys
     $order->write();
     // Loop through each session cart item and add that item to the order
     foreach ($cart->getItems() as $cart_item) {
         $order_item = new OrderItem();
         $order_item->Title = $cart_item->Title;
         $order_item->SKU = $cart_item->SKU;
         $order_item->Price = $cart_item->Price;
         $order_item->Tax = $cart_item->Tax;
         $order_item->Customisation = serialize($cart_item->Customised);
         $order_item->Quantity = $cart_item->Quantity;
         $order_item->write();
         $order->Items()->add($order_item);
     }
     $order->write();
     // Add order to session so our payment handler can process it
     Session::set("Commerce.Order", $order);
     $this->payment_handler->setOrder($order);
     // Get gateway data
     $return = $this->payment_handler->index();
     return $this->customise($return)->renderWith(array("Payment", "Commerce", "Page"));
 }
コード例 #11
0
 /**
  * Finds or creates a current order.
  * @todo split this into two functions: initcart, and currentcart...so that templates can return null for Cart
  */
 public static function current_order()
 {
     if (self::$order) {
         return self::$order;
     }
     //we only want to hit the database once
     //find order by id saved to session (allows logging out and retaining cart contents)
     $cartid = Session::get(self::$cartid_session_name);
     //TODO: make clear cart on logout optional
     if ($cartid && ($o = DataObject::get_one('Order', "\"Status\" = 'Cart' AND \"ID\" = {$cartid}"))) {
         $order = $o;
     } else {
         $order = new Order();
         $order->SessionID = session_id();
         if (EcommerceRole::get_associate_to_current_order()) {
             $order->MemberID = Member::currentUserID();
         }
         // Set the Member relation to this order
         $order->write();
         Session::set(self::$cartid_session_name, $order->ID);
         //init modifiers the first time the order is created
         // (currently assumes modifiers won't change)
     }
     self::$order = $order;
     //temp caching
     $order->initModifiers();
     //init /re-init modifiers
     $order->write();
     // Write the order
     return $order;
 }
コード例 #12
0
ファイル: DataAdmin.php プロジェクト: hemant-chakka/awss
 public function changeSubscription($data, $form)
 {
     //Get the record ID
     $id = Controller::curr()->request->param('ID');
     // Get the subscription
     $subscription = Subscription::get()->byID($id);
     //Get the new product ID
     $newProductID = $data['ProductID'];
     if ($subscription->ProductID == $newProductID) {
         $form->sessionMessage("Please select a new subscription.", 'bad');
         return $this->edit(Controller::curr()->getRequest());
     }
     // Get the Page controller
     $Pg_Ctrl = new Page_Controller();
     // Get InfusionSoft Api
     $app = $Pg_Ctrl->getInfusionSoftApi();
     // Get AttentionWizard member
     $member = Member::get()->byID($data['MemberID']);
     // Get IndusionSoft contact ID
     $isConID = $member->ISContactID;
     //Get current date
     $curdate = $app->infuDate(date('j-n-Y'));
     //Get old order
     $oldOrder = $subscription->Order();
     //Get new product
     $product = Product::get()->byID($newProductID);
     $credits = $product->Credits;
     $isProductID = $product->ISInitialProductID;
     // Get the current InfusionSoft credit card ID
     $creditCard = $Pg_Ctrl->getCurrentCreditCard($member->ID);
     if (!$creditCard) {
         $form->sessionMessage("The user does not have a Credit Card on account, please add a credit card.", 'bad');
         return $this->edit(Controller::curr()->getRequest());
     }
     $ccID = $creditCard->ISCCID;
     $subscriptionID = $Pg_Ctrl->createISSubscription($isConID, $product->ISProductID, $product->RecurringPrice, $ccID, 30);
     if ($subscriptionID && is_int($subscriptionID)) {
         // Create an order
         $order = new Order();
         $order->OrderStatus = 'P';
         $order->Amount = $product->RecurringPrice;
         $order->MemberID = $member->ID;
         $order->ProductID = $newProductID;
         $order->CreditCardID = $creditCard->ID;
         $orderID = $order->write();
         //Create an infusionsoft order
         $config = SiteConfig::current_site_config();
         $invoiceId = $app->blankOrder($isConID, $product->Name, $curdate, 0, 0);
         $orderItem = $app->addOrderItem($invoiceId, $isProductID, 9, floatval($product->RecurringPrice), 1, $product->Name, $product->Name);
         $result = $app->chargeInvoice($invoiceId, $product->Name, $ccID, $config->MerchantAccount, false);
         if ($result['Successful']) {
             $nextBillDate = $Pg_Ctrl->getSubscriptionNextBillDate($subscriptionID);
             $expireDate = date('Y-m-d H:i:s', strtotime($nextBillDate));
             $startDate = date('Y-m-d H:i:s', strtotime($expireDate . "-30 days"));
             //Set the current subscription to Inactive
             $Pg_Ctrl->setSubscriptionStatus($subscription->SubscriptionID, 'Inactive');
             //Remove trial tag if exists
             $app->grpRemove($isConID, 2216);
             //get old Tag ID
             if ($Pg_Ctrl->isTrialMember($member->ID)) {
                 $oldISTagID = 2216;
             } else {
                 $oldISTagID = $Pg_Ctrl->getISTagIdByProduct($oldOrder->ProductID);
             }
             //Remove old tag ID
             $app->grpRemove($isConID, $oldISTagID);
             $newISTagID = $Pg_Ctrl->getISTagIdByProduct($newProductID);
             //Add new tag ID
             $app->grpAssign($isConID, $newISTagID);
             //Add a note
             $conActionDat = array('ContactId' => $isConID, 'ActionType' => 'UPDATE', 'ActionDescription' => "Payment made for AW service", 'CreationDate' => $curdate, 'ActionDate' => $curdate, 'CompletionDate' => $curdate, 'CreationNotes' => "{$product->Name} Subscription", 'UserID' => 1);
             $app->dsAdd("ContactAction", $conActionDat);
             $returnFields = array('_AWofmonths');
             $conData = $app->loadCon($isConID, $returnFields);
             $conDat = array('_AWofmonths' => (isset($conData['_AWofmonths']) ? $conData['_AWofmonths'] : 0) + 1, '_AttentionWizard' => 'Paid and Current');
             $app->updateCon($isConID, $conDat);
             //Create a new Subscription
             $newSubscription = new Subscription();
             $newSubscription->StartDate = $startDate;
             $newSubscription->ExpireDate = $expireDate;
             $newSubscription->SubscriptionID = $subscriptionID;
             $newSubscription->Status = 1;
             $newSubscription->IsTrial = 0;
             $newSubscription->SubscriptionCount = 1;
             $newSubscription->MemberID = $member->ID;
             $newSubscription->ProductID = $newProductID;
             $newSubscription->OrderID = $orderID;
             $newSubscription->write();
             // Create a MemberCredits record
             $memberCredits = new MemberCredits();
             $memberCredits->Credits = $credits;
             $memberCredits->Expire = 1;
             $memberCredits->ExpireDate = $expireDate;
             $memberCredits->MemberID = $member->ID;
             $memberCredits->ProductID = $newProductID;
             $memberCredits->SubscriptionID = $newSubscription->ID;
             $memberCredits->write();
             // Update order
             $order->OrderStatus = 'c';
             $order->write();
             //Update old subscription status
             $subscription->Status = 0;
             $subscription->IsTrial = 0;
             $subscription->write();
         } else {
             //Set the subscription to Inactive
             $Pg_Ctrl->setSubscriptionStatus($subscriptionID, 'Inactive');
             $form->sessionMessage("Sorry,the payment failed due to some reason.please update your credit card", 'bad');
             return $this->edit(Controller::curr()->getRequest());
         }
     } else {
         $form->sessionMessage("Sorry,the subscription failed due to some reason.please try again", 'bad');
         return $this->edit(Controller::curr()->getRequest());
     }
     $form->sessionMessage("The Subscription is changed successfully.", 'good');
     return Controller::curr()->redirect("admin/manage-data/Subscription/EditForm/field/Subscription/item/{$newSubscription->ID}/edit");
 }
コード例 #13
0
ファイル: OrderProcessor.php プロジェクト: 8secs/cocina
 /**
  * Send the receipt of the order by mail.
  * Precondition: The order payment has been successful
  */
 public function sendReceipt()
 {
     $this->sendEmail('Order_ReceiptEmail', Config::inst()->get('OrderProcessor', 'bcc_receipt_to_admin'));
     $this->order->ReceiptSent = SS_Datetime::now()->Rfc2822();
     $this->order->write();
 }
 private function createorder()
 {
     $order = new Order();
     $order->UseShippingAddress = true;
     $order->CustomerOrderNote = "THIS IS AN AUTO-GENERATED ORDER";
     $order->write();
     $member = new Member();
     $member->FirstName = 'Tom';
     $member->Surname = 'Cruize';
     $member->Email = '*****@*****.**';
     $member->Password = '******';
     $member->write();
     $order->MemberID = $member->ID;
     $billingAddress = new BillingAddress();
     $billingAddress->Prefix = "Dr";
     $billingAddress->FirstName = "Tom";
     $billingAddress->Surname = "Cruize";
     $billingAddress->Address = "Lamp Drive";
     $billingAddress->Address2 = "Linux Mountain";
     $billingAddress->City = "Apache Town";
     $billingAddress->PostalCode = "555";
     $billingAddress->Country = "NZ";
     $billingAddress->Phone = "555 5555555";
     $billingAddress->Email = "*****@*****.**";
     $billingAddress->write();
     $order->BillingAddressID = $billingAddress->ID;
     $shippingAddress = new ShippingAddress();
     $shippingAddress->ShippingPrefix = "Dr";
     $shippingAddress->ShippingFirstName = "Tom";
     $shippingAddress->ShippingSurname = "Cruize";
     $shippingAddress->ShippingAddress = "Lamp Drive";
     $shippingAddress->ShippingAddress2 = "Linux Mountain";
     $shippingAddress->ShippingCity = "Apache Town";
     $shippingAddress->ShippingPostalCode = "555";
     $shippingAddress->ShippingCountry = "NZ";
     $shippingAddress->ShippingPhone = "555 5555555";
     $shippingAddress->write();
     $order->ShippingAddressID = $shippingAddress->ID;
     //get a random product
     $extension = "";
     if (Versioned::current_stage() == "Live") {
         $extension = "_Live";
     }
     $count = 0;
     $noProductYet = true;
     $triedArray = array(0 => 0);
     while ($noProductYet && $count < 50) {
         $product = Product::get()->where("\"ClassName\" = 'Product' AND \"Product{$extension}\".\"ID\" NOT IN (" . implode(",", $triedArray) . ") AND Price > 0")->First();
         if ($product) {
             if ($product->canPurchase()) {
                 $noProductYet = false;
             } else {
                 $triedArray[] = $product->ID;
             }
         }
         $count++;
     }
     //adding product order item
     $item = new Product_OrderItem();
     $item->addBuyableToOrderItem($product, 7);
     $item->OrderID = $order->ID;
     $item->write();
     //final save
     $order->write();
     $order->tryToFinaliseOrder();
 }
コード例 #15
0
ファイル: PrepaidSignup.php プロジェクト: hemant-chakka/awss
 function doPrepaidSignup()
 {
     $data = $_POST;
     //Check for existing member email address
     if ($member = DataObject::get_one("Member", "`Email` = '" . Convert::raw2sql($data['Email']) . "'")) {
         return "inlineMsg1";
     }
     $currentYear = date('Y');
     $currentMonth = date('n');
     //Stop sign-up when the credit card is expired
     if ($data['ExpirationYear'] < $currentYear) {
         return "inlineMsg6";
     }
     if ($data['ExpirationYear'] == $currentYear) {
         if ($data['ExpirationMonth'] < $currentMonth) {
             return "inlineMsg6";
         }
     }
     //Get InfusionSoft Api
     $app = $this->getInfusionSoftApi();
     // Get country text from code
     $country = Geoip::countryCode2name($data['Country']);
     // Create IndusionSoft contact
     $returnFields = array('Id');
     $conInfo = $app->findByEmail($data['Email'], $returnFields);
     if (count($conInfo)) {
         $isConID = $conInfo[0]['Id'];
     } else {
         $conDat = array('FirstName' => $data['FirstName'], 'LastName' => $data['LastName'], 'Company' => $data['Company'], 'StreetAddress1' => $data['StreetAddress1'], 'StreetAddress2' => $data['StreetAddress2'], 'City' => $data['City'], 'State' => $data['State'], 'PostalCode' => $data['PostalCode'], 'Country' => $country, 'Email' => $data['Email']);
         $isConID = $app->addCon($conDat);
     }
     // Locate existing credit card
     $ccID = $app->locateCard($isConID, substr($data['CreditCardNumber'], -4, 4));
     $creditCardType = $this->getISCreditCardType($data['CreditCardType']);
     if (!$ccID) {
         //Validate the credit card
         $card = array('CardType' => $creditCardType, 'ContactId' => $isConID, 'CardNumber' => $data['CreditCardNumber'], 'ExpirationMonth' => sprintf("%02s", $data['ExpirationMonth']), 'ExpirationYear' => $data['ExpirationYear'], 'CVV2' => $data['CVVCode']);
         $result = $app->validateCard($card);
         if ($result['Valid'] == 'false') {
             return "inlineMsg5";
         }
         $ccData = array('ContactId' => $isConID, 'FirstName' => $data['FirstName'], 'LastName' => $data['LastName'], 'BillAddress1' => $data['StreetAddress1'], 'BillAddress2' => $data['StreetAddress2'], 'BillCity' => $data['City'], 'BillState' => $data['State'], 'BillZip' => $data['PostalCode'], 'BillCountry' => $country, 'CardType' => $creditCardType, 'NameOnCard' => $data['NameOnCard'], 'CardNumber' => $data['CreditCardNumber'], 'CVV2' => $data['CVVCode'], 'ExpirationMonth' => sprintf("%02s", $data['ExpirationMonth']), 'ExpirationYear' => $data['ExpirationYear']);
         $ccID = $app->dsAdd("CreditCard", $ccData);
     }
     // Create AttentionWizard member
     $member = new Member();
     $member->FirstName = $data['FirstName'];
     $member->Surname = $data['LastName'];
     $member->Email = $data['Email'];
     $member->Password = $data['Password']['_Password'];
     $member->ISContactID = $isConID;
     $memberID = $member->write();
     //Find or create the 'user' group
     if (!($userGroup = DataObject::get_one('Group', "Code = 'customers'"))) {
         $userGroup = new Group();
         $userGroup->Code = "customers";
         $userGroup->Title = "Customers";
         $userGroup->Write();
     }
     //Add member to user group
     $userGroup->Members()->add($member);
     //Get the current date
     $curdate = $app->infuDate(date('j-n-Y'));
     $product = Product::get()->byID(7);
     // Store credit card info
     $creditCard = new CreditCard();
     $creditCard->CreditCardType = $data['CreditCardType'];
     $creditCard->CreditCardNumber = $data['CreditCardNumber'];
     $creditCard->NameOnCard = $data['NameOnCard'];
     $creditCard->CreditCardCVV = $data['CVVCode'];
     $creditCard->ExpiryMonth = $data['ExpirationMonth'];
     $creditCard->ExpiryYear = $data['ExpirationYear'];
     $creditCard->Company = $data['Company'];
     $creditCard->StreetAddress1 = $data['StreetAddress1'];
     $creditCard->StreetAddress2 = $data['StreetAddress2'];
     $creditCard->City = $data['City'];
     $creditCard->State = $data['State'];
     $creditCard->PostalCode = $data['PostalCode'];
     $creditCard->Country = $data['Country'];
     $creditCard->Current = 1;
     $creditCard->ISCCID = $ccID;
     $creditCard->MemberID = $memberID;
     $creditCardID = $creditCard->write();
     // Create an Infusionsoft order
     $config = SiteConfig::current_site_config();
     $invoiceId = $app->blankOrder($isConID, $product->Name, $curdate, 0, 0);
     $orderItem = $app->addOrderItem($invoiceId, $this->getNonExpiringIsProductId(7), 3, floatval($data['Price']), intval($data['Quantity']), $product->Name, $product->Name);
     $result = $app->chargeInvoice($invoiceId, $product->Name, $ccID, $config->MerchantAccount, false);
     // Create an order
     $order = new Order();
     $order->OrderStatus = 'P';
     $order->Amount = $data['Price'] * $data['Quantity'];
     $order->MemberID = $memberID;
     $order->ProductID = 7;
     $order->CreditCardID = $creditCardID;
     $orderID = $order->write();
     $returnFields = array('_AttentionWizard', 'Leadsource');
     $conDat1 = $app->loadCon($isConID, $returnFields);
     if ($result['Successful']) {
         // Add tag Paid member - prepaid
         $app->grpAssign($isConID, 2290);
         $conDat = array('ContactType' => 'AW Customer');
         if (!isset($conDat1['_AttentionWizard'])) {
             $conDat['_AttentionWizard'] = 'Prepaid only - no subscription';
         }
         if (isset($conDat1['_AttentionWizard']) && $conDat1['_AttentionWizard'] != 'Paid and Current' && $conDat1['_AttentionWizard'] != 'Free') {
             $conDat['_AttentionWizard'] = 'Prepaid only - no subscription';
         }
         if (!isset($conDat1['Leadsource']) || !$conDat1['Leadsource']) {
             $conDat['Leadsource'] = 'AttentionWizard';
         }
         $conID = $app->updateCon($isConID, $conDat);
         // Note is added
         $conActionDat = array('ContactId' => $isConID, 'ActionType' => 'UPDATE', 'ActionDescription' => "Purchased AW Prepaid Credits", 'CreationDate' => $curdate, 'ActionDate' => $curdate, 'CompletionDate' => $curdate, 'UserID' => 1);
         $conActionID = $app->dsAdd("ContactAction", $conActionDat);
         // Update order
         $order->OrderStatus = 'c';
         $order->write();
         // Create a Subscription record
         $subscription = new Subscription();
         $subscription->StartDate = date("Y-m-d H:i:s");
         $subscription->MemberID = $memberID;
         $subscription->ProductID = 7;
         $subscription->OrderID = $orderID;
         $subscription->write();
         // Create a MemberCredits record
         $memberCredits = new MemberCredits();
         $memberCredits->Credits = $product->Credits * $data['Quantity'];
         $memberCredits->MemberID = $memberID;
         $memberCredits->ProductID = 7;
         $memberCredits->SubscriptionID = $subscription->ID;
         $memberCredits->write();
         $member->logIn();
         $this->setMessage('Success', 'Purchased non-expiring heatmaps successfully.');
         return 'url1';
     } else {
         //Update Infusionsoft contact
         $conDat = array('_AttentionWizard' => 'Unsuccessful prepaid sign-up', 'ContactType' => 'AW Prospect');
         if (!isset($conDat1['Leadsource'])) {
             $conDat['Leadsource'] = 'AttentionWizard';
         }
         $app->updateCon($isConID, $conDat);
         // Add an AW prospect tag
         $app->grpAssign($isConID, $this->getISTagIdByPaymentCode(strtoupper($result['Code'])));
         // Add a note
         $conActionDat = array('ContactId' => $isConID, 'ActionType' => 'UPDATE', 'ActionDescription' => "Unsuccessful attempt to sign-up prepaid plan", 'CreationDate' => $curdate, 'ActionDate' => $curdate, 'CompletionDate' => $curdate, 'UserID' => 1);
         $conActionID = $app->dsAdd("ContactAction", $conActionDat);
         $member->logIn();
         $this->setMessage('Error', 'Sorry,the payment failed due to some reason.please update your credit card.');
         return 'url2';
     }
 }
コード例 #16
0
 /**
  * Takes an order from being a cart to awaiting payment.
  *
  * @param Member $member - assign a member to the order
  *
  * @return boolean - success/failure
  */
 public function placeOrder()
 {
     if (!$this->order) {
         $this->error(_t("OrderProcessor.NULL", "A new order has not yet been started."));
         return false;
     }
     if (!$this->canPlace($this->order)) {
         //final cart validation
         return false;
     }
     if ($this->order->Locale) {
         ShopTools::install_locale($this->order->Locale);
     }
     //remove from session
     $cart = ShoppingCart::curr();
     if ($cart && $cart->ID == $this->order->ID) {
         ShoppingCart::singleton()->clear();
     }
     //update status
     if ($this->order->TotalOutstanding()) {
         $this->order->Status = 'Unpaid';
     } else {
         $this->order->Status = 'Paid';
     }
     if (!$this->order->Placed) {
         $this->order->Placed = SS_Datetime::now()->Rfc2822();
         //record placed order datetime
         if ($request = Controller::curr()->getRequest()) {
             $this->order->IPAddress = $request->getIP();
             //record client IP
         }
     }
     //re-write all attributes and modifiers to make sure they are up-to-date before they can't be changed again
     $items = $this->order->Items();
     if ($items->exists()) {
         foreach ($items as $item) {
             $item->onPlacement();
             $item->write();
         }
     }
     $modifiers = $this->order->Modifiers();
     if ($modifiers->exists()) {
         foreach ($modifiers as $modifier) {
             $modifier->write();
         }
     }
     //add member to order & customers group
     if ($member = Member::currentUser()) {
         if (!$this->order->MemberID) {
             $this->order->MemberID = $member->ID;
         }
         $cgroup = ShopConfig::current()->CustomerGroup();
         if ($cgroup->exists()) {
             $member->Groups()->add($cgroup);
         }
     }
     //allow decorators to do stuff when order is saved.
     $this->order->extend('onPlaceOrder');
     $this->order->write();
     //send confirmation if configured and receipt hasn't been sent
     if (self::config()->send_confirmation && !$this->order->ReceiptSent) {
         $this->notifier->sendConfirmation();
     }
     //notify admin, if configured
     if (self::config()->send_admin_notification) {
         $this->notifier->sendAdminNotification();
     }
     // Save order reference to session
     OrderManipulation::add_session_order($this->order);
     return true;
     //report success
 }
コード例 #17
0
 function old_testUnitPriceWithOrder()
 {
     $product = $this->objFromFixture('Product', 'p1a');
     $order = new Order();
     $order->Currency = 'EUR';
     $order->write();
     // @todo Currently you can't add items to an order directly
     $orderitem = new ProductOrderItem(null, null, $product, 1);
     $orderitem->OrderID = $order->ID;
     $orderitem->write();
     $this->assertEquals($orderitem->UnitPrice->Amount, 420);
     $this->assertEquals($orderitem->UnitPrice->Currency, 'EUR');
 }
コード例 #18
0
 function doPurchase($data, $form)
 {
     //Get InfusionSoft Api
     $app = $this->getInfusionSoftApi();
     // Get curent date
     $curdate = $app->infuDate(date('j-n-Y'));
     $member = Member::currentUser();
     $isConID = $member->ISContactID;
     $product = Product::get()->byID($data['ProductID']);
     // Get existing credit card ID
     $creditCard = $this->getCurrentCreditCard($member->ID);
     // Get the current InfusionSoft credit card ID
     $ccID = $creditCard->ISCCID;
     // Create an Infusionsoft order
     $config = SiteConfig::current_site_config();
     $invoiceId = $app->blankOrder($isConID, $product->Name, $curdate, 0, 0);
     $orderItem = $app->addOrderItem($invoiceId, intval($this->getNonExpiringIsProductId($data['ProductID'])), 3, floatval($product->Price), intval($data['Quantity']), $product->Name, $product->Name);
     $result = $app->chargeInvoice($invoiceId, $product->Name, $ccID, $config->MerchantAccount, false);
     // Create an order
     $order = new Order();
     $order->OrderStatus = 'P';
     $order->Amount = $product->Price * $data['Quantity'];
     $order->MemberID = $member->ID;
     $order->ProductID = $data['ProductID'];
     $order->CreditCardID = $creditCard->ID;
     $orderID = $order->write();
     if ($result['Successful']) {
         // Add tag Paid member - prepaid
         $app->grpAssign($isConID, 2290);
         $conDat = array('ContactType' => 'AW Customer');
         $returnFields = array('_AttentionWizard');
         $conDat1 = $app->loadCon($isConID, $returnFields);
         if ($conDat1['_AttentionWizard'] != 'Paid and Current' && $conDat1['_AttentionWizard'] != 'Free') {
             $conDat['_AttentionWizard'] = 'Prepaid only - no subscription';
         }
         $conID = $app->updateCon($isConID, $conDat);
         // Note is added
         $conActionDat = array('ContactId' => $isConID, 'ActionType' => 'UPDATE', 'ActionDescription' => "Purchased AW Prepaid Credits", 'CreationDate' => $curdate, 'ActionDate' => $curdate, 'CompletionDate' => $curdate, 'UserID' => 1);
         $conActionID = $app->dsAdd("ContactAction", $conActionDat);
         // Update order
         $order->OrderStatus = 'c';
         $order->write();
         // Create a Subscription record
         $subscription = new Subscription();
         $subscription->StartDate = date("Y-m-d H:i:s");
         $subscription->MemberID = $member->ID;
         $subscription->ProductID = $data['ProductID'];
         $subscription->OrderID = $orderID;
         $subscription->write();
         // Create a MemberCredits record
         $memberCredits = new MemberCredits();
         $memberCredits->Credits = $product->Credits * $data['Quantity'];
         $memberCredits->MemberID = $member->ID;
         $memberCredits->ProductID = $product->ID;
         $memberCredits->SubscriptionID = $subscription->ID;
         $memberCredits->write();
         $this->setMessage('Success', 'Purchased non-expiring heatmaps successfully.');
     } else {
         // Add an AW prospect tag
         $app->grpAssign($isConID, $this->getISTagIdByPaymentCode(strtoupper($result['Code'])));
         // Add a note
         $conActionDat = array('ContactId' => $isConID, 'ActionType' => 'UPDATE', 'ActionDescription' => "Unsuccessful attempt to purchase prepaid plan", 'CreationDate' => $curdate, 'ActionDate' => $curdate, 'CompletionDate' => $curdate, 'UserID' => 1);
         $conActionID = $app->dsAdd("ContactAction", $conActionDat);
         $this->setMessage('Error', 'Sorry,the payment failed,please update your credit card.');
         return $this->redirect('/account-settings/#tabs-2');
     }
     return $this->redirect('/account-settings');
 }
コード例 #19
0
 /**
  * ACTION /addtobasket
  * Add the requested item to the basket.
  */
 public function addtobasket($data)
 {
     /* Retreive the TempBasketID (Cookie) for the current users basket. If it doesn't exist, create one */
     if (Store_BasketController::get_temp_basket_id()) {
         $TempBasketID = Store_BasketController::get_temp_basket_id();
     } else {
         $TempBasketID = Store_BasketController::set_temp_basket_id();
     }
     /* Try to fetch an Order record using the TempBasketID */
     $Order = DataObject::get_one("Order", "(`TempBasketID`='" . $TempBasketID . "')");
     /**
      * If an Order record doesn't exist, create the Order record first.
      */
     if (!$Order) {
         $n = new Order();
         $n->TempBasketID = $TempBasketID;
         $n->write();
         $Order = DataObject::get_one("Order", "(`TempBasketID`='" . $TempBasketID . "')");
     }
     /**
      * Do any Order_Items exist for this Product in the current Order? If yes, increment Quantity.
      * Otherwise, add a new item.
      */
     $count = new SQLQuery("COUNT(*)");
     $count->setFrom("Order_Items")->addWhere("(`OriginalProductID`='" . $data["ProductID"] . "' AND `TempBasketID`='" . $TempBasketID . "')");
     if ($count->execute()->value() > 0) {
         DB::Query("UPDATE Order_Items SET Quantity=Quantity + " . $data["Qty"] . " WHERE (`OriginalProductID`='" . $data["ProductID"] . "' AND `TempBasketID`='" . $TempBasketID . "')");
     } else {
         /**
          * Proceed to add the selected Product to the order as an Order_Items with the same TempBasketID.
          */
         $order_item = new Order_Items();
         $order_item->OrderID = $Order->ID;
         $order_item->OriginalProductID = $data["ProductID"];
         $order_item->Quantity = $data["Qty"];
         $order_item->TempBasketID = $TempBasketID;
         /**
          * As this order is still in its 'Shopping Basket' stages we will have no customer information
          * to calculate tax with at this time. Set tax rate and class to zero for now.
          */
         $order_item->TaxClassName = "To Be Calculated";
         $order_item->TaxClassRate = "0.00";
         /* Write to the database */
         $order_item->write();
     }
     /* Take the user to their Basket */
     return $this->redirect(Store_BasketController::get_link());
 }
コード例 #20
0
 function old_testProductOrderItems()
 {
     $product1a = $this->objFromFixture('Product', 'p1a');
     $product1b = $this->objFromFixture('Product', 'p1b');
     $order = new Order();
     $order->Currency = 'USD';
     $order->write();
     $item1a = new ProductOrderItem(null, null, $product1a, 2);
     $item1a->write();
     $order->Items()->add($item1a);
     $item1b = new ProductOrderItem(null, null, $product1b, 1);
     $item1b->write();
     $order->Items()->add($item1b);
     $item1c = new ProductOrderItem(null, null, $product1a, 1);
     $item1c->write();
     $order->Items()->add($item1c);
     $items = $order->ProductOrderItems();
     $testString = 'ProductList: ';
     foreach ($items as $item) {
         $testString .= $item->Product()->Title . ";";
     }
     $this->assertEquals($testString, "ProductList: Product 1a;Product 1b;Product 1a;");
 }
コード例 #21
0
 /**
  * Create a new address if the existing address has changed, or is not yet
  * created.
  *
  * @param Order $order order to get addresses from
  * @param array $data  data to set
  */
 public function setData(Order $order, array $data)
 {
     $existingID = !empty($data[$this->addresstype . "AddressID"]) ? (int) $data[$this->addresstype . "AddressID"] : 0;
     if ($existingID > 0) {
         $order->{$this->addresstype . "AddressID"} = $existingID;
         $order->write();
         $order->extend('onSet' . $this->addresstype . 'Address', $address);
     } else {
         parent::setData($order, $data);
     }
 }
コード例 #22
0
 public function setData(Order $order, array $data)
 {
     $order->update($data);
     $order->write();
 }
コード例 #23
0
 /**
  * Takes an order from being a cart to awaiting payment.
  *
  * @param Member $member - assign a member to the order
  *
  * @return boolean - success/failure
  */
 public function placeOrder()
 {
     if (!$this->order) {
         $this->error(_t("OrderProcessor.NoOrderStarted", "A new order has not yet been started."));
         return false;
     }
     if (!$this->canPlace($this->order)) {
         //final cart validation
         return false;
     }
     if ($this->order->Locale) {
         ShopTools::install_locale($this->order->Locale);
     }
     // recalculate order to be sure we have the correct total
     $this->order->calculate();
     if (ShopTools::DBConn()->supportsTransactions()) {
         ShopTools::DBConn()->transactionStart();
     }
     //update status
     if ($this->order->TotalOutstanding(false)) {
         $this->order->Status = 'Unpaid';
     } else {
         $this->order->Status = 'Paid';
     }
     if (!$this->order->Placed) {
         $this->order->Placed = SS_Datetime::now()->Rfc2822();
         //record placed order datetime
         if ($request = Controller::curr()->getRequest()) {
             $this->order->IPAddress = $request->getIP();
             //record client IP
         }
     }
     // Add an error handler that throws an exception upon error, so that we can catch errors as exceptions
     // in the following block.
     set_error_handler(function ($severity, $message, $file, $line) {
         throw new ErrorException($message, 0, $severity, $file, $line);
     }, E_ALL & ~(E_STRICT | E_NOTICE));
     try {
         //re-write all attributes and modifiers to make sure they are up-to-date before they can't be changed again
         $items = $this->order->Items();
         if ($items->exists()) {
             foreach ($items as $item) {
                 $item->onPlacement();
                 $item->write();
             }
         }
         $modifiers = $this->order->Modifiers();
         if ($modifiers->exists()) {
             foreach ($modifiers as $modifier) {
                 $modifier->write();
             }
         }
         //add member to order & customers group
         if ($member = Member::currentUser()) {
             if (!$this->order->MemberID) {
                 $this->order->MemberID = $member->ID;
             }
             $cgroup = ShopConfig::current()->CustomerGroup();
             if ($cgroup->exists()) {
                 $member->Groups()->add($cgroup);
             }
         }
         //allow decorators to do stuff when order is saved.
         $this->order->extend('onPlaceOrder');
         $this->order->write();
     } catch (Exception $ex) {
         // Rollback the transaction if an error occurred
         if (ShopTools::DBConn()->supportsTransactions()) {
             ShopTools::DBConn()->transactionRollback();
         }
         $this->error($ex->getMessage());
         return false;
     } finally {
         // restore the error handler, no matter what
         restore_error_handler();
     }
     // Everything went through fine, complete the transaction
     if (ShopTools::DBConn()->supportsTransactions()) {
         ShopTools::DBConn()->transactionEnd();
     }
     //remove from session
     $cart = ShoppingCart::curr();
     if ($cart && $cart->ID == $this->order->ID) {
         // clear the cart, but don't write the order in the process (order is finalized and should NOT be overwritten)
         ShoppingCart::singleton()->clear(false);
     }
     //send confirmation if configured and receipt hasn't been sent
     if (self::config()->send_confirmation && !$this->order->ReceiptSent) {
         $this->notifier->sendConfirmation();
     }
     //notify admin, if configured
     if (self::config()->send_admin_notification) {
         $this->notifier->sendAdminNotification();
     }
     // Save order reference to session
     OrderManipulation::add_session_order($this->order);
     return true;
     //report success
 }
コード例 #24
0
ファイル: Page.php プロジェクト: hemant-chakka/awss
 public function moveOrdersFromJoomlaToSS()
 {
     die('test3');
     error_reporting(E_ALL);
     ini_set('display_errors', 1);
     ini_set('max_execution_time', 0);
     ini_set('memory_limit', '-1');
     $mysqli = $this->getDbConnection();
     $result = $mysqli->query("SELECT * FROM jos_users u\n\t\tINNER JOIN jos_osemsc_orders o ON u.id = o.user_id\n\t\tLEFT JOIN jos_aw_cc cc ON o.order_number = cc.cc_order_number");
     $count = 0;
     while ($obj = $result->fetch_object()) {
         $ssMember = $this->getSSMember($obj->email);
         if (!$ssMember) {
             continue;
         }
         $order = new Order();
         $order->Created = $obj->date;
         $order->LastEdited = $obj->date;
         $order->OrderStatus = $obj->order_status;
         $order->Amount = $obj->payment_price;
         $order->JoomlaOrderNumber = $obj->order_number;
         if ($obj->payment_price == 0.01 || $obj->payment_price == 1) {
             $order->IsTrial = 1;
         }
         $order->MemberID = $ssMember->ID;
         $order->ProductID = $obj->msc_id;
         $order->ProductID = $obj->msc_id;
         if ($obj->cc_number && ($ssCreditCard = $this->getSSCreditCard($obj->cc_number, $ssMember->ID))) {
             $order->CreditCardID = $ssCreditCard->ID;
         } else {
             if ($cardId = $this->getSSCreditCardId2($obj->id, $ssMember->ID, $obj->date)) {
                 $order->CreditCardID = $cardId;
             }
         }
         $order->write();
         $count++;
     }
     $mysqli->close();
     echo "Total Orders moved: {$count}";
 }
コード例 #25
0
 function createSubscription($request)
 {
     //Get product id
     $productID = $request->param('ProductID');
     // Get AttentionWizard member
     $member = Member::currentUser();
     //Get InfusionSoft Api
     $app = $this->getInfusionSoftApi();
     // Get IndusionSoft contact ID
     $isConID = $member->ISContactID;
     $product = Product::get()->byID($productID);
     $credits = $product->Credits;
     // Get existing credit card ID
     $creditCard = $this->getCurrentCreditCard($member->ID);
     if (!$creditCard) {
         $this->setMessage('Error', 'Sorry,the payment failed,please update your credit card.');
         return $this->redirect('/account-settings/#tabs-2');
     }
     $ccID = $creditCard->ISCCID;
     $subscriptionID = $this->createISSubscription($isConID, $product->ISProductID, $product->RecurringPrice, $ccID, 30);
     if ($subscriptionID && is_int($subscriptionID)) {
         if ($productID == 1 && !$this->isCCUsedForTrial($creditCard->CreditCardNumber)) {
             $orderAmount = $product->TrialPrice;
             $productName = "30 days 1-dollar Trial";
             $isProductID = 38;
             $trial = 1;
             $subscriptionCount = 0;
         } else {
             $productName = $product->Name;
             $orderAmount = $product->RecurringPrice;
             $isProductID = $product->ISInitialProductID;
             $trial = 0;
             $subscriptionCount = 1;
         }
         // Create an order
         $order = new Order();
         $order->OrderStatus = 'P';
         $order->Amount = $orderAmount;
         $order->MemberID = $member->ID;
         $order->ProductID = $productID;
         $order->CreditCardID = $creditCard->ID;
         $orderID = $order->write();
         //get the current date
         $curdate = $app->infuDate(date('j-n-Y'));
         //Create an infusionsoft order
         $config = SiteConfig::current_site_config();
         $invoiceId = $app->blankOrder($isConID, $productName, $curdate, 0, 0);
         $orderItem = $app->addOrderItem($invoiceId, $isProductID, 9, floatval($orderAmount), 1, $productName, $productName);
         $result = $app->chargeInvoice($invoiceId, $productName, $ccID, $config->MerchantAccount, false);
         if ($result['Successful']) {
             // Update order
             $order->OrderStatus = 'c';
             $order->IsTrial = $trial;
             $order->write();
             // Create a Subscription record
             $nextBillDate = $this->getSubscriptionNextBillDate($subscriptionID);
             $expireDate = date('Y-m-d H:i:s', strtotime($nextBillDate));
             $startDate = date('Y-m-d H:i:s', strtotime($expireDate . "-30 days"));
             $subscription = new Subscription();
             $subscription->SubscriptionID = $subscriptionID;
             $subscription->StartDate = $startDate;
             $subscription->ExpireDate = $expireDate;
             $subscription->Status = 1;
             $subscription->IsTrial = $trial;
             $subscription->SubscriptionCount = $subscriptionCount;
             $subscription->MemberID = $member->ID;
             $subscription->ProductID = $productID;
             $subscription->OrderID = $orderID;
             $subscription->write();
             // Create a MemberCredits record
             $memberCredits = new MemberCredits();
             $memberCredits->Credits = $credits;
             $memberCredits->ExpireDate = $expireDate;
             $memberCredits->MemberID = $member->ID;
             $memberCredits->ProductID = $productID;
             $memberCredits->SubscriptionID = $subscription->ID;
             $memberCredits->write();
             //Get contact custom fields
             $returnFields = array('_AWofmonths', '_AWstartdate');
             $conDat1 = $app->loadCon($isConID, $returnFields);
             if ($productID == 1 && !$this->isCCUsedForTrial($creditCard->CreditCardNumber)) {
                 // Update Member
                 $member->SignUpTrial = 1;
                 $member->write();
                 //Add the Trial tag
                 $app->grpAssign($isConID, 2216);
                 //Update the contact
                 $conDat = array('_AttentionWizard' => 'Free', 'ContactType' => 'AW Customer', '_AWcanceldate' => null);
                 if (!isset($conDat1['_AWstartdate'])) {
                     $conDat['_AWstartdate'] = $curdate;
                 }
                 $app->updateCon($isConID, $conDat);
                 // Mark credit card as TrialCreditCard
                 $creditCard->UsedForTrial = 1;
                 $creditCard->write();
             } else {
                 if (!isset($conDat1['_AWofmonths'])) {
                     $conDat1['_AWofmonths'] = 0;
                 }
                 // Add the InfusionSoft tag
                 $isTagId = $this->getISTagIdByProduct($productID);
                 $app->grpRemove($isConID, $isTagId);
                 $app->grpAssign($isConID, $isTagId);
                 //Remove trial tag if exists
                 $app->grpRemove($isConID, 2216);
                 //Update the InfusionSoft contact details
                 $conDat = array('_AWofmonths' => $conDat1['_AWofmonths'] + 1, 'ContactType' => 'AW Customer', '_AttentionWizard' => 'Paid and Current', '_AWcanceldate' => null);
                 if (!isset($conDat1['_AWstartdate'])) {
                     $conDat['_AWstartdate'] = $curdate;
                 }
                 $app->updateCon($isConID, $conDat);
                 // Note is added
                 $conActionDat = array('ContactId' => $isConID, 'ActionType' => 'UPDATE', 'ActionDescription' => "Renewed AW subscription", 'CreationDate' => $curdate, 'ActionDate' => $curdate, 'CompletionDate' => $curdate, 'UserID' => 1);
                 $conActionID = $app->dsAdd("ContactAction", $conActionDat);
                 //Delete all the previous pending orders
                 //DB::query("DELETE from `Order` where MemberID = $member->ID AND OrderStatus = 'P'");
             }
             // Remove previous cancel tags
             $app->grpRemove($isConID, 2226);
             $app->grpRemove($isConID, 2758);
             $app->grpRemove($isConID, 2682);
             $app->grpRemove($isConID, 2680);
             $app->grpRemove($isConID, 2694);
             $app->grpRemove($isConID, 3019);
             $app->grpRemove($isConID, 3097);
         } else {
             //Set the subscription to Inactive
             $this->setSubscriptionStatus($subscriptionID, 'Inactive');
             if ($productID == 1 && !$this->isCCUsedForTrial($creditCard->CreditCardNumber)) {
                 $aw = 'Unsuccessful trial sign-up';
             } else {
                 $aw = 'Unsuccessful paid sign-up';
             }
             $conDat = array('_AttentionWizard' => $aw);
             $app->updateCon($isConID, $conDat);
             // Add an AW prospect tag
             $app->grpAssign($isConID, $this->getISTagIdByPaymentCode($result['Code']));
             // Add a note
             $conActionDat = array('ContactId' => $isConID, 'ActionType' => 'UPDATE', 'ActionDescription' => "Unsuccessful attempt to sign-up for AW", 'CreationDate' => $curdate, 'ActionDate' => $curdate, 'CompletionDate' => $curdate, 'UserID' => 1);
             $conActionID = $app->dsAdd("ContactAction", $conActionDat);
             $this->setMessage('Error', 'Sorry,the payment failed,please update your credit card.');
             return $this->redirect('/account-settings/#tabs-2');
         }
     } else {
         // Add an AW prospect tag
         $app->grpAssign($isConID, 3097);
         //Update InfusionSoft contact
         if ($productID == 1 && !$this->isCCUsedForTrial($creditCard->CreditCardNumber)) {
             $aw = 'Unsuccessful trial sign-up';
         } else {
             $aw = 'Unsuccessful paid sign-up';
         }
         $conDat = array('_AttentionWizard' => $aw);
         $app->updateCon($isConID, $conDat);
         // Add a note
         $conActionDat = array('ContactId' => $isConID, 'ActionType' => 'UPDATE', 'ActionDescription' => "Unsuccessful attempt to sign-up for AW", 'CreationDate' => $curdate, 'ActionDate' => $curdate, 'CompletionDate' => $curdate, 'UserID' => 1);
         $conActionID = $app->dsAdd("ContactAction", $conActionDat);
         $this->setMessage('Error', 'Sorry,the subscription not created due to some reason.please try again.');
         return $this->redirect('/account-settings/#tabs-4');
     }
     $this->setMessage('Success', 'The Subscription is created successfully.');
     return $this->redirect('/account-settings');
 }
コード例 #26
0
 /**
  * Add a member to the order - in case he / she is not a shop admin.
  *
  * @param Order object
  * @return Boolean - true if run correctly.
  **/
 public function doStep(Order $order)
 {
     if (!$order->IsSubmitted()) {
         $className = $this->getRelevantLogEntryClassName();
         if (class_exists($className)) {
             //add currency if needed.
             $order->getHasAlternativeCurrency();
             $obj = $className::create();
             if (is_a($obj, Object::getCustomClass("OrderStatusLog"))) {
                 $obj->OrderID = $order->ID;
                 $obj->Title = $this->Name;
                 //it is important we add this here so that we can save the 'submitted' version.
                 //this is particular important for the Order Item Links.
                 //order write will also update all the OrderAttributes!
                 $obj->write();
                 $obj = OrderStatusLog::get()->byID($obj->ID);
                 $saved = false;
                 if ($this->SaveOrderAsSerializedObject) {
                     $obj->OrderAsString = $order->ConvertToString();
                     $saved = true;
                 }
                 if ($this->SaveOrderAsHTML || !$saved) {
                     $obj->OrderAsHTML = Convert::raw2sql($order->ConvertToHTML());
                 }
                 $obj->write();
             } else {
                 user_error('EcommerceConfig::get("OrderStatusLog", "order_status_log_class_used_for_submitting_order") refers to a class that is NOT an instance of OrderStatusLog');
             }
         } else {
             user_error('EcommerceConfig::get("OrderStatusLog", "order_status_log_class_used_for_submitting_order") refers to a non-existing class');
         }
         $order->LastEdited = "'" . SS_Datetime::now()->Rfc2822() . "'";
         //add member if needed...
         if (!$order->MemberID) {
             //lets see if we can find a member
             $memberOrderID = Session::get("Ecommerce_Member_For_Order");
             Session::clear("Ecommerce_Member_For_Order");
             Session::set("Ecommerce_Member_For_Order", 0);
             Session::save();
             if ($memberOrderID) {
                 $order->MemberID = $memberOrderID;
             }
         }
         $order->write($showDebug = false, $forceInsert = false, $forceWrite = true);
     }
     return true;
 }
コード例 #27
0
 /**
  * Process the items in the shopping cart from session,
  * creating a new {@link Order} record, and updating the
  * customer's details {@link Member} record.
  *
  * {@link Payment} instance is created, linked to the order,
  * and payment is processed {@link Payment::processPayment()}
  *
  * @param array $data Form request data submitted from OrderForm
  * @param Form $form Form object for this action
  * @param HTTPRequest $request Request object for this action
  */
 function saveAddress(array $data, Form $form, SS_HTTPRequest $request)
 {
     Session::set("BillingEcommerceGeocodingFieldValue", empty($data["BillingEcommerceGeocodingField"]) ? null : $data["BillingEcommerceGeocodingField"]);
     Session::set("ShippingEcommerceGeocodingFieldValue", empty($data["ShippingEcommerceGeocodingField"]) ? null : $data["ShippingEcommerceGeocodingField"]);
     $data = Convert::raw2sql($data);
     //check for cart items
     if (!$this->order) {
         $form->sessionMessage(_t('OrderForm.ORDERNOTFOUND', 'Your order could not be found.'), 'bad');
         $this->controller->redirectBack();
         return false;
     }
     if ($this->order && $this->order->TotalItems($recalculate = true) < 1) {
         // WE DO NOT NEED THE THING BELOW BECAUSE IT IS ALREADY IN THE TEMPLATE AND IT CAN LEAD TO SHOWING ORDER WITH ITEMS AND MESSAGE
         $form->sessionMessage(_t('OrderForm.NOITEMSINCART', 'Please add some items to your cart.'), 'bad');
         $this->controller->redirectBack();
         return false;
     }
     //----------- START BY SAVING INTO ORDER
     $form->saveInto($this->order);
     //----------- --------------------------------
     //MEMBER
     $this->orderMember = $this->createOrFindMember($data);
     if ($this->orderMember && is_object($this->orderMember)) {
         if ($this->memberShouldBeSaved($data)) {
             $form->saveInto($this->orderMember);
             $password = $this->validPasswordHasBeenEntered($data);
             if ($password) {
                 $this->orderMember->changePassword($password);
             }
             $this->orderMember->write();
         }
         if ($this->memberShouldBeLoggedIn($data)) {
             $this->orderMember->LogIn();
         }
         //this causes ERRORS ....
         //$this->order->MemberID = $this->orderMember->ID;
         Session::set("Ecommerce_Member_For_Order", $this->orderMember->ID);
     }
     //BILLING ADDRESS
     if ($billingAddress = $this->order->CreateOrReturnExistingAddress("BillingAddress")) {
         $form->saveInto($billingAddress);
         // NOTE: write should return the new ID of the object
         $this->order->BillingAddressID = $billingAddress->write();
     }
     // SHIPPING ADDRESS
     if (isset($data['UseShippingAddress'])) {
         if ($data['UseShippingAddress']) {
             if ($shippingAddress = $this->order->CreateOrReturnExistingAddress("ShippingAddress")) {
                 $form->saveInto($shippingAddress);
                 // NOTE: write should return the new ID of the object
                 $this->order->ShippingAddressID = $shippingAddress->write();
             }
         }
     }
     $this->extend("saveAddressExtension", $data, $form, $order, $this->orderMember);
     //SAVE ORDER
     $this->order->write();
     //----------------- CLEAR OLD DATA ------------------------------
     $this->clearSessionData();
     //clears the stored session form data that might have been needed if validation failed
     //-----------------------------------------------
     $nextStepLink = CheckoutPage::find_next_step_link("orderformaddress");
     $this->controller->redirect($nextStepLink);
     return true;
 }
コード例 #28
0
 public function testSinglePageConfigForSingleCountrySiteWithReadonlyFieldsForCountry()
 {
     // Set as a single country site
     $this->loadFixture("shop/tests/fixtures/singlecountry.yml");
     $singlecountry = SiteConfig::current_site_config();
     $this->assertEquals("NZ", $singlecountry->getSingleCountry(), "Confirm that website is setup as a single country site");
     $order = new Order();
     //start a new order
     $order->write();
     $config = new SinglePageCheckoutComponentConfig($order);
     $customerdetailscomponent = $config->getComponentByType("CustomerDetailsCheckoutComponent");
     $customerdetailscomponent->setData($order, array("FirstName" => "John", "Surname" => "Walker", "Email" => "*****@*****.**"));
     $shippingaddresscomponent = $config->getComponentByType("ShippingAddressCheckoutComponent");
     $shippingaddresscomponent->setData($order, $this->addressNoCountry->toMap());
     $billingaddresscomponent = $config->getComponentByType("BillingAddressCheckoutComponent");
     $billingaddresscomponent->setData($order, $this->addressNoCountry->toMap());
     $paymentcomponent = $config->getComponentByType("PaymentCheckoutComponent");
     $paymentcomponent->setData($order, array("PaymentMethod" => "Dummy"));
     $fields = $config->getFormFields();
     $shippingaddressfield = $fields->fieldByName("ShippingAddressCheckoutComponent_Country_readonly");
     $billingaddressfield = $fields->fieldByName("BillingAddressCheckoutComponent_Country_readonly");
     $this->assertContains("New Zealand", $shippingaddressfield->Value(), "The value of the Shipping Country readonly field is 'New Zealand'");
     $this->assertContains("New Zealand", $billingaddressfield->Value(), "The value of the Billing Country readonly field is 'New Zealand'");
     $this->assertTrue($shippingaddressfield->isReadonly(), "The Shipping Address Country field is readonly");
     $this->assertTrue($shippingaddressfield->isReadonly(), "The Billing Address Country field is readonly");
     $required = $config->getRequiredFields();
     $requiredfieldswithCountryAbsent = array("CustomerDetailsCheckoutComponent_FirstName", "CustomerDetailsCheckoutComponent_Surname", "CustomerDetailsCheckoutComponent_Email", "ShippingAddressCheckoutComponent_State", "ShippingAddressCheckoutComponent_City", "ShippingAddressCheckoutComponent_Address", "BillingAddressCheckoutComponent_State", "BillingAddressCheckoutComponent_City", "BillingAddressCheckoutComponent_Address");
     $this->assertSame($requiredfieldswithCountryAbsent, $required, "getRequiredFields function returns required fields from numerous components except for the Country fields (no need to validate readonly fields)");
     $data = $config->getData();
     $this->assertEquals("NZ", $data["ShippingAddressCheckoutComponent_Country"]);
     $this->assertEquals("NZ", $data["BillingAddressCheckoutComponent_Country"]);
     $validateData = $config->validateData($data);
     $this->assertTrue($validateData, print_r($validateData, true), "Data validation must return true.  Note: should not be testing a country field here as validation of a readonly field is not necessary" . print_r($validateData, true));
     $config->setData($data);
 }
コード例 #29
0
 /**
  * NOTE: tried to copy part to the Order Class - but that was not much of a go-er.
  * @param Int | Order $order
  * @return DataObject(Order)
  **/
 public function copyOrder($oldOrder)
 {
     if (is_numeric($oldOrder)) {
         $oldOrder = DataObject::get_by_id('Order', intval($oldOrder));
     } elseif ($oldOrder instanceof Order) {
         //$oldOrder = $oldOrder;
     }
     if ($oldOrder) {
         if ($oldOrder->canView()) {
             $newOrder = new Order();
             //for later use...
             $newOrder->MemberID = $oldOrder->MemberID;
             $newOrder->write();
             $this->loadOrder($newOrder);
             $items = DataObject::get("OrderItem", "\"OrderID\" = " . $oldOrder->ID);
             if ($items) {
                 foreach ($items as $item) {
                     $buyable = $item->Buyable($current = true);
                     if ($buyable->canPurchase()) {
                         $this->addBuyable($buyable, $item->Quantity);
                     }
                 }
             }
             $newOrder->write();
             $this->addMessage(_t("ShoppingCart.ORDERCOPIED", "Order has been copied."), 'good');
             return true;
         } else {
             $this->addMessage(_t("ShoppingCart.NOPERMISSION", "You do not have permission to view this order."), 'bad');
             return false;
         }
     } else {
         $this->addMessage(_t("ShoppingCart.NOORDER", "Order can not be found."), 'bad');
         return false;
     }
 }
コード例 #30
0
 /**
  * creates order from repeatorder for a specific day.
  * IF it does not already exists.
  *
  */
 protected function createOrderFromRepeatOrder($orderDateInteger)
 {
     if ($order = DataObject::get_one("Order", "\"OrderDateInteger\" = '" . $orderDateInteger . "' AND \"RepeatOrderID\" = " . $this->ID)) {
         //do nothing
     } else {
         $order = new Order();
         $order->OrderDate = date("Y-m-d", $orderDateInteger);
         $order->OrderDateInteger = $orderDateInteger;
         $order->RepeatOrderID = $this->ID;
         $order->MemberID = $this->MemberID;
         $order->CustomerOrderNote = "Created as part of a repeating order.";
         $order->write();
         if ($this->OrderItems()) {
             foreach ($this->OrderItems() as $repeatOrderOrderItem) {
                 $product = DataObject::get_by_id('Product', $repeatOrderOrderItem->ProductID);
                 if ($product) {
                     //START CHECK AVAILABILITY
                     if (class_exists("ProductStockCalculatedQuantity")) {
                         $numberAvailable = ProductStockCalculatedQuantity::get_quantity_by_product_id($product->ID);
                         if ($numberAvailable < $repeatOrderOrderItem->Quantity) {
                             $alternatives = $repeatOrderOrderItem->AlternativesPerProduct();
                             $product = null;
                             if ($dos) {
                                 foreach ($alternatives as $alternative) {
                                     $stillLookingForAlternative = true;
                                     $numberAvailable = ProductStockCalculatedQuantity::get_quantity_by_product_id($alternative->ID);
                                     if ($numberAvailable > $repeatOrderOrderItem->Quantity && $stillLookingForAlternative) {
                                         $stillLookingForAlternative = false;
                                         $product = $alternative;
                                     }
                                 }
                             }
                         }
                     }
                     //END CHECK AVAILABILITY
                     if ($product) {
                         $newProductOrderItem = new Product_OrderItem();
                         $newProductOrderItem->addBuyableToOrderItem($product, $repeatOrderOrderItem->Quantity);
                         $newProductOrderItem->OrderID = $order->ID;
                         $newProductOrderItem->write();
                     }
                 } else {
                     USER_ERROR("Product does not exist", E_USER_WARNING);
                 }
             }
         } else {
             USER_ERROR("There are no order items", E_USER_WARNING);
         }
         //FINALISE!!!
         $order->write();
         $order->tryToFinaliseOrder();
     }
 }