<?php

// TODO: Uncomment
include "access.php";
include_once "../includes/SystemConfiguration.class.php";
global $systemConfiguration;
global $logger;
// If we have id, then we are trying to delete
if (isset($_GET['id']) && is_numeric($_GET['id'])) {
    $id = $_GET['id'];
    PromoCode::delete($id);
}
header("Location: promo_codes_list.php");
 public function syncPromoCode()
 {
     $config = $this->getConfigValues(get_class($this));
     $strPromoCode = $config['promocode'];
     //Entered promo code
     $objPromoCode = PromoCode::LoadByShipping(get_class($this));
     if (!$objPromoCode) {
         //If we're this far without an object, create one
         $objPromoCode = new PromoCode();
         $objPromoCode->lscodes = "shipping:,";
         $objPromoCode->exception = 0;
         $objPromoCode->enabled = 1;
         $objPromoCode->module = get_class($this);
     }
     //Sync any fields with the promo code table
     if (strlen($strPromoCode) == 0) {
         $strPromoCode = get_class($this) . ":";
     }
     $objPromoCode->code = $strPromoCode;
     $objPromoCode->valid_from = isset($config['startdate']) && !empty($config['startdate']) ? $config['startdate'] : null;
     $objPromoCode->valid_until = isset($config['enddate']) && !empty($config['enddate']) ? $config['enddate'] : null;
     $objPromoCode->amount = 0;
     $objPromoCode->type = PromoCodeType::Percent;
     //Needs to be 0% so UpdatePromoCode() returns valid test
     $objPromoCode->threshold = $config['rate'] == "" ? "0" : $config['rate'];
     if ($config['qty_remaining'] == '') {
         $objPromoCode->qty_remaining = -1;
     } else {
         $objPromoCode->qty_remaining = $config['qty_remaining'];
     }
     $objPromoCode->save();
 }
 public function testGeneratPromoCode()
 {
     $pc = new PromoCode();
     $pc->generate(10);
     $this->assertSame(10, count($pc), 'Not matching count of codes');
     foreach ($pc->getCodes() as $code) {
         $this->assertSame(10, strlen($code), 'Not matching code length');
     }
 }
 public function actionUpdateRestrictions()
 {
     $blnShipping = false;
     $errormsg = Yii::t('admin', "An error occurred saving Promo Code restrictions. Please check your System Log.");
     $arrRPost = Yii::app()->getRequest()->getPost('RestrictionForm');
     $arrSPost = Yii::app()->getRequest()->getPost('ShippingRestrictionForm');
     if (isset($arrRPost)) {
         $arrPost = $arrRPost;
     }
     if (isset($arrSPost)) {
         $arrPost = $arrSPost;
         $blnShipping = true;
     }
     if (isset($arrPost['id'])) {
         $id = $arrPost['id'];
         $objPromoCode = PromoCode::model()->findByPk($id);
         if ($objPromoCode instanceof PromoCode) {
             $lscodes = '';
             unset($arrPost['id']);
             $arrSections = array('category:' => 'categories', 'family:' => 'families', 'keyword:' => 'keywords', 'class:' => 'classes', '' => 'codes');
             foreach ($arrSections as $key => $arrSection) {
                 if (isset($arrPost[$arrSection])) {
                     foreach ($arrPost[$arrSection] as $sectionValue) {
                         $lscodes .= $key . $sectionValue . ",";
                     }
                     unset($arrPost[$arrSection]);
                 }
             }
             //Since we're using our Promo Code restriction structure for general shipping restrictions...
             if ($blnShipping && $objPromoCode->module != "freeshipping") {
                 if (strlen($lscodes) > 0) {
                     $objPromoCode->enabled = 1;
                 } else {
                     $objPromoCode->enabled = 0;
                 }
             }
             if (strlen($lscodes) > 0) {
                 $lscodes = substr($lscodes, 0, -1);
             } else {
                 $arrPost['exception'] = 0;
             }
             $arrPost['lscodes'] = $blnShipping == true ? "shipping:," . $lscodes : $lscodes;
             $objPromoCode->attributes = $arrPost;
             if ($objPromoCode->validate()) {
                 if (!$objPromoCode->save()) {
                     echo $errormsg;
                 } else {
                     echo "success";
                 }
             } else {
                 echo $errormsg;
                 Yii::log("Admin panel validation error saving promo code " . print_r($objPromoCode->getErrors(), true), 'error', 'application.' . __CLASS__ . "." . __FUNCTION__);
             }
         } else {
             echo $errormsg;
         }
     } else {
         echo $errormsg;
     }
 }
 public static function get_from_id($id)
 {
     $id = (int) $id;
     $date = Gadget::$date_do->format(DATE_FORMAT_MYSQL);
     if ($row = dbi()->q_1("SELECT Subscriptions.*, Customers.*\n                                FROM Customers\n                                    LEFT JOIN Subscriptions\n                                        ON (Customers.CustomerID = Subscriptions.CustomerID AND DeliveryDate = '{$date}')\n                                WHERE Customers.CustomerID = '{$id}'")) {
         $DeliveryAddress = new Address(array('Address1' => $row->DeliveryAddress1, 'Address2' => $row->DeliveryAddress2, 'City' => $row->DeliveryCity, 'State' => $row->DeliveryState, 'Zip' => $row->DeliveryZip, 'Comments' => $row->DeliveryComments));
         $BillingAddress = new Address(array('Address1' => $row->BillingAddress1, 'Address2' => $row->BillingAddress2, 'City' => $row->BillingCity, 'State' => $row->BillingState, 'Zip' => $row->BillingZip));
         return new Customer(array('CustomerID' => $row->CustomerID, 'Email' => $row->Email, 'Password' => $row->Password, 'FirstName' => $row->FirstName, 'LastName' => $row->LastName, 'ContactPhone' => $row->ContactPhone, 'Allergies' => $row->Allergies, 'BillingFirstName' => $row->BillingFirstName, 'BillingLastName' => $row->BillingLastName, 'BillingPhone' => $row->BillingPhone, 'BillingCardType' => $row->BillingCardType, 'BillingCardNumber' => $row->BillingCardNumber, 'First_Order_Date' => $row->First_Order_Date, 'Last_Order_Date' => $row->Last_Order_Date, 'Total_Orders' => $row->Total_Orders, 'Delivery_Window' => $row->Delivery_Window, 'CIMCustID' => $row->CIMCustID, 'CIMPymtProfID' => $row->CIMPymtProfID, 'DeliveryAddress' => $DeliveryAddress, 'BillingAddress' => $BillingAddress, 'WeeklyMeals' => $row->WeeklyMeals, 'WeeklyReg' => $row->WeeklyReg, 'WeeklyVeg' => $row->WeeklyVeg, 'Want' => $row->Want, 'DontWant' => $row->DontWant, 'Comments' => $row->Comments, 'PromoCodeID' => $row->PromoCodeID, 'PromoCode' => PromoCode::get_from_id($row->PromoCodeID)));
     } else {
         return NULL;
     }
 }
 public function &__get($name) {
     switch ($name) {
         case 'PromoCode':
             if ($this->PromoCodeID) {
                 return $this->PromoCode = PromoCode::get_from_id($this->PromoCodeID);
             }
             break;
         case 'Customer':
             if ($this->CustomerID) {
                 return $this->Customer = Customer::get_from_id($this->CustomerID);
             }
             break;
     }
     if (isset($this->Amounts->$name)) {
         return $this->Amounts->$name;
     }
     return NULL;
 }
 /**
  * Make sure at least one module is active, otherwise throw warning
  */
 public function verifyActive()
 {
     $objModules = Modules::model()->findAllByAttributes(array('category' => 'shipping', 'active' => 1));
     if (count($objModules) == 0) {
         Yii::app()->user->setFlash('error', Yii::t('admin', 'WARNING: You have no shipping modules activated. No one can checkout.'));
     } else {
         $blnRestrictionWarning = false;
         foreach ($objModules as $objModule) {
             if ($objModule->active) {
                 if ($blnRestrictionWarning) {
                     $objPromo = PromoCode::LoadByShipping($objModule->module);
                     if (!$objPromo instanceof Promocode || !$objPromo->enabled) {
                         //nothing defined or turned off
                         $blnRestrictionWarning = false;
                     }
                 }
             }
             if ($blnRestrictionWarning) {
                 Yii::app()->user->setFlash('warning', Yii::t('admin', 'WARNING: You have product restrictions set on all active shipping modules. This could lead to a scenario where a customer orders an item and no shipping method applies. Check your restrictions carefully to avoid gaps in coverage.'));
             }
         }
     }
 }
 public static function EnableShippingPromoCodes()
 {
     PromoCode::model()->updateAll(array('enabled' => 1), "lscodes LIKE 'shipping:,%'");
 }
// Calculate price details
$logger->LogInfo("Calculating price ...");
$bookingDetails->calculatePriceDetails($language_selected);
// Get entered promo code and client info
$promoErrorMessage = null;
$clientEmailAddress = null;
$client = new Client();
if (isset($_POST['promo_code'])) {
    $logger->LogInfo("Promo code was entered: " . $_POST['promo_code']);
    $client = Client::fetchFromParameters($_POST);
    $bookingDetails->promoCode = null;
    if (isset($_POST['email'])) {
        $logger->LogInfo("Email was entered: " . $_POST['email']);
        $clientsEmailAddress = $_POST['email'];
    }
    $promoCode = PromoCode::fetchFromDBForCode($_POST['promo_code']);
    if ($promoCode == null) {
        $logger->LogWarn("Promo could not be found in the database!");
        $logger->LogWarn("Errors:");
        $logger->LogWarn(PromoCode::$staticErrors);
        $promoErrorMessage = PromoCode::$staticErrors[0];
    } else {
        if ($promoCode->isApplicable($bookingDetails->priceDetails->grandTotal, $clientsEmailAddress, $bookingDetails->searchCriteria->getNightCount(), $promoErrorMessage)) {
            $logger->LogInfo("Promo is applicable!");
            $bookingDetails->promoCode = $promoCode;
            $logger->LogInfo("Recalculating price ...");
            $bookingDetails->calculatePriceDetails($language_selected);
        } else {
            $logger->LogWarn("Promo is not applicable!");
            $logger->LogWarn($promoErrorMessage);
        }
 public function actionNewpromo()
 {
     if (isset($_POST['PromoCode'])) {
         $objPromo = new PromoCode();
         $objPromo->attributes = $_POST['PromoCode'];
         $objPromo->setScenario('create');
         if ($objPromo->validate()) {
             if ($objPromo->save()) {
                 echo CJSON::encode(array('result' => 'success'));
             }
         } else {
             echo CJSON::encode(array('result' => 'failure', 'errors' => $objPromo->getErrors()));
         }
     }
 }
 protected function checkCode()
 {
     //Does this item have a promo code?
     if (isset($this->config['promocode'])) {
         if (!empty($this->config['promocode'])) {
             Yii::log(get_class($this) . " module requires promo code '" . $this->config['promocode'] . "', checking...", 'info', 'application.' . __CLASS__ . "." . __FUNCTION__);
             $cart = $this->objCart;
             if ($cart->fk_promo_id > 0) {
                 $pcode = PromoCode::model()->findbyPk($cart->fk_promo_id);
                 if ($pcode->code == $this->config['promocode']) {
                     return true;
                 }
             }
             return false;
         }
     }
     return true;
 }
Exemple #12
0
$CORE->loggedInOrReturn();
//Load the Tokens Module
$CORE->load_CoreModule('promo.codes');
//prepare multi errors
$ERRORS->NewInstance('pcode');
$RealmID = $CURUSER->GetRealm();
//Get the code
$code = isset($_POST['code']) ? $_POST['code'] : false;
//Get the character name if passed
$charName = isset($_POST['character']) ? $_POST['character'] : false;
if (!$code) {
    $ERRORS->Add("Please enter promo code.");
}
$ERRORS->Check('/index.php?page=pcode');
//Setup new promo code
$PCode = new PromoCode($code);
//set the account
$PCode->setAccount($CURUSER->get('id'));
//set the realm in case of item reward
$PCode->setRealm($RealmID);
//set character if online
$PCode->setCharacter($charName);
//Verify promo code
if ($PCode->Verify()) {
    //Reward the user
    if ($PCode->ProcessReward()) {
        //bind the onsuccess message
        $ERRORS->onSuccess('The promotion code was successfully redeemed.', '/index.php?page=pcode');
        $ERRORS->triggerSuccess();
        exit;
    } else {
Exemple #13
0
 /**
  * Check that the promo code applied to the cart is still valid.
  * If the promo code is no longer valid, remove it and return an error
  * message.
  *
  * @return array|null Null if the promo code is still valid. If the promo
  * code is invalid an array with the following keys will be returned:
  *	code => The promo code.
  *	reason => The reason that the promo code is invalid.
  */
 public function revalidatePromoCode()
 {
     if ($this->fk_promo_id === null) {
         // No promo code applied.
         return null;
     }
     $hasInvalidPromoCode = false;
     $objPromoCode = PromoCode::model()->findByPk($this->fk_promo_id);
     if ($objPromoCode === null) {
         // The promo code has been deleted from Web Store.
         $hasInvalidPromoCode = true;
     } else {
         $objPromoCode->validatePromocode('code', null);
         $arrErrors = $objPromoCode->getErrors();
         if (count($arrErrors) > 0) {
             // After validating the promo code, there were errors.
             $hasInvalidPromoCode = true;
         }
     }
     if ($hasInvalidPromoCode === false) {
         return null;
     }
     if ($objPromoCode === null) {
         $promoCodeCode = '';
         $reason = 'This Promo Code has been disabled.';
     } else {
         $promoCodeCode = $objPromoCode->code;
         $reason = _xls_convert_errors_display(_xls_convert_errors($arrErrors));
     }
     return array('code' => $promoCodeCode, 'reason' => $reason);
 }
Exemple #14
0
<?php

if (!defined('init_ajax')) {
    header('HTTP/1.0 404 not found');
    exit;
}
//Load the Tokens Module
$CORE->load_CoreModule('promo.codes');
header('Content-type: text/json');
$code = isset($_GET['code']) ? $_GET['code'] : false;
if (!$code) {
    echo '{"error": "The promo code is missing."}';
    die;
}
//Setup new promo code
$PCode = new PromoCode($code);
//Verify promo code
if ($PCode->Verify()) {
    echo json_encode($PCode->getInfo());
    exit;
}
//If we're here then something is wrong
echo '{"error": "', $PCode->getLastError(), '"}';
unset($PCode);
exit;
    $promoCode = PromoCode::fetchFromParameters($_POST);
    if (!$promoCode->save()) {
        $logger->LogError("Error saving promo code.");
        foreach ($promoCode->errors as $error) {
            $logger->LogError($error);
            $errors[] = $error;
        }
    } else {
        header("Location: promo_codes_list.php");
    }
} else {
    if (isset($_REQUEST['id']) && is_numeric($_REQUEST['id'])) {
        $logger->LogInfo("Page was called for edit of id: " . $_REQUEST['id']);
        $id = intval($_REQUEST['id']);
        $logger->LogDebug("Numeric id is: {$id}");
        $promoCode = PromoCode::fetchFromDb($id);
        if ($promoCode == null) {
            $logger->LogError("Invalid request. No promo code with id: {$id} exists.");
            $errors[] = "Invalid request. No promo code with id: {$id} exists.";
        }
    }
}
include "header.php";
?>

<!-- jquery.datePicker.js -->
<script type="text/javascript" src="../scripts/jquery-1.2.6.min.js"></script>
<script type="text/javascript" src="../scripts/date.js"></script>
<script type="text/javascript" src="../scripts/jquery.datePicker.js"></script>
<!-- datePicker required styles -->
<link rel="stylesheet" type="text/css" media="screen" href="../css/datePicker.css">
<?php

// TODO: umcomment
include "access.php";
require_once "../includes/SystemConfiguration.class.php";
global $systemConfiguration;
global $logger;
$errors = array();
$logger->LogDebug("Fetching all promo codes ...");
$promoCodes = PromoCode::fetchAllFromDb();
if ($promoCodes == null) {
    $logger->LogError("There were errors fetching nerws categories.");
    foreach (PromoCode::$staticErrors as $error) {
        $logger->LogError($error);
        $errors[] = $error;
    }
}
include "header.php";
?>
	</td>
  </tr> 
  
  <tr>
    <td valign="top" >
    <?php 
if (sizeof($errors) > 0) {
    echo '			<table width="100%">' . "\n";
    foreach ($errors as $error) {
        echo '				<tr><td class="TitleBlue11pt" style="color: red; font-weight: bold;">' . htmlentities($error) . '</td></tr>' . "\n";
    }
    echo '			</table>' . "\n";
 public function getFormCreate()
 {
     return array('title' => 'This feature is for creating one-time use promo codes in bulk for loyalty programs. Paste in your list of codes into the entry blank below, and select an existing promo code to use as a template. The following fields will be copied from this code: Amount, Percent or Money, optional Start and Stop date, Product restrictions and Good Above. Codes created with this process can be used once, then are rendered invalid.', 'elements' => array('createCodes' => array('type' => 'textarea', 'layout' => '<div class="span4">{label}</div><div class="span4">{input}</div>{error}'), 'existingCodes' => array('type' => 'dropdownlist', 'items' => CHtml::listData(PromoCode::model()->findAll(array('condition' => 'enabled=:status AND code IS NOT NULL AND module IS NULL', 'params' => array(':status' => 1), 'order' => 'code')), 'id', 'code'), 'prompt' => 'Please select:', 'layout' => '<div class="span4">{label}</div><div class="span4">{input}</div>{error}')));
 }
 public static function fetchFromDbForCode($promoCode)
 {
     global $logger;
     $logger->LogDebug(__METHOD__ . " Fetching " . __CLASS__ . " object from database for promo code: {$promoCode}");
     PromoCode::$staticErrors = array();
     $sql = "SELECT * FROM bsi_promo_codes WHERE UPPER(TRIM(promo_code)) = '" . strtoupper(trim(mysql_escape_string($promoCode))) . "'";
     $query = mysql_query($sql);
     if (!$query) {
         $logger->LogError("Error executing query: {$sql}");
         $logger->LogFatal("Database error: " . mysql_errno() . ". Message: " . mysql_error());
         die("There was an error connecting to the database. Please try your request again or contact the system administrator.");
     }
     if ($row = mysql_fetch_assoc($query)) {
         $promoCode = PromoCode::fetchFromParameters($row);
         return $promoCode;
     } else {
         $logger->LogWarn("There is no promo code for promo code: {$promoCode}");
         PromoCode::setStaticError(BOOKING_DETAILS_COUPON_INVALID);
         return null;
     }
 }
 /**
  * Extract shipping and billing address information, create address book and map to the carts
  */
 protected function actionConvertAddressBook()
 {
     $sql = "select * from xlsws_cart where billaddress_id IS NULL and address_bill IS NOT NULL order by id limit 500";
     $arrProducts = Yii::app()->db->createCommand($sql)->query();
     while (($result = $arrProducts->read()) !== false) {
         $result['email'] = strtolower($result['email']);
         //verify that Customer ID really exists in customer table
         $objCust = Customer::model()->findByPk($result['customer_id']);
         if (!$objCust instanceof Customer) {
             $result['customer_id'] = 0;
         }
         if (strlen($result['address_bill']) > 0) {
             $arrAddress = explode("\n", $result['address_bill']);
             if (count($arrAddress) == 5) {
                 //old format address, should be 6 pieces
                 $arrAddress[5] = $arrAddress[4];
                 $strSt = $arrAddress[3];
                 if ($strSt[0] == " ") {
                     //no state on this address
                     $arrAddress[4] = substr($strSt, 1, 100);
                     $arrAddress[3] = "";
                 } else {
                     $arrSt = explode(" ", $strSt);
                     $arrAddress[3] = $arrSt[0];
                     $arrAddress[4] = str_replace($arrSt[0] . " ", "", $strSt);
                 }
             }
             $objAddress = new CustomerAddress();
             if (count($arrAddress) >= 5) {
                 $objCountry = Country::LoadByCode($arrAddress[5]);
                 if ($objCountry) {
                     $objAddress->country_id = $objCountry->id;
                     $objState = State::LoadByCode($arrAddress[3], $objCountry->id);
                     if ($objState) {
                         $objAddress->state_id = $objState->id;
                     }
                 }
                 $objAddress->address1 = $arrAddress[0];
                 $objAddress->address2 = $arrAddress[1];
                 $objAddress->city = $arrAddress[2];
                 $objAddress->postal = $arrAddress[4];
                 $objAddress->first_name = $result['first_name'];
                 $objAddress->last_name = $result['last_name'];
                 $objAddress->company = $result['company'];
                 $objAddress->phone = $result['phone'];
                 $objAddress->residential = CustomerAddress::RESIDENTIAL;
                 $objAddress->created = $result['datetime_cre'];
                 $objAddress->modified = $result['datetime_cre'];
                 $objAddress->active = 1;
                 if (empty($objAddress->address2)) {
                     $objAddress->address2 = null;
                 }
                 if (empty($objAddress->company)) {
                     $objAddress->company = null;
                 }
                 $blnFound = false;
                 if ($result['customer_id'] > 0) {
                     //See if this is already in our database
                     $objPriorAddress = CustomerAddress::model()->findByAttributes(array('address1' => $objAddress->address1, 'address2' => $objAddress->address2, 'city' => $objAddress->city, 'postal' => $objAddress->postal, 'first_name' => $objAddress->first_name, 'last_name' => $objAddress->last_name, 'company' => $objAddress->company, 'phone' => $objAddress->phone));
                     if ($objPriorAddress instanceof CustomerAddress) {
                         Yii::app()->db->createCommand("update xlsws_cart set billaddress_id=" . $objPriorAddress->id . " where id=" . $result['id'])->execute();
                         $blnFound = true;
                     } else {
                         $objAddress->customer_id = $result['customer_id'];
                     }
                 } else {
                     //We need a shell customer record just for the email
                     $objC = Customer::model()->findByAttributes(array('email' => $result['email']));
                     if ($objC instanceof Customer) {
                         Yii::app()->db->createCommand("UPDATE xlsws_cart set customer_id=" . $objC->id . " where id=" . $result['id'])->execute();
                     } else {
                         $objC = new Customer();
                         $objC->record_type = Customer::GUEST;
                         $objC->email = $result['email'];
                         $objC->first_name = $objAddress->first_name;
                         $objC->last_name = $objAddress->last_name;
                         $objC->company = $objAddress->company;
                         if (!$objC->validate()) {
                             $arrErr = $objC->getErrors();
                             if (isset($arrErr['email'])) {
                                 $objC->email = $result['id'] . "*****@*****.**";
                             }
                             if (!$objC->validate()) {
                                 return print_r($objC->getErrors(), true);
                             }
                         }
                         if (!$objC->save()) {
                             Yii::log("Import Error " . print_r($objC->getErrors(), true), 'error', 'application.' . __CLASS__ . "." . __FUNCTION__);
                             return print_r($objC->getErrors(), true);
                         } else {
                             $cid = $objC->id;
                         }
                         Yii::app()->db->createCommand("UPDATE xlsws_cart set customer_id=" . $cid . " where id=" . $result['id'])->execute();
                     }
                     $result['customer_id'] = $objC->id;
                     $objAddress->customer_id = $result['customer_id'];
                 }
                 if (!$blnFound) {
                     if (!$objAddress->save()) {
                         //We have a corrupt billing address, just blank it out so import goes on
                         Yii::app()->db->createCommand("update xlsws_cart set address_bill=null where id=" . $result['id'])->execute();
                     } else {
                         $cid = $objAddress->id;
                         Yii::app()->db->createCommand("update xlsws_cart set billaddress_id=" . $cid . " where id=" . $result['id'])->execute();
                     }
                 }
             } else {
                 //We have a corrupt billing address, just blank it out so import goes on
                 Yii::app()->db->createCommand("update xlsws_cart set address_bill=null where id=" . $result['id'])->execute();
             }
             $objAddress = new CustomerAddress();
             $objCountry = Country::LoadByCode($result['ship_country']);
             if ($objCountry) {
                 $objAddress->country_id = $objCountry->id;
                 $objState = State::LoadByCode($result['ship_state'], $objCountry->id);
                 if ($objState) {
                     $objAddress->state_id = $objState->id;
                 }
             }
             $objAddress->first_name = $result['ship_firstname'];
             $objAddress->last_name = $result['ship_lastname'];
             $objAddress->company = $result['ship_company'];
             $objAddress->address1 = $result['ship_address1'];
             $objAddress->address2 = $result['ship_address2'];
             $objAddress->city = $result['ship_city'];
             $objAddress->postal = $result['ship_zip'];
             $objAddress->phone = $result['ship_phone'];
             $objAddress->residential = CustomerAddress::RESIDENTIAL;
             $objAddress->created = $result['datetime_cre'];
             $objAddress->modified = $result['datetime_cre'];
             $objAddress->active = 1;
             if (empty($objAddress->address2)) {
                 $objAddress->address2 = null;
             }
             if (empty($objAddress->company)) {
                 $objAddress->company = null;
             }
             $blnFound = false;
             if ($result['customer_id'] > 0) {
                 //See if this is already in our database
                 $objPriorAddress = CustomerAddress::model()->findByAttributes(array('address1' => $objAddress->address1, 'city' => $objAddress->city, 'postal' => $objAddress->postal, 'first_name' => $objAddress->first_name, 'last_name' => $objAddress->last_name, 'company' => $objAddress->company, 'phone' => $objAddress->phone));
                 if ($objPriorAddress instanceof CustomerAddress) {
                     Yii::app()->db->createCommand("update xlsws_cart set shipaddress_id=" . $objPriorAddress->id . " where id=" . $result['id'])->execute();
                     $blnFound = true;
                 } else {
                     $objAddress->customer_id = $result['customer_id'];
                 }
             }
             if (!$blnFound) {
                 if (!$objAddress->save()) {
                     Yii::log("Import Error " . print_r($objAddress->getErrors(), true), 'error', 'application.' . __CLASS__ . "." . __FUNCTION__);
                 } else {
                     $cid = $objAddress->id;
                     Yii::app()->db->createCommand("update xlsws_cart set shipaddress_id=" . $cid . " where id=" . $result['id'])->execute();
                 }
             }
         }
         $objShipping = new CartShipping();
         $objShipping->shipping_method = $result['shipping_method'];
         $objShipping->shipping_module = $result['shipping_module'];
         $objShipping->shipping_data = $result['shipping_data'];
         $objShipping->shipping_cost = $result['shipping_cost'];
         $objShipping->shipping_sell = $result['shipping_sell'];
         if (!$objShipping->save()) {
             return print_r($objShipping->getErrors());
         } else {
             $cid = $objShipping->id;
         }
         Yii::app()->db->createCommand("update xlsws_cart set shipping_id=" . $cid . " where id=" . $result['id'])->execute();
         $objPayment = new CartPayment();
         $objPayment->payment_method = $result['payment_method'];
         $objPayment->payment_module = str_replace(".php", "", $result['payment_module']);
         $objPayment->payment_data = $result['payment_data'];
         $objPayment->payment_amount = $result['payment_amount'];
         $objPayment->datetime_posted = $result['datetime_posted'];
         if ($result['fk_promo_id'] > 0) {
             $objPromo = PromoCode::model()->findByPk($result['fk_promo_id']);
             if ($objPromo) {
                 $objPayment->promocode = $objPromo->code;
             }
         }
         if (!$objPayment->save()) {
             return print_r($objPayment->getErrors());
         } else {
             $cid = $objPayment->id;
         }
         Yii::app()->db->createCommand("update xlsws_cart set payment_id=" . $cid . " where id=" . $result['id'])->execute();
     }
     $results2 = Yii::app()->db->createCommand("select count(*) from xlsws_cart where billaddress_id IS NULL and address_bill IS NOT NULL")->queryScalar();
     if ($results2 == 0) {
         $remain = 8;
     } else {
         $remain = 3;
     }
     return array('result' => "success", 'makeline' => $remain, 'total' => 50, 'tag' => 'Converting cart addresses, ' . $results2 . ' remaining');
 }
Exemple #20
0
         $transaction->line_items[] = $li;
     }
     if ($meal['VegCount']) {
         $li = new AuthorizeNetLineItem();
         $li->itemId = $meal['Meal']->ItemID;
         $li->name = strlen($mealName) > 18 ? substr($mealName, 0, 18) . ' - Vegetarian' : $mealName . ' - Vegetarian';
         $li->quantity = $meal['VegCount'];
         $li->unitPrice = $meal['Meal']->Vegetarian_Price;
         $li->taxable = true;
         $transaction->line_items[] = $li;
     }
 }
 $transaction->info->description = "Madison &amp; Rayne Order For Week {$week}" . ($order->PromoCode ? ' - ' . $order->PromoCode->description : '');
 $transaction->amounts = array('total' => $order->Amounts->Total, 'tax' => $order->Amounts->Tax);
 // if gift codes bring the total to 0
 $promoCode = PromoCode::get_from_id($order->PromoCodeID);
 if ($order->Amounts->Total == 0) {
     $krustomer->First_Order_Date = $krustomer->First_Order_Date ? $krustomer->First_Order_Date : $date;
     $krustomer->Last_Order_Date = date('Y-m-d');
     $krustomer->Total_Orders++;
     $krustomer->update();
     $orderSuccess = true;
     // If they used a promocode that was an ammount, subtract total from promocode amount
     if ($promoCode->multiple_use == 0) {
         if ($promoCode->Amount > 0 && $promoCode->PromoCodeType == "Amount Discount") {
             $newPromoCodeAmount = $promoCode->Amount - $order->Amounts->Total;
             if ($newPromoCodeAmount < 0) {
                 $newPromoCodeAmount = 0;
             }
             $dbi->update('PromoCodes', array('Amount' => $newPromoCodeAmount), array('PromoCodeID' => $order->PromoCodeID));
         }
Exemple #21
0
 public function applyPromoCode($mixCode)
 {
     if ($mixCode instanceof PromoCode) {
         $objPromoCode = $mixCode;
     } else {
         $objPromoCode = PromoCode::LoadByCode($mixCode);
     }
     if ($objPromoCode instanceof PromoCode) {
         $this->model->fk_promo_id = $objPromoCode->id;
         $this->recalculateAndSave();
     }
 }
        foreach ($validation->errors as $error) {
            Gadget::add_message($error);
        }
    } else {

        $PromoCodeID = NULL;
        if ($_POST['PromoCodeName']) {
            $PromoCodeName = $dbi->escape($_POST['PromoCodeName']);

            $PromoCodeID = $dbi->q_1("SELECT PromoCodeID
                                        FROM PromoCodes
                                        WHERE PromoCodeName = '$PromoCodeName'
                                            AND ValidFrom <= CURDATE()
                                            AND (ValidTo IS NULL OR ValidTo >= CURDATE())")->PromoCodeID;

            $PromoCode = PromoCode::get_from_id($PromoCodeID);
        }
        if ($PromoCode && $PromoCode->can_be_used($_SESSION['CustomerID'], 'GiftCertificates')) {

            $PromoCodeID     = $PromoCode->PromoCodeID;
            $totalCost       = $PromoCode->apply_discount(new Amount($data['GiftAmount']));
            $beforePromoCost = new Amount($data['GiftAmount']);
        } else {
            $PromoCodeID     = NULL;
            $totalCost       = new Amount($data['GiftAmount']);
            $beforePromoCost = new Amount($data['GiftAmount']);
        }

        $transaction                   = new Transaction();
        //$transaction->debug            = true;
        $transaction->amounts['total'] = $totalCost;
 /**
  * Apply a promo code to the cart and return an array indicating what happened.
  * @param string $strPromoCode The promocode.
  * @return array An array indicating what happened.
  *	['success'] boolean Whether the promo code was applied.
  *	['action'] string Recommended action: alert|error|triggerCalc|success.
  *	['message'] string A message to display.
  */
 protected function applyPromoCodeModal($strPromoCode)
 {
     if (Yii::app()->shoppingcart->PromoCode !== null) {
         return array('success' => false, 'action' => 'alert', 'message' => Yii::t('global', 'Only one promo code can be applied'));
     }
     $objPromoCode = new PromoCode();
     $objPromoCode->code = $strPromoCode;
     $objPromoCode->setScenario('checkout');
     if ($objPromoCode->validate() === false) {
         $arrErrors = $objPromoCode->getErrors();
         return array('success' => false, 'action' => 'error', 'message' => $arrErrors['code'][0]);
     }
     $objPromoCode = PromoCode::LoadByCode($strPromoCode);
     Yii::app()->shoppingcart->applyPromoCode($objPromoCode);
     // See if this promo code is supposed to turn on free shipping.
     // This runs AFTER validate() so if we get here, it means that any
     // criteria have passed. So just apply and refresh the shipping list.
     if ($objPromoCode->Shipping) {
         // Update the shipping selection to use the free shipping module.
         $objFreeShipping = Modules::model()->freeshipping()->find();
         if ($objFreeShipping !== null) {
             $checkoutForm = MultiCheckoutForm::loadFromSession();
             if ($checkoutForm !== null) {
                 try {
                     $arrCartScenario = Shipping::getCartScenarios($checkoutForm);
                 } catch (Exception $e) {
                     $arrCartScenario = null;
                 }
                 if ($arrCartScenario !== null) {
                     $freeShippingScenario = findWhere($arrCartScenario, array('providerId' => $objFreeShipping->id));
                     $checkoutForm = MultiCheckoutForm::loadFromSessionOrNew();
                     $checkoutForm->shippingProvider = $freeShippingScenario['providerId'];
                     $checkoutForm->shippingPriority = $freeShippingScenario['priorityLabel'];
                     MultiCheckoutForm::saveToSession($checkoutForm);
                 }
             }
         }
         return array('success' => true, 'action' => 'triggerCalc', 'message' => Yii::t('global', 'Congratulations! This order qualifies for Free Shipping!'));
     }
     return array('success' => true, 'action' => 'success');
 }