Skip to content

Commit

Permalink
updates to coupon module
Browse files Browse the repository at this point in the history
  • Loading branch information
jedateach committed Apr 20, 2011
1 parent 38dcb26 commit b21c09c
Show file tree
Hide file tree
Showing 8 changed files with 337 additions and 53 deletions.
8 changes: 8 additions & 0 deletions README
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,11 @@ Pre 0.1 proof of concept
see: http://code.google.com/p/silverstripe-ecommerce


Possible uses for this module:
*gift vouchers/cards
*discount coupons
*credit notes


TODO:
* Handle cases such as: buy x, and get x for half price
1 change: 0 additions & 1 deletion _config.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,5 @@
//===================---------------- START ecommerce_discount_coupon MODULE ----------------===================
//NOTE: add http://svn.gpmd.net/svn/open/multiselectfield/tags/0.2/ for nicer interface
//DiscountCoupon::set_form_header("Delivery Option (REQUIRED)"); //doesn't work
ProductsAndGroupsModelAdmin::add_managed_model("OrderCoupon");
Order::set_modifiers(array('OrderCouponModifier'));
//===================---------------- END ecommerce_discount_coupon MODULE ----------------===================
9 changes: 9 additions & 0 deletions code/cms/CouponBulkLoader.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<?php

class CouponBulkLoader extends CSVBulkLoader{

//TODO

}

?>
110 changes: 110 additions & 0 deletions code/cms/CouponsModelAdmin.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
<?php

/**
* @author Nicolaas [at] sunnysideup.co.nz, jeremy [at] burnbright.co.nz
**/

class CouponsModelAdmin extends ModelAdmin {

static $menu_priority = 4;

public static $collection_controller_class = "CouponsModelAdmin_CollectionController";

public static $record_controller_class = "CouponsModelAdmin_RecordController";

public static $managed_models = array("OrderCoupon");

public static function set_managed_models(array $array) {
self::$managed_models = $array;
}
public static function add_managed_model($item) {self::$managed_models[] = $item;}

public static $url_segment = 'coupons';

public static $menu_title = 'Coupons';

public static $model_importers = array(
'Product' => 'CouponBulkLoader',
);


function GenerateCouponsForm(){

$fields = Object::create('OrderCoupon')->scaffoldFormFields();

$fields->insertBefore(new HeaderField('generatorhead','Generate Coupons'),'Title');
$fields->insertBefore(new NumericField('Number','Number of coupons to generate'),'Title');
$fields->removeByName('Code');

$actions = new FieldSet(
new FormAction('generate','Generate')
);

$validator = new RequiredFields(array(
'Title',
'Number'
));

return new Form($this,"GenerateCouponsForm",$fields,$actions,$validator);
}

function generate($data,$form){

$count = 1;
if(isset($data['Number']) && is_numeric($data['Number']))
$count = (int)$data['Number'];

for($i = 0; $i < $count; $i++){
$coupon = new OrderCoupon();
$form->saveInto($coupon);
$coupon->Code = OrderCoupon::generateNewCode();
$coupon->write();
}

return "Generated $count coupons, now click 'Search' to see them";
}


}
//remove side forms
class CouponsModelAdmin_CollectionController extends ModelAdmin_CollectionController {

//public function CreateForm() {return false;}
//public function ImportForm() {return false;}

//note that these are called once for each $managed_models

function ImportForm(){
$form = parent::ImportForm();
if($form){
//EmptyBeforeImport checkbox does not appear to work for SiteTree objects, so removed for now
$form->Fields()->removeByName('EmptyBeforeImport');
}
return $form;
}


//TODO: Half-started attempt at modifying the way products are deleted - they should be deleted from both stages
function ResultsForm($searchCriteria){
$form = parent::ResultsForm($searchCriteria);
if($tf = $form->Fields()->fieldByName($this->modelClass)){
/*$tf->actions['create'] = array(
'label' => 'delete',
'icon' => null,
'icon_disabled' => 'cms/images/test.gif',
'class' => 'testlink'
);*/

/*$tf->setPermissions(array(
'create'
));*/
}
return $form;
}


}

class CouponsModelAdmin_RecordController extends ModelAdmin_RecordController{

}
87 changes: 65 additions & 22 deletions code/model/OrderCoupon.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,18 +10,25 @@
class OrderCoupon extends DataObject {

static $db = array(
"Title" => "Varchar(255)", //store the promotion name, or whatever you like
"Code" => "Varchar(25)",
"Value" => "Currency",
"PercentageDiscount" => "Decimal(4,2)",

"StartDate" => "Date",
"EndDate" => "Date",
"DiscountAbsolute" => "Currency",
"DiscountPercentage" => "Decimal(4,2)",
//"CanOnlyBeUsedOnce" => "Boolean",

//TODO: Order must be greater than...


"MinOrderValue" => "Currency",
"UseLimit" => 'Int'
//"Type" => "Enum('Voucher,GiftCard,Coupon','Coupon')" //for managing purposes
//"UseInConjunction" => "Boolean"
);


public static $has_many = array(
//'FreeItems' => 'OrderItem'
//'SpecificProducts' => 'Product' //ie: not for any order
);

public static $casting = array(
"UseCount" => "Int",
"IsValid" => "Boolean"
Expand All @@ -39,20 +46,30 @@ class OrderCoupon extends DataObject {

public static $summary_fields = array(
"Code",
"Title",
"StartDate",
"EndDate"
);

protected static $coupons_can_only_be_used_once = "";
static function set_coupons_can_only_be_used_once($b) {self::$coupons_can_only_be_used_once = $b;}
static function get_coupons_can_only_be_used_once() {return self::$coupons_can_only_be_used_once;}

protected static $code_length = 10;
static function set_code_length($l) {self::$code_length = $l;}
static function get_code_length() {return self::$code_length;}


public static $singular_name = "Order Coupon";

public static $plural_name = "Order Coupon";

public static $default_sort = "EndDate DESC, StartDate DESC";


static function get_by_code($code){
return DataObject::get_one('OrderCoupon',"\"Code\" = UPPER('$code')");
}

function UseCount() {
$objects = DataObject::get("OrderCouponModifier", "\"OrderCouponID\" = ".$this->ID);
if($objects) {
Expand All @@ -62,29 +79,41 @@ function UseCount() {
}

function IsValid() {
if($this->UseLimit > 0 && $this->UseCount() < $this->UseLimit) {

$this->getForm()->sessionMessage(_t("OrderCoupon.LIMITREACHED","Limit of $this->UseLimit has been reached"),'bad');

if($this->UseLimit > 0 && $this->UseCount() < $this->UseLimit) {
//$this->getForm()->sessionMessage(_t("OrderCoupon.LIMITREACHED","Limit of $this->UseLimit has been reached"),'bad');
return false;
}

//TODO:check order minimum

$startDate = strtotime($this->StartDate);
$endDate = strtotime($this->EndDate);
$today = strtotime("today");
$yesterday = strtotime("yesterday");


if($this->EndDate && $endDate < $yesterday){
$this->getForm()->sessionMessage(_t("OrderCoupon.EXPIRED","This coupon has already expired"),'bad');
//$this->getForm()->sessionMessage(_t("OrderCoupon.EXPIRED","This coupon has already expired"),'bad');
return false;
}

if($this->StartDate && $startDate > $today){
$this->getForm()->sessionMessage(_t("OrderCoupon.TOOEARLY","It is too early to use this coupon"),'bad');
//$this->getForm()->sessionMessage(_t("OrderCoupon.TOOEARLY","It is too early to use this coupon"),'bad');
return false;
}

return true;
}

function getDiscountValue($origionalvalue){
if($this->DiscountAbsolute) {
return $origionalvalue - abs($this->Value);
}
if($this->PercentageDiscount) {
return $origionalvalue * ($this->PercentageDiscount / 100);
}
return $origionalvalue;
}


function canDelete($member = null) {
Expand All @@ -101,16 +130,30 @@ function canEdit($member = null) {
function getCMSFields() {
$fields = parent::getCMSFields();

//TODO: only allow entering percentage, OR ammount

if(!$this->Code){
$this->Code = self::generateNewCode();
}
//TODO: only allow entering percentage, OR ammount ..ie javascript split the two
return $fields;
}

function onBeforeWrite() {
$this->Code = eregi_replace("[^[:alnum:]]", " ", $this->Code );
$this->Code = trim(eregi_replace(" +", "", $this->Code));
parent::onBeforeWrite();
function setCode($code){
$code = eregi_replace("[^[:alnum:]]", " ", $code); //EXPLAIN: what does this do?
$code = trim(eregi_replace(" +", "", $code)); //gets rid of any white spaces
$this->setField("Code", strtoupper($code));
}


/**
* Static function for generating new codes.
* @return string - the new code, in uppercase, based on the first x characters of md5(time())
*/
static function generateNewCode(){
$code = null;
do{
$code = strtoupper(substr(md5(time()),0,self::$code_length));
}while(DataObject::get('OrderCoupon',"\"Code\" = '$code'"));
return $code;
}

}

Loading

0 comments on commit b21c09c

Please sign in to comment.