function SubmittedOrder() { $lastStatusOrder = OrderStep::get()->Last(); if ($lastStatusOrder) { return Order::get()->Filter("StatusID", $lastStatusOrder->ID)->Sort("RAND()")->First(); } }
/** * (non-PHPdoc) * @see DetailsPageAbstract::saveItem() */ public function saveItem($sender, $param) { $results = $errors = array(); try { Dao::beginTransaction(); $task = null; if (isset($param->CallbackParameter->id) && !($task = Task::get(trim($param->CallbackParameter->id))) instanceof Task) { throw new Exception('Invalid Task passed in!'); } if (!isset($param->CallbackParameter->instructions) || ($instructions = trim($param->CallbackParameter->instructions)) === '') { throw new Exception('Instructions are required!'); } if (!isset($param->CallbackParameter->customerId) || !($customer = Customer::get(trim($param->CallbackParameter->customerId))) instanceof Customer) { throw new Exception('Invalid Customer Passed in!'); } $tech = isset($param->CallbackParameter->techId) ? UserAccount::get(trim($param->CallbackParameter->techId)) : null; $order = isset($param->CallbackParameter->orderId) ? Order::get(trim($param->CallbackParameter->orderId)) : null; $dueDate = new UDate(trim($param->CallbackParameter->dueDate)); $status = isset($param->CallbackParameter->statusId) ? TaskStatus::get(trim($param->CallbackParameter->statusId)) : null; if (!$task instanceof Task) { $task = Task::create($customer, $dueDate, $instructions, $tech, $order); } else { $task->setCustomer($customer)->setDueDate($dueDate)->setInstructions($instructions)->setTechnician($tech)->setFromEntityId($order instanceof Order ? $order->getId() : '')->setFromEntityName($order instanceof Order ? get_class($order) : '')->setStatus($status)->save(); } // $results['url'] = '/task/' . $task->getId() . '.html?' . $_SERVER['QUERY_STRING']; $results['item'] = $task->getJson(); Dao::commitTransaction(); } catch (Exception $ex) { Dao::rollbackTransaction(); $errors[] = $ex->getMessage(); } $param->ResponseData = StringUtilsAbstract::getJson($results, $errors); }
public function BillingHistory() { $billingHistory = new ArrayList(); $orders = Order::get()->filter(array('MemberID' => Member::currentUserID(), 'OrderStatus' => 'c'))->sort('Created'); foreach ($orders as $order) { $productId = $order->ProductID; if (($productId == 1 || $productId == 2 || $productId == 3) && $order->IsTrial == 1) { $productDesc = 'First Month Trial'; } else { $product = Product::get()->byID($productId); $productDesc = $product->Name; } $creditCard = $order->CreditCard(); $ccNumber = 'XXXX-XXXX-XXXX-' . substr($creditCard->CreditCardNumber, -4); $orderDetails = array('Date' => $order->Created, 'Description' => $productDesc, 'CCType' => strtoupper($creditCard->CreditCardType), 'CCNumber' => $ccNumber, 'Amount' => $order->Amount); $billingHistory->push(new ArrayData($orderDetails)); } $memBillHistory = MemberBillingHistory::get()->filter('MemberID', Member::currentUserID())->sort('Created'); foreach ($memBillHistory as $history) { $creditCard = $history->CreditCard(); $ccNumber = 'XXXX-XXXX-XXXX-' . substr($creditCard->CreditCardNumber, -4); $details = array('Date' => $history->Created, 'Description' => $history->Product()->Name, 'CCType' => strtoupper($creditCard->CreditCardType), 'CCNumber' => $ccNumber, 'Amount' => $history->Product()->RecurringPrice); $billingHistory->push(new ArrayData($details)); } $sortedBillingHistory = $billingHistory->sort('Date'); return $sortedBillingHistory; }
/** * Sending the email out * * @param unknown $sender * @param unknown $param * * @throws Exception */ public function sendEmail($sender, $param) { $results = $errors = array(); try { Dao::beginTransaction(); if (!isset($param->CallbackParameter->orderId) || !($order = Order::get($param->CallbackParameter->orderId)) instanceof Order) { throw new Exception('System Error: invalid order provided!'); } if (!isset($param->CallbackParameter->emailAddress) || ($emailAddress = trim($param->CallbackParameter->emailAddress)) === '') { throw new Exception('System Error: invalid emaill address provided!'); } $emailBody = ''; if (isset($param->CallbackParameter->emailBody) && ($emailBody = trim($param->CallbackParameter->emailBody)) !== '') { $emailBody = str_replace("\n", "<br />", $emailBody); } $pdfFile = EntityToPDF::getPDF($order); $asset = Asset::registerAsset($order->getOrderNo() . '.pdf', file_get_contents($pdfFile), Asset::TYPE_TMP); $type = $order->getType(); EmailSender::addEmail('*****@*****.**', $emailAddress, 'BudgetPC ' . $type . ':' . $order->getOrderNo(), (trim($emailBody) === '' ? '' : $emailBody . "<br /><br />") . 'Please find attached ' . $type . ' (' . $order->getOrderNo() . '.pdf) from Budget PC Pty Ltd.', array($asset)); $order->addComment('An email sent to "' . $emailAddress . '" with the attachment: ' . $asset->getAssetId(), Comments::TYPE_SYSTEM); $results['item'] = $order->getJson(); Dao::commitTransaction(); } catch (Exception $ex) { Dao::rollbackTransaction(); $errors[] = $ex->getMessage(); } $param->ResponseData = StringUtilsAbstract::getJson($results, $errors); }
/** * Display the currently selected order from the URL * */ public function order() { $orderID = $this->owner->request->param("ID"); $order = Order::get()->byID($orderID); $this->owner->customise(array("ClassName" => "AccountPage", "Order" => $order)); return $this->owner->renderWith(array("UserAccount_order", "UserAccount", "Page")); }
function export() { $orders = Order::get()->innerJoin("Address", "\"Order\".\"ShippingAddressID\" = \"Address\".\"ID\"")->filter("SentToDispatchIT", 0)->filter("Status", Order::config()->placed_status)->filter("Address.Country", "NZ")->sort(array("Placed" => "ASC", "Created" => "ASC")); $output = ""; if ($orders->exists()) { foreach ($orders as $order) { $address = $order->getShippingAddress(); $name = $address->Company; //TODO: company if (!$name || $name == "") { $name = $order->Name; } $line = array($order->ID, $order->MemberID, $name, $address->Address, $address->AddressLine2, $address->Suburb, $address->State, $address->City, "", "0", "1", "", $address->Phone, "", $order->Fax, $order->Email, "1", "", "0", "", "0"); $output .= implode("\t", $line) . "\n"; $order->SentToDispatchIT = true; $order->write(); } //store output in a local file, then output the contents, or a link to the file //name format: DDcxxxxxxx.TXT $filename = "DDc" . uniqid() . "_" . date('YmdHis') . ".txt"; $exportpath = ASSETS_PATH . "/_dispatchitexports"; if (!is_dir($exportpath)) { mkdir($exportpath); } if (file_put_contents($exportpath . "/{$filename}", $output) === false) { $output = "failed to save file"; } } else { $output = "no new orders"; } header('Content-type: text/plain'); echo $output; die; }
public function testModifierFailure() { if (!ShopTools::DBConn()->supportsTransactions()) { $this->markTestSkipped('The Database doesn\'t support transactions.'); } Config::inst()->update('Order', 'modifiers', array('OrderModifierTest_TestModifier')); $order = $this->createOrder(); $order->calculate(); $order->write(); // 408 from items + 10 from modifier + 25% from tax $this->assertEquals('522.5', $order->Total); $amounts = array(); foreach ($order->Modifiers()->sort('Sort') as $modifier) { $amounts[] = (string) $modifier->Amount; } $this->assertEquals(array('10', '104.5'), $amounts); OrderModifierTest_TestModifier::$value = 42; try { // Calculate will now fail! $order->calculate(); } catch (Exception $e) { } // reload order from DB $order = Order::get()->byID($order->ID); // Order Total should not have changed $this->assertEquals('522.5', $order->Total); $amounts = array(); foreach ($order->Modifiers()->sort('Sort') as $modifier) { $amounts[] = (string) $modifier->Amount; } $this->assertEquals(array('10', '104.5'), $amounts, 'Modifiers aren\'t allowed to change upon failure'); }
public function parameterFields() { $fields = new FieldList(); // Check if any order exist if (Order::get()->exists()) { $first_order = Order::get()->sort('Created ASC')->first(); $months = array('All'); $statuses = Order::config()->statuses; array_unshift($statuses, 'All'); for ($i = 1; $i <= 12; $i++) { $months[] = date("F", mktime(0, 0, 0, $i + 1, 0, 0)); } // Get the first order, then count down from current year to that $firstyear = new SS_Datetime('FirstDate'); $firstyear->setValue($first_order->Created); $years = array(); for ($i = date('Y'); $i >= $firstyear->Year(); $i--) { $years[$i] = $i; } //Result Limit $result_limit_options = array(0 => 'All', 50 => 50, 100 => 100, 200 => 200, 500 => 500); $fields->push(DropdownField::create('Filter_Month', 'Filter by month', $months)); $fields->push(DropdownField::create('Filter_Year', 'Filter by year', $years)); $fields->push(DropdownField::create('Filter_Status', 'Filter By Status', $statuses)); $fields->push(DropdownField::create("ResultsLimit", "Limit results to", $result_limit_options)); } return $fields; }
public function testOffsitePaymentWithGatewayCallback() { //set up cart $cart = ShoppingCart::singleton()->setCurrent($this->objFromFixture("Order", "cart"))->current(); //collect checkout details $cart->update(array('FirstName' => 'Foo', 'Surname' => 'Bar', 'Email' => '*****@*****.**')); $cart->write(); //pay for order with external gateway $processor = OrderProcessor::create($cart); $this->setMockHttpResponse('PaymentExpress/Mock/PxPayPurchaseSuccess.txt'); $response = $processor->makePayment("PaymentExpress_PxPay", array()); //gateway responds (in a different session) $oldsession = $this->mainSession; $this->mainSession = new TestSession(); ShoppingCart::singleton()->clear(); $this->setMockHttpResponse('PaymentExpress/Mock/PxPayCompletePurchaseSuccess.txt'); $this->getHttpRequest()->query->replace(array('result' => 'abc123')); $identifier = $response->getPayment()->Identifier; $response = $this->get("paymentendpoint/{$identifier}/complete"); //reload cart as new order $order = Order::get()->byId($cart->ID); $this->assertFalse($order->isCart(), "order is no longer in cart"); $this->assertTrue($order->isPaid(), "order is paid"); //bring back client session $this->mainSession = $oldsession; $response = $this->get("paymentendpoint/{$identifier}/complete"); $this->assertNull(Session::get("shoppingcartid"), "cart session id should be removed"); $this->assertNotEquals(404, $response->getStatusCode(), "We shouldn't get page not found"); $this->markTestIncomplete("Should assert other things"); }
public function Orders() { if ($this->Count == 0) { $this->Count = 10; } $orders = Order::get()->sort("Placed", "DESC")->exclude('Status', Config::inst()->get('DashboardRecentOrdersPanel', 'exclude_status'))->limit($this->Count); return $orders; }
public function quote() { $object = Order::get()->filter(array("ClassName" => $this->config()->estimate_class, "ID" => $this->request->param("ID")))->first(); if ($object && $object->AccessKey && $object->AccessKey == $this->request->param("OtherID")) { return $this->customise(array("SiteConfig" => SiteConfig::current_site_config(), "MetaTitle" => _t("Orders.QuoteTitle", "Quote"), "Object" => $object))->renderWith(array("OrderFront_quote", "Orders", "Page")); } else { return $this->httpError(404); } }
protected function placeOrder() { // ensure order is being reloaded from DB, to prevent dealing with stale data! /** @var Order $order */ $order = Order::get()->byID($this->owner->OrderID); if ($order && $order->exists()) { OrderProcessor::create($order)->placeOrder(); } }
function run($request) { $orders = Order::get()->where("\"Order\".\"Env\" = 'dev'"); if ($orders && $orders->exists()) { foreach ($orders as $order) { $order->delete(); $order->destroy(); } } }
/** * Get all orders for current member / session. * @return DataList of Orders */ public function allorders() { $filters = array('ID' => -1); if ($sessids = self::get_session_order_ids()) { $filters['ID'] = $sessids; } if ($memberid = Member::currentUserID()) { $filters['MemberID'] = $memberid; } return Order::get()->filterAny($filters)->filter("Status:not", Order::config()->hidden_status); }
/** * returns the order to use.... You can provide one * which basically just checks that it is a real order * @param Order | Int * @return Order */ protected function orderToUse($order = null) { if ($order && $order instanceof $order) { return $order; } if (intval($order)) { return Order::get()->byID(intval($order)); } else { return ShoppingCart::current_order(); } user_error("Can't find an order to use"); }
public function showUpdateForm($id) { if (!is_numeric($id)) { return; } $userId = User::getUserId(); $order = Order::get($id, $userId); if (count($order) < 1) { return; } $data = array('order' => $order[0]); return View::make('order.update', $data); }
/** * (non-PHPdoc) * @see CRUDPageAbstract::_getEndJs() */ protected function _getEndJs() { $applyToOptions = CreditNote::getApplyToTypes(); $js = parent::_getEndJs(); if (isset($_REQUEST['orderid']) && ($order = Order::get(trim($_REQUEST['orderid']))) instanceof Order) { $js .= "pageJs._order=" . json_encode($order->getJson()) . ";"; } $js .= "pageJs._applyToOptions=" . json_encode($applyToOptions) . ";"; $js .= "pageJs._bindSearchKey()"; $js .= ".setCallbackId('deactivateItems', '" . $this->deactivateItemBtn->getUniqueID() . "')"; $js .= ".init(true, " . $this->pageSize . ");"; return $js; }
/** * batch process orders */ public function migrateOrders() { $start = $count = 0; $batch = Order::get()->sort("Created", "ASC")->limit($start, self::$batch_size); while ($batch->exists()) { foreach ($batch as $order) { $this->migrate($order); echo ". "; $count++; } $start += self::$batch_size; $batch = $batch->limit($start, self::$batch_size); } echo "{$count} orders updated.\n<br/>"; }
public function parseOrder($Order_ID) { $transaction = Order::get()->filter(array('Order_ID' => $Order_ID))->First(); if ($transaction) { // grab response, parse as XML $orders = new SimpleXMLElement($transaction->Response); $this->parseOrderInfo($orders, $transaction); $this->parseOrderCustomer($orders, $transaction); // record transaction so user info can be accessed from parseOrderDetails() $transaction->write(); $this->parseOrderDetails($orders, $transaction); // record transaction as order $transaction->write(); } }
/** * @param SS_HTTPRequest $request * @return SS_HTTPResponse */ public function claim(SS_HTTPRequest $request) { /** @var Order $order */ $order = Order::get()->byID($request->param('ID')); $hash = $request->param('OtherID'); $realHash = FollowUpEmail::generate_hash($order); if (!$order || !$order->exists() || empty($hash) || $hash !== $realHash) { $this->httpError(404); } // Require a login if the order is attached to an account if ($order->MemberID && $order->MemberID != Member::currentUserID()) { return Security::permissionFailure($this->owner, _t('ShopEmail.NotYourOrder', 'You must log in to access this order.')); } // Otherwise if all is good, proceed to checkout ShoppingCart::singleton()->setCurrent($order); return $this->redirect(CheckoutPage::get()->first()->Link()); }
/** * (non-PHPdoc) * @see BPCPageAbstract::onLoad() */ public function onLoad($param) { parent::onLoad($param); if (!$this->isPostBack) { $this->order = Order::get($this->Request['orderId']); if (!$this->order instanceof Order) { die('Invalid Order!'); } if (isset($_REQUEST['pdf']) && intval($_REQUEST['pdf']) === 1) { $file = EntityToPDF::getPDF($this->order, 'docket'); header('Content-Type: application/pdf'); // The PDF source is in original.pdf readfile($file); die; } } }
/** * (non-PHPdoc) * @see BPCPageAbstract::_preGetEndJs() */ protected function _preGetEndJs() { parent::_preGetEndJs(); $order = $tech = $customer = null; if (isset($_REQUEST['customerId']) && !($customer = Customer::get(trim($_REQUEST['customerId']))) instanceof Customer) { die('Invalid Customer provided!'); } if (isset($_REQUEST['orderId']) && !($order = Order::get(trim($_REQUEST['orderId']))) instanceof Order) { die('Invalid Order provided!'); } if (isset($_REQUEST['techId']) && !($tech = UserAccount::get(trim($_REQUEST['techId']))) instanceof UserAccount) { die('Invalid Technician provided!'); } $statusIds = array(); if (isset($_REQUEST['statusIds']) && ($statusIds = trim($_REQUEST['statusIds'])) !== '') { $statusIds = array_map(create_function('$a', 'return intval(trim($a));'), explode(',', $statusIds)); } $allstatuses = isset($_REQUEST['allstatuses']) && intval(trim($_REQUEST['allstatuses'])) === 1; $preSetData = array('statuses' => array(), 'order' => $order instanceof Order ? $order->getJson() : array(), 'technician' => $tech instanceof UserAccount ? $tech->getJson() : array(), 'customer' => $customer instanceof Customer ? $customer->getJson() : array(), 'meId' => Core::getUser()->getId(), 'noDueDateStatusIds' => array()); $statuses = array(); foreach (TaskStatus::getAll() as $status) { $statuses[] = $statusJson = $status->getJson(); if (($noDueDateChecking = in_array(intval($status->getId()), TaskStatus::getClosedStatusIds())) === true) { $preSetData['noDueDateStatusIds'][] = $status->getId(); } if (count($statusIds) > 0) { if (in_array(intval($status->getId()), $statusIds)) { $preSetData['statuses'][] = $statusJson; } } else { if ($allstatuses === false && !$noDueDateChecking) { $preSetData['statuses'][] = $statusJson; } } } if (count($statusIds) > 0 && count($preSetData['statuses']) === 0) { die('Invalide Task Status provided.'); } $js = "pageJs"; $js .= ".setOpenInFancyBox(" . (isset($_REQUEST['blanklayout']) && intval(trim($_REQUEST['blanklayout'])) === 1 && (isset($_REQUEST['nosearch']) && intval($_REQUEST['nosearch']) === 1) ? 'false' : 'true') . ")"; $js .= ".setStatuses(" . json_encode($statuses) . ")"; $js .= ".setPreSetData(" . json_encode($preSetData) . ")"; $js .= ";"; return $js; }
public function run($request) { if (!$this->config()->get('delete_after_mins')) { throw new LogicException('No valid time specified in "delete_after_mins"'); } $start = 0; $count = 0; $time = date('Y-m-d H:i:s', SS_Datetime::now()->Format('U') - $this->config()->get('delete_after_mins') * 60); $this->log("Deleting all orders since " . $time); $orders = Order::get()->filter(array('Status' => 'Cart', 'LastEdited:LessThan' => $time)); foreach ($orders as $order) { $this->log(sprintf('Deleting order #%s (Reference: %s)', $order->ID, $order->Reference)); $order->delete(); $order->destroy(); $count++; } $this->log("{$count} old carts removed."); }
/** *@return Integer - number of carts destroyed **/ public function run($request) { if (!Director::isDev() || Director::isLive()) { DB::alteration_message("you can only run this in dev mode!"); } else { if (!isset($_REQUEST["i-am-sure"])) { $_REQUEST["i-am-sure"] = ""; } if ("yes" != $_REQUEST["i-am-sure"]) { die("<h1>ARE YOU SURE?</h1><br /><br /><br /> please add the 'i-am-sure' get variable to your request and set it to 'yes' ... e.g. <br />http://www.mysite.com/dev/ecommerce/ecommercetaskdeleteallorders/?i-am-sure=yes"); } $oldCarts = Order::get(); $count = 0; if ($oldCarts->count()) { if ($this->verbose) { $totalToDeleteSQLObject = DB::query("SELECT COUNT(*) FROM \"Order\""); $totalToDelete = $totalToDeleteSQLObject->value(); DB::alteration_message("<h2>Total number of orders: " . $totalToDelete . " .... now deleting: </h2>", "deleted"); } foreach ($oldCarts as $oldCart) { $count++; if ($this->verbose) { DB::alteration_message("{$count} ... deleting abandonned order #" . $oldCart->ID, "deleted"); } $oldCart->delete(); $oldCart->destroy(); } } else { if ($this->verbose) { $count = DB::query("SELECT COUNT(\"ID\") FROM \"Order\"")->value(); DB::alteration_message("There are no abandonned orders. There are {$count} 'live' Orders.", "created"); } } $countCheck = DB::query("Select COUNT(ID) FROM \"Order\"")->value(); if ($countCheck) { DB::alteration_message("ERROR: in testing <i>Orders</i> it appears there are " . $countCheck . " records left.", "deleted"); } else { DB::alteration_message("PASS: in testing <i>Orders</i> there seem to be no records left.", "created"); } $this->cleanupUnlinkedOrderObjects(); $this->doubleCheckModifiersAndItems(); return $count; } }
/** * Process the callback data from the payment provider */ public function callback($request) { if (Director::isDev()) { $secret_key = StripePayment::config()->test_secret_key; $publish_key = StripePayment::config()->test_publish_key; } else { $secret_key = StripePayment::config()->live_secret_key; $publish_key = StripePayment::config()->live_publish_key; } Stripe::setApiKey($secret_key); $site = SiteConfig::current_site_config(); $order = $this->getOrderData(); $cart = ShoppingCart::get(); $this->extend('onBeforeCallback'); $error_url = Controller::join_links(Director::absoluteBaseURL(), Payment_Controller::config()->url_segment, 'complete', 'error'); $data = $this->request->postVars(); $status = "error"; // Get the credit card details submitted by the form $token = $data['stripeToken']; $order_no = Session::get("StripePayment.OrderNumber"); $order = Estimate::get()->filter("OrderNumber", $order_no)->first(); if ($order_no && $order) { // Create the charge on Stripe's servers - this will charge // the user's card try { $success_url = Controller::join_links(Director::absoluteBaseURL(), Payment_Controller::config()->url_segment, 'complete', $order_no); $charge = StripeCharge::create(array("amount" => round($order->Total->Value * 100), "currency" => strtolower(Checkout::config()->currency_code), "source" => $token, "metadata" => array("Order" => $order_no))); $order->convertToOrder(); $order->write(); $order = Order::get()->byID($order->ID); $order->Status = "paid"; $order->PaymentProvider = "Stripe"; $order->PaymentNo = $charge->id; $order->write(); return $this->redirect($success_url); } catch (Exception $e) { $order->Status = "failed"; $order->write(); return $this->redirect($error_url); } } else { return $this->redirect($error_url); } }
function run($request) { //reset time limit set_time_limit(1200); //file data $now = Date("d-m-Y-H-i"); $fileName = "export-{$now}.csv"; //data object variables $orderStatusSubmissionLog = EcommerceConfig::get("OrderStatusLog", "order_status_log_class_used_for_submitting_order"); $fileData = ""; $offset = 0; $count = 50; while ($orders = Order::get()->sort("\"Order\".\"ID\" ASC")->innerJoin("OrderStatusLog", "\"Order\".\"ID\" = \"OrderStatusLog\".\"OrderID\"")->innerJoin($orderStatusSubmissionLog, "\"{$orderStatusSubmissionLog}\".\"ID\" = \"OrderStatusLog\".\"ID\"")->leftJoin("Member", "\"Member\".\"ID\" = \"Order\".\"MemberID\"")->limit($count, $offset) && ($ordersCount = $orders->count())) { $offset = $offset + $count; foreach ($orders as $order) { if ($order->IsSubmitted()) { $memberIsOK = false; if (!$order->MemberID) { $memberIsOK = true; } elseif (!$order->Member()) { $memberIsOK = true; } elseif ($member = $order->Member()) { $memberIsOK = true; if ($member->IsShopAdmin()) { $memberIsOK = false; } } if ($memberIsOK) { $items = OrderItem::get()->filter(array("OrderID" => $order->ID)); if ($items && $items->count()) { $fileData .= $this->generateExportFileData($order->getOrderEmail(), $order->SubmissionLog()->Created, $items); } } } } unset($orders); } if ($fileData) { SS_HTTPRequest::send_file($fileData, $fileName, "text/csv"); } else { user_error("No records found", E_USER_ERROR); } }
/** * (non-PHPdoc) * @see BPCPageAbstract::_preGetEndJs() */ protected function _preGetEndJs() { // parent::_preGetEndJs(); $order = $task = $customer = null; if (isset($_REQUEST['customerId']) && !($customer = Customer::get(trim($_REQUEST['customerId']))) instanceof Customer) { die('Invalid Customer provided!'); } if (isset($_REQUEST['taskId']) && !($task = Task::get(trim($_REQUEST['taskId']))) instanceof Task) { die('Invalid Order provided!'); } if (isset($_REQUEST['orderId']) && !($order = Order::get(trim($_REQUEST['orderId']))) instanceof Order) { die('Invalid Order provided!'); } $preSetData = array('task' => $task instanceof Task ? $task->getJson() : array(), 'order' => $order instanceof Order ? $order->getJson() : array(), 'customer' => $customer instanceof Customer ? $customer->getJson() : array()); $js = "pageJs"; $js .= ".setOpenInFancyBox(" . (isset($_REQUEST['blanklayout']) && intval(trim($_REQUEST['blanklayout'])) === 1 && (isset($_REQUEST['nosearch']) && intval($_REQUEST['nosearch']) === 1) ? 'false' : 'true') . ")"; $js .= ".setPreSetData(" . json_encode($preSetData) . ")"; $js .= ";"; return $js; }
/** * @param SS_HTTPRequest $request */ public function run($request) { $email = $request->remaining(); $params = $request->allParams(); $url = Director::absoluteURL("dev/{$params['Action']}/{$params['TaskName']}", true); echo '<h2>Choose Email</h2>'; echo '<ul>'; foreach ($this->previewableEmails as $key => $method) { echo '<li><a href="' . $url . '/' . $method . '">' . $method . '</a></li>'; } echo '</ul><hr>'; if ($email && in_array($email, $this->previewableEmails)) { $order = Order::get()->first(); $notifier = OrderEmailNotifier::create($order)->setDebugMode(true); $method = "send{$email}"; echo $notifier->{$method}(); } else { } //this is a little hardcore way of ending the party, //but as it's only used for styling, it works for now die; }
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(); }
/** * Retrieve and process order data from the request */ public function callback() { $data = $this->request->postVars(); $success_url = Controller::join_links(Director::absoluteBaseURL(), Payment_Controller::config()->url_segment, 'complete'); $error_url = Controller::join_links(Director::absoluteBaseURL(), Payment_Controller::config()->url_segment, 'complete', 'error'); $vars = array("SiteConfig" => SiteConfig::current_site_config(), "RedirectURL" => $error_url); // Check if CallBack data exists and install id matches the saved ID if (isset($data) && (isset($data['instId']) && isset($data['cartId']) && isset($data['transStatus']) && isset($data["callbackPW"])) && $this->payment_gateway->InstallID == $data['instId'] && $this->payment_gateway->ResponsePassword == $data["callbackPW"]) { $order = Order::get()->filter('OrderNumber', $data['cartId'])->first(); $order_status = $data['transStatus']; if ($order) { if ($order_status == 'Y') { $order->Status = 'paid'; $vars["RedirectURL"] = $success_url; } else { $order->Status = 'failed'; } // Store all the data sent from the gateway in a json $order->GatewayData = json_encode($data); $order->write(); } } return $this->renderWith(array("Payment_WorldPay"), $vars); }