API Docs for: WebTemplate API v2.0
Show:

File: /data/www/webtemplate/wtv2/codedoc/wtOrder.php

<?php

/**
 *  WebTemplate Core
 *
 *  @version 2.0
 *  @module WebTemplate Core
 */

$GLOBALS["WTORDERNOTIFICATIONS"] = Array();
$GLOBALS["WTORDERNOTIFICATIONS"]["payment confirmation email"] = Array("path" => "Orders/Payment Confirmation Email", "name" => "Order Payment Received Email (Credit Card or Account)", "description" => "This message is emailed to the customer after they pay for an order by credit card or when an account order is set to 'paid' in the office", "tags" => "[Order Number] = Order number, [Order Summary] = Summary of order, [Payment Method] = Payment method, [First Name] = Customer's First Name, [Last Name] = Customer's Last Name");
$GLOBALS["WTORDERNOTIFICATIONS"]["account payment confirmation email"] = Array("path" => "Orders/Payment Options/Account/Account Order Paid Email", "name" => "Order Payment Received Email (Account)", "description" => "This message is emailed to the customer after an account order is set to 'paid' in the office", "tags" => "[Order Number] = Order number, [Order Summary] = Summary of order, [Payment Method] = Payment method, [First Name] = Customer's First Name, [Last Name] = Customer's Last Name");

$GLOBALS["WTORDERNOTIFICATIONS"]["account order received"] = Array("path" => "Orders/Payment Options/Account/Account Order Received", "name" => "Account Order Received Message", "description" => "This message is displayed to the customer after they submit an account order", "tags" => "[Order Number] = Order number, [Order Summary] = Summary of order, [First Name] = Customer's First Name, [Last Name] = Customer's Last Name");

$GLOBALS["WTORDERNOTIFICATIONS"]["account order received email"] = Array("path" => "Orders/Payment Options/Account/Account Order Received Email", "name" => "Account Order Received Email", "description" => "This message is emailed to the customer after they submit an account order", "tags" => "[Order Number] = Order number, [Order Summary] = Summary of order, [First Name] = Customer's First Name, [Last Name] = Customer's Last Name");
$GLOBALS["WTORDERNOTIFICATIONS"]["credit card order successful"] = Array("path" => "Orders/Payment Options/Credit Card/Credit Card Order Successful", "name" => "Credit Card Order Successful Message", "description" => "This message is displayed to the customer after a successful credit card payment", "tags" => "[Order Number] = Order number, [Order Summary] = Summary of order, [First Name] = Customer's First Name, [Last Name] = Customer's Last Name");

$GLOBALS["WTORDERNOTIFICATIONS"]["quote request instructions"] = Array("path" => "Orders/Payment Options/Quote Request/Quote Request Instructions", "name" => "Quote Request Instructions", "description" => "This message is displayed to the customer when they are submitting a quote request", "tags" => "");
$GLOBALS["WTORDERNOTIFICATIONS"]["quote request received"] = Array("path" => "Orders/Payment Options/Quote Request/Quote Request Received", "name" => "Quote Request Received Message", "description" => "This message is displayed to the customer after they submit a quote request", "tags" => "[Order Number] = Order number, [Order Summary] = Summary of order, [First Name] = Customer's First Name, [Last Name] = Customer's Last Name");
$GLOBALS["WTORDERNOTIFICATIONS"]["quote request received email"] = Array("path" => "Orders/Payment Options/Quote Request/Quote Request Received Email", "name" => "Quote Request Received Email", "description" => "This message is emailed to the customer after they submit a quote request", "tags" => "[Order Number] = Order number, [Order Summary] = Summary of order, [First Name] = Customer's First Name, [Last Name] = Customer's Last Name");
$GLOBALS["WTORDERNOTIFICATIONS"]["quote payment required email"] = Array("path" => "Orders/Payment Options/Quote Request/Quote Payment Required Email", "name" => "Quote Payment Required Email", "description" => "This message is emailed to the customer when their quote requires payment", "tags" => "[Order Number] = Order number, [Order Summary] = Summary of order, [First Name] = Customer's First Name, [Last Name] = Customer's Last Name");
$GLOBALS["WTORDERNOTIFICATIONS"]["terms and conditions"] = Array("path" => "Orders/Terms and Conditions", "name" => "Terms and Conditions", "description" => "The terms and conditions shown on the billing details page");


/**
 *  The class representing wtOrder Nodes
 *
 *  @class WTOrder
 *  @extends WTNode
 */

class WTOrder extends WTNode {

  function setAttributes($attributes)
  {
    $paymentMethod = $this->getAttribute("Payment Method");
    $oldPaid = $this->getAttribute("Paid");
    parent::setAttributes($attributes);
    $accountMethodName = WTConfig::get("Orders/Payment Options/Account/Account Method Name");
    if($accountMethodName == "") {
      $accountMethodName = "Account";
    }


    if( ($attributes["Paid"] == "Yes" || $attributes["Paid ID"] == 1) && $oldPaid == "No") {
      $this->paid();
    }
    if( ($attributes["Paid"] == "Yes" || $attributes["Paid ID"] == 1) && ($paymentMethod == $accountMethodName || $paymentMethod == "BPAY") && $oldPaid == "No") {
      $this->sendEmail();

    }

  }


  /**
   *  This function is called when an order is paid<br/>
   *  It may be overridden so custom processing can occur when an order is paid
   *
   *  @method paid
   */
  function paid() {
    return true;
  }


  /**
   *  This function is called when an order is submitted<br/>
   *  It may be overridden so custom processing can occur when an order is submitted
   *
   *  @method orderSubmitted
   */
  function orderSubmitted() {
    return true;
  }

  /**
   *  Add an item to an order
   *
   *  @method addItem
   *  @param {Array} attributes An associative array. The keys are the attributes of the wtOrderItem Type
   */
  function addItem($attributes) {
    $orderItem = $this->createChild("wtOrderItem", $attributes);
    $this->calculateTotal();
    return $orderItem;
  }

  /**
   *  Delete all items in an order
   *
   *  @method deleteItems
   *
   */
  function deleteItems() {
    $results = Array();
    $q["Node Type"] = "wtOrderItem";
    $q["Path"] = $this->m_guid . "/*";
    $q["Results Array"] = &$results;
    $GLOBALS["WT"]->query($q);
    foreach($results as $result) {
      $node = $GLOBALS["WT"]->getNode($result["__guid"]);
      $node->deleteNode();
    }
  }


  /**
   *  calcualte the total for an orders and set the "Order Total" attribute of the order
   *
   *  @method calculateTotal
   *  @return {float} The total for the order
   */  
  function calculateTotal() {
    $total = $this->getTotal();
    $this->setAttributes(Array("Order Total" => $total));
    return $total;
  }

  /**
   *  Return the total number of items in the order (adding all quantities)
   *
   *  @method getTotalItems
   *  @return {int} The total number of items
   */
  function getTotalItems()
  {
    $q["Path"] = $this->m_guid . "/*";
    $q["Node Type"] = "wtOrderItem";
    $q["Select"] = 'SUM(Quantity)';
    return  $GLOBALS["WT"]->query($q, "singleValueCallback");

  }


  /**
   *  Get the total for the order
   *
   *  @method getTotal
   *  @param {boolean} [includeFreight=true] Include freight in the total
   *  @param {boolean} [includeDiscount=true] Include the discount in the total
   *  @param {boolean] [subtractGST=false] Subtract GST from the total
   *
   */
  function getTotal($includeFreight = true, $includeDiscount = true, $subtractGST = false)
  {
    $q["Path"] = $this->m_guid . "/*";
    $q["Node Type"] = "wtOrderItem";
    $q["Select"] = 'SUM(Price)';
    $subtotal = $GLOBALS["WT"]->query($q, "singleValueCallback");

    if($includeFreight) {
      $freight = $this->getAttribute("Freight");
      $subtotal += $freight;
    }

    if($includeDiscount) {
      $discount = $this->getAttribute("Discount");
      $subtotal -= $discount;
    }

    if($subtractGST) {
      $gst = $this->getAttribute("GST");
      if($gst) {
        $subtotal -= $gst;
      }
    }
/*
    $user = $GLOBALS["WT"]->getCurrentUser();
    if (!$inDiscount && $user->m_name !== '__public') {
       $subtotal = $subtotal - $this->getDiscount();
    }
*/
    return $subtotal;
  }

/*
  function getDiscount() {
   $subtotal=0;
   $user = $GLOBALS["WT"]->getCurrentUser();
   if ($user->m_name !== '__public') {
   $user = $GLOBALS["WT"]->getCurrentUser();
   $use = $GLOBALS["WT"]->getNode($user->m_guid);
   $memberGroups = $use->getAttribute('Member Groups');
   $groups = explode(',', $memberGroups);
   for ($i=0;$i<count($groups);$i++) {
   $grp = $GLOBALS["WT"]->getNode($groups[$i]);
    if ($grp->getAttribute('Discount (%)') > 0) {
      $discount = $grp->getAttribute('Discount (%)');
      break;
     }
   }

   $discount = $user->getDiscount();
   if($discount > 0) {
    $total = $this->getTotal(false,true);
    $subtotal = $total * $discount/100;
   }
   }
   return $subtotal;
  }
*/
  function getCustomerDetails() {
  }

  function activateDownloads() {
    $q = Array();
    $results = Array();
    $q["Node Type"] = "wtOrderItem";
    $q["Path"] = $this->m_guid . "/*";
    $q["Results Array"] = &$results;
    $GLOBALS["WT"]->query($q);


    foreach($results as $result) {
      if(array_key_exists("Product ID", $result) && $result["Product ID"]) {

        $product = $GLOBALS["WT"]->getNode($result["Product ID"]);


        if($product->getAttribute("Product Type") == "Image") {

          $downloadKey = md5(uniqid(rand(), true));
          $imageGuid = $product->getAttribute("Image");
          $image = $GLOBALS["WT"]->getNode($imageGuid);
          $filename = $image->getAttribute("File Name");
          $orderItem = $GLOBALS["WT"]->getNode($result["__guid"]);
          $orderItem->setAttributes(Array("Key" => $downloadKey, "Key Date" => date("Y-m-d")));
          $link = WTConfig::get("Site Details/Site URL") . "__files/purchase/$downloadKey/" . $orderItem->m_guid . "/$filename";
          $description = 'Please use the link below to download your file:<br><a href="' . $link . '">' . $link . '</a>';


          $orderItem->setAttributes(Array("Description" => $description));
        }
      }
    }
  }

  function getEmailCopyToAddress() {
    return $GLOBALS["WT"]->getWTValue("wt.settings.Orders.Send Email Copy To");
  }


  /**
   *  Send the email related to the order and its status
   *
   *  @method sendEmail
   */

  function sendEmail() {

    $sendEmailAsName = $GLOBALS["WT"]->getWTValue("wt.settings.Orders.Send Email As Name");
    $sendEmailAsAddress = $GLOBALS["WT"]->getWTValue("wt.settings.Orders.Send Email As Address");
//    $sendEmailCopyTo = $GLOBALS["WT"]->getWTValue("wt.settings.Orders.Send Email Copy To");
    $sendEmailCopyTo = $this->getEmailCopyToAddress();

    $paymentMethod = $this->getAttribute("Payment Method");
    $paid = $this->getAttribute("Paid");
    $status = $this->getAttribute("Status");

    $accountMethodName = WTConfig::get("Orders/Payment Options/Account/Account Method Name");
    if($accountMethodName == "") {
      $accountMethodName = "Account";
    }


    if(($paymentMethod == "Quote Request") && $paid == "No") {
      $subject = WTOrder::getNotificationSubject("quote request received email");
      $message = WTOrder::getNotificationMessage("quote request received email");

    } else if(($paymentMethod == $accountMethodName) && $paid == "No") {
      $subject = WTOrder::getNotificationSubject("account order received email");
      $message = WTOrder::getNotificationMessage("account order received email");
    } else if(($paymentMethod == "Credit Card" || $paymentMethod == "PayPal") && $status == "Requires Payment") {
      $subject = WTOrder::getNotificationSubject("quote payment required email");
      $message = WTOrder::getNotificationMessage("quote payment required email");
    } else if (($paymentMethod == $accountMethodName) && $paid == "Yes") {
      $subject = WTOrder::getNotificationSubject("account payment confirmation email");
      $message = WTOrder::getNotificationMessage("account payment confirmation email");


      if($subject == "" && $message == "") {
        $subject = WTOrder::getNotificationSubject("payment confirmation email");
        $message = WTOrder::getNotificationMessage("payment confirmation email");
      }

      if($subject == "" && $message == "") {
	$subject = WTOrder::getNotificationSubject("credit card order successful");
	$message = WTOrder::getNotificationMessage("credit card order successful");
      }
      //    } else if($paymentMethod == "Credit Card" || ( ($paymentMethod == $accountMethodName) && $paid == "Yes") || $paymentMethod == "PayPal" ) {
    } else if($paymentMethod == "Credit Card" || $paymentMethod == "PayPal" ) {
      $subject = WTOrder::getNotificationSubject("credit card order successful");
      $message = WTOrder::getNotificationMessage("credit card order successful");


      if($subject == "" && $message == "") {
        $subject = WTOrder::getNotificationSubject("payment confirmation email");
        $message = WTOrder::getNotificationMessage("payment confirmation email");

      }
    }

    if($subject == "" && $message == "") {
      $subject = $GLOBALS["WT"]->getWTValue("wt.settings.Orders.Confirmation Email Subject");
      $message = $GLOBALS["WT"]->getWTValue("wt.settings.Orders.Confirmation Email Message");
    }



    $data = Array();
    $data["Order Number"] = $this->getAttribute("Order Number");
    $data["Order Summary"] = $this->render(Array("Inline Styles" => "yes"));

    $form = $GLOBALS["WT"]->getNode("/Forms/Order Billing Form");
    if(!$form) {
      $form = $GLOBALS["WT"]->getNode("/Forms/Order Address");
    }

    $billing = $GLOBALS["WT"]->getNode($this->m_guid . "/Billing Address");
    $firstNameField = $form->getFieldName("First Name");
    $data["First Name"] = $billing->getAttribute($firstNameField);
    $lastNameField = $form->getFieldName("Last Name");
    $data["Last Name"] = $billing->getAttribute($lastNameField);

    $customerEmailAddress = trim($this->getAttribute("Customer Email Address"));

    foreach($data as $key => $value) {
      $subject = str_replace("[$key]", $value, $subject);
      $message = str_replace("[$key]", $value, $message);
    }

    $templateNode = $GLOBALS["WT"]->getNode("/Templates/Emails/General");
    if($templateNode) {
      $templateData = Array("Content" => $message);
      $message = $templateNode->evaluate($templateData);
    } else {
      $message = '<html><head></head><body>' . $message . '</body></html>';
    }




    $wtMail = new WTMail();
    $wtMail->setTo($customerEmailAddress);
    $wtMail->setFrom($sendEmailAsAddress, $sendEmailAsName);
    $wtMail->setReplyTo($sendEMailAsAddress);
    $wtMail->setContent($subject, $message, true);
    $wtMail->send();


    $wtMail->setTo($sendEmailCopyTo);
    $wtMail->send();

  }

  /**
   *  Return a HTML representation of the order
   *
   *  @method render
   *  @return {String} A HTML version of the order
   */

  function render($args = Array())
  {
    $inlineStyles = false;
    if(array_key_exists("Inline Styles", $args) && $args["Inline Styles"] == "yes") {
      $inlineStyles = true;
    }
    $templateData = Array();
    $tid = $GLOBALS["WT"]->getRequestValue("tid");
    if($tid != '') {
      $transaction = $GLOBALS["WT"]->getNode($tid);
      if(!array_key_exists("Inline Styles", $args) || $args["Inline Styles"] != "yes") {
        $templateData["Transaction Error"] = $transaction->getAttribute("Description");
      }

    }

//    $summaryTemplate = WTTemplate::load($GLOBALS["WTDIRECTORY"] . "templates/cart/orderSummary.wt");
    $summaryItemTemplate = WTTemplate::load($GLOBALS["WTDIRECTORY"] . "templates/cart/orderSummaryItem.wt");

    $results = Array();
    $q = Array();
    $q["Path"] = $this->m_guid . "/*";
    $q["Node Type"] = "wtOrderItem";
//    $q["Template Source"] = $summaryItemTemplate;
    $q["Results Array"] = &$results;

    $templateData["Order Items"] = '';
    $GLOBALS["WT"]->query($q);
    foreach($results as $key => $data) {
      if($inlineStyles) {
        $data["Order Summary Table"] = 'style="border-collapse: collapse; border: 1px solid #aaa"';
        $data["Order Summary Heading"] = 'style="border: 1px solid #aaa; padding: 4px; text-align: left"';
        $data["Order Summary Cell"] = 'style="border: 1px solid #aaa; padding: 4px;"';
      }


      $templateData["Order Items"] .= WTTemplate::compileAndEvaluate($summaryItemTemplate, $data);
    }

    $templateData["__guid"] = $this->m_guid;
    $templateData["Subtotal"] = $this->getTotal(false);
    $templateData["Freight"] = $this->getAttribute("Freight");
    $templateData["Freight Carrier"] = $this->getAttribute("Freight Carrier");
    $templateData["GST"] = $this->getAttribute("GST");
    $templateData["Payment Method"] = $this->getAttribute("Payment Method");
    $templateData["Card Type"] = $this->getAttribute("Card Type");

    $user = $GLOBALS["WT"]->getCurrentUser();
/*
    if ($user->m_name !== '__public') {
     $templateData['Discount'] = $this->getDiscount();
    }
*/
     $templateData["Discount"] = $this->getAttribute("Discount");
     $templateData["Total"] = $this->getTotal(true, true, true);

    $addressstyles = Array("style" => 'class="orderaddress"');
    if($inlineStyles) {
      $templateData["Order Summary Table"] = 'style="border-collapse: collapse; border: 1px solid #aaa"';
      $templateData["Order Summary Heading"] = 'style="border: 1px solid #aaa; padding: 4px; text-align: left"';
      $templateData["Order Summary Cell"] = 'style="border: 1px solid #aaa; padding: 4px;"';

      $addressstyles["style"] = 'style="border-collapse: collapse; border: 1px solid #aaa"';
      $addressstyles["headingstyle"] = 'style="border: 1px solid #aaa; padding: 4px; text-align: left"';
      $addressstyles["cellstyle"] = 'style="border: 1px solid #aaa; padding: 4px;"';

    }


    $shippingAddress = $GLOBALS["WT"]->getNode($this->m_guid . "/Shipping Address");
    $shippingForm = $GLOBALS["WT"]->getNode("/Forms/Order Shipping Form");
    if(!$shippingForm) {
      $shippingForm = $GLOBALS["WT"]->getNode("/Forms/Order Address");
    }
    if($shippingAddress) {
      $templateData["Shipping Address"] = $shippingForm->render(Array("static" => "yes", "nfolabels" => "yes"), $shippingAddress->getAttributes());
    }


    $deliveryAddress = $GLOBALS["WT"]->getNode($this->m_guid . "/Delivery Address");
    $deliveryForm = $GLOBALS["WT"]->getNode("/Forms/Order Delivery Form");
    if(!$deliveryForm) {
      $deliveryForm = $GLOBALS["WT"]->getNode("/Forms/Order Address");
    }
    if($deliveryAddress) {
      $addressstyles["rowidprefix"] = "deliveryrow";
      $templateData["Delivery Address"] = $deliveryForm->renderStatic($deliveryAddress->getAttributes(), $addressstyles);
//      $templateData["Delivery Address"] = $deliveryForm->render(Array("static" => "yes", "nfolabels" => "yes"), $deliveryAddress->getAttributes());
    }



    $shippingInstructions = $GLOBALS["WT"]->getNode($this->m_guid . "/Shipping Instructions");

    if(!$shippingInstructions) {
    $shippingInstructions = $GLOBALS["WT"]->getNode($this->m_guid . "/Delivery Instructions");

    }
    $shippingInstructionsForm = $GLOBALS["WT"]->getNode("/Forms/Order Shipping Instructions");

    if(!$shippingInstructionsForm) {
      $shippingInstructionsForm = $GLOBALS["WT"]->getNode("/Forms/Order Delivery Instructions");
    }
    if($shippingInstructions != NULL && $shippingInstructionsForm != NULL) {
      $templateData["Shipping Instructions"] = $shippingInstructionsForm->render(Array("static" => "yes"), $shippingInstructions->getAttributes());
      $templateData["Delivery Instructions"] = $shippingInstructionsForm->renderStatic($shippingInstructions->getAttributes(), $addressstyles);
    }



    $billingAddress = $GLOBALS["WT"]->getNode($this->m_guid . "/Billing Address");

    if($billingAddress) {
      $billingForm = $GLOBALS["WT"]->getNode("/Forms/Order Billing Form");
      if(!$billingForm) {
        $billingForm = $GLOBALS["WT"]->getNode("/Forms/Order Address");
      }
      $addressstyles["rowidprefix"] = "billingrow";
      $templateData["Billing Address"] = $billingForm->renderStatic($billingAddress->getAttributes(), $addressstyles);
//      $templateData["Billing Address"] = $billingForm->render(Array("static" => "yes", "nolfabels" => "yes"), $billingAddress->getAttributes());

      if(array_key_exists("Show Change Links", $args)) {
        $templateData["Show Change Links"] = $args["Show Change Links"];
      }
    }


    $page = $GLOBALS["WT"]->setURIParameter($page, "wtStep", "pay");

    $summaryTemplateNode = $GLOBALS["WT"]->getNode("/Templates/Cart Layouts/Summary");

    if($summaryTemplateNode) {
      return $summaryTemplateNode->evaluate($templateData);
    } else {

      $summaryTemplate = WTTemplate::load($GLOBALS["WTDIRECTORY"] . "templates/cart/orderSummary.wt");

      return WTTemplate::compileAndEvaluate($summaryTemplate, $templateData);
    }
  }

  static function setNotification($type, $subject, $message)
  {
    $subjectPath = $GLOBALS["WTORDERNOTIFICATIONS"][$type]["path"] . " Subject";
    $messagePath = $GLOBALS["WTORDERNOTIFICATIONS"][$type]["path"] . " Message";

    WTConfig::set($subjectPath, $subject);
    WTConfig::set($messagePath, $message);
  }

  static function getNotificationInfo($type, $element) {
    $info = $GLOBALS["WTORDERNOTIFICATIONS"][$type][$element];
    if( ($type == "account order received" || $type == "account order received email") && $element == "name" ) {
      $accountMethodName = WTConfig::get("Orders/Payment Options/Account/Account Method Name");
      if($accountMethodName != "") {
        $info = str_replace("Account", $accountMethodName, $info);
      }
    }
    if( ($type == "account order received" || $type == "account order received email") && $element == "description" ) {
      $accountMethodName = WTConfig::get("Orders/Payment Options/Account/Account Method Name");
      if($accountMethodName != "") {
        $info = str_replace("account", strtolower($accountMethodName), $info);
      }
    }

    return $info;
  }

  static function getNotificationSubject($type)
  {
    $subjectPath = $GLOBALS["WTORDERNOTIFICATIONS"][$type]["path"] . " Subject";
    return WTConfig::get($subjectPath);
  }

  static function getNotificationMessage($type)
  {
    $messagePath = $GLOBALS["WTORDERNOTIFICATIONS"][$type]["path"] . " Message";
    return WTConfig::get($messagePath);
  }


}

?>