Skip to content

Instantly share code, notes, and snippets.

@brunokruse
Created March 7, 2014 16:00
Show Gist options
  • Select an option

  • Save brunokruse/9414216 to your computer and use it in GitHub Desktop.

Select an option

Save brunokruse/9414216 to your computer and use it in GitHub Desktop.
count redeemed debug
<?php
App::uses('AppModel', 'Model');
/**
* @property User $User
* @property Saving $Saving
* @property Scan $Scan
*/
class Campaign extends AppModel {
public $uploadDir = null;
/**
* Model name
*
* @var string
*/
public $name = 'Campaign';
public $belongsTo = array('User', 'Category');
public $hasMany = array('Saving', 'Scan', 'Social', 'Redemption', 'Reverse', 'Rating', 'Geocode', 'Winner', 'SpecialSaving');
public $actsAs = array(
'Upload.Upload' => array(
'barcode',
'processUpload',
'product_picture'
)
);
public $validate = array();
public function __construct($id = false, $table = null, $ds = null) {
parent::__construct($id, $table, $ds);
App::uses('Data', 'Utility');
$this->uploadDir = WWW_ROOT . 'files' . DS;
$noInputError = Configure::read('Translations.Messages.noInputError');
$noSelectionError = Configure::read('Translations.Messages.noSelectionError');
$urlError = Configure::read('Translations.Messages.urlError');
$this->validate = array(
'company_name' => array(
'rule' => 'notEmpty',
'message' => $noInputError
),
'promotion_type' => array(
'rule' => 'notEmpty',
'message' => $noInputError
),
'name' => array(
'rule' => 'notEmpty',
'message' => $noInputError
),
'promotion_name' => array(
'rule' => 'notEmpty',
'message' => $noInputError
),
'promotion_description' => array(
'rule' => 'notEmpty',
'message' => $noInputError
),
'category_id' => array(
'rule' => 'notEmpty',
'message' => $noInputError
),
'start_date' => array(
'rule' => 'date',
'message' => $noInputError
),
'end_date' => array(
'rule' => 'date',
'message' => $noInputError
),
'redemption_frequency_count' => array(
'rule' => 'notEmpty',
'message' => $noInputError
),
'standard_price' => array(
'rule' => 'notEmpty',
'message' => $noInputError
),
'discount_nach_price' => array(
'rule' => 'notEmpty',
'message' => $noInputError
),
'redemption_frequency_interval' => array(
'rule' => 'notEmpty',
'message' => $noSelectionError
),
'company_url' => array(
'rule' => 'url',
'allowEmpty' => true,
'message' => $urlError
)
);
}
/**
* Callback
*
* @return boolean
*/
public function afterValidate() {
parent::afterValidate();
// make sure there are no validation errors on the dates
if (isset($this->data[$this->alias]['start_date']) AND
!isset($this->validationErrors['start_date']) AND
!isset($this->validationErrors['end_date'])) {
if ($this->data[$this->alias]['start_date'] > $this->data[$this->alias]['end_date']) {
$this->invalidate('end_date', __('End date must be greater than or equal to the start date.'));
}
}
}
public function beforeSave($options = array()) {
if (isset($this->data[$this->alias]['end_date']) AND
!empty($this->data[$this->alias]['end_date']) AND
strlen($this->data[$this->alias]['end_date']) <= 10) {
$this->data[$this->alias]['end_date'] = $this->data[$this->alias]['end_date'] . ' 23:59:59';
}
if (isset($this->data[$this->alias]['lottery_end_date']) AND
!empty($this->data[$this->alias]['lottery_end_date']) AND
strlen($this->data[$this->alias]['lottery_end_date']) <= 10) {
$this->data[$this->alias]['lottery_end_date'] = $this->data[$this->alias]['lottery_end_date'] . ' 23:59:59';
}
return parent::beforeSave($options);
}
public function customRange($check, $from = 0, $to = 1) {
$value = current($check);
return is_numeric($value) AND $value >= $from AND $value <= $to;
}
public function checkEmpty($check = array()) {
$key = key($check);
if ($check[$key]['error'] == 4) {
return false;
}
return true;
}
public function processUpload($check = array()) {
// deal with uploaded file
$key = key($check);
if (!empty($check[$key]['tmp_name'])) {
$user_id = $this->authUserId;
if (!empty($this->data['Campaign']['user_id'])) {
$user_id = $this->data['Campaign']['user_id'];
}
// check file is uploaded
if (!is_uploaded_file($check[$key]['tmp_name'])) {
return FALSE;
}
$path = $this->uploadDir . $user_id;
if (!is_dir($path)) {
mkdir($path, 0777, true); // permissions
}
// build full filename
$filename = $path . DS . md5(time() . $check[$key]['name']) . '.' . pathinfo($check[$key]['name'], PATHINFO_EXTENSION);
// @todo check for duplicate filename
// try moving file
if (!move_uploaded_file($check[$key]['tmp_name'], $filename)) {
return FALSE;
} else {
// save the file path relative from WWW_ROOT e.g. uploads/example_filename.jpg
$newKey = str_replace('_file', '', $key);
$loc = str_replace(DS, "/", str_replace(WWW_ROOT, "", $filename));
$this->{$newKey} = $loc;
if (!empty($this->data[$this->alias][$newKey])) {
$filepath = WWW_ROOT . $this->data[$this->alias][$newKey];
if (file_exists($filepath)) {
unlink($filepath);
}
}
if ($key == 'product_picture_file') {
$arr = getimagesize($loc);
if ($arr[0] != $this->productPictureSize['width'] || $arr[1] != $this->productPictureSize['height']) {
if (file_exists($loc)) {
unlink($loc);
}
return false;
}
}
$this->data[$this->alias][$newKey] = $loc;
}
}
return TRUE;
}
public function beforeValidate($options = array()) {
$uploadError = Configure::read('Translations.Messages.noInputError');
$processUploadError = Configure::read('Translations.Messages.processUploadError');
$mimeTypeError = Configure::read('Translations.Messages.mimeTypeError');
$dateError = Configure::read('Translations.Messages.dateError');
$noInputError = Configure::read('Translations.Messages.noInputError');
$this->productPictureSize = Configure::read('Campaign.productPictureSize');
$processUploadSizeError = sprintf(Configure::read('Translations.Messages.processUploadSizeError'),
$this->productPictureSize['width'], $this->productPictureSize['height']);
$this->validate['discount'] = array(
'rule' => 'notEmpty',
'message' => $noInputError
);
$checkUploads = array('product_logo', 'product_picture');
if (!isset($this->data[$this->alias]['lottery_type']) OR
$this->data[$this->alias]['lottery_type'] !== 'special') {
$checkUploads[] = 'barcode';
}
foreach ($checkUploads as $checkUpload) {
if (!(!empty($this->data[$this->alias][$checkUpload]) && empty($this->data[$this->alias][$checkUpload . '_file']['tmp_name']))) {
$processUploadErrorMsg = $processUploadError;
if ($checkUpload == 'product_picture') {
$processUploadErrorMsg = $processUploadSizeError;
}
$this->validate[$checkUpload . '_file'] = array(
'uploadError' => array(
'rule' => 'uploadError',
'message' => $uploadError,
'required' => FALSE,
'allowEmpty' => TRUE,
),
// custom callback to deal with the file upload
'processUpload' => array(
'rule' => 'processUpload',
'message' => $processUploadErrorMsg,
'required' => FALSE,
'allowEmpty' => TRUE,
'last' => TRUE,
),
'mimeType' => array(
'rule' => array('isValidMimeType', array('image/gif', 'image/png', 'image/jpg', 'image/jpeg')),
'message' => $mimeTypeError,
)
);
}
}
if (!empty($this->data[$this->alias]['deal_type'])) {
if (isset($this->data[$this->alias]['lottery_type']) OR isset($this->data[$this->alias]['discount'])) {
$lotteryType = '';
if (isset($this->data[$this->alias]['lottery_type'])) {
$lotteryType = $this->data[$this->alias]['lottery_type'];
}
$discountType = '';
if (isset($this->data[$this->alias]['discount'])) {
$discountType = $this->data[$this->alias]['discount'];
}
if ($discountType == 'price' OR $lotteryType == 'reward') {
$this->validate['standard_price'] = array(
array('rule' => 'notEmpty', 'message' => $noInputError)
);
$this->validate['discount_percent'] = array(
array('rule' => 'notEmpty', 'message' => $noInputError),
array('rule' => 'decimal', 'message' => __('Ungültige Prozentzahl.')),
array('rule' => array('customRange', 0, 100), 'message' => __('Zwischen 0 und 100.'))
);
} else if ($discountType == 'amount') {
$this->validate['discount_count'] = array(
array('rule' => 'notEmpty', 'message' => $noInputError),
array('rule' => array('naturalNumber', true), 'message' => __('Bitte geben Sie eine Ganzzahl größer gleich 0 ein.'))
);
$this->validate['discount_reference'] = array(
array('rule' => 'notEmpty', 'message' => $noInputError),
array('rule' => array('naturalNumber', true), 'message' => __('Bitte geben Sie eine Ganzzahl größer gleich 0 ein.'))
);
}
if (in_array($discountType, array('price', 'amount')) OR $lotteryType == 'reward') {
$this->validate['discount_nach_price'] = array(
array('rule' => 'notEmpty', 'message' => $noInputError)
);
}
}
if ($this->data[$this->alias]['deal_type'] == 'lottery') {
$this->validate['number_of_winners'] = array(
array('rule' => 'notEmpty', 'message' => $noInputError),
array('rule' => 'naturalNumber', 'message' => __('Bitte geben Sie eine Ganzzahl größer gleich 1 ein.'))
);
$this->validate['lottery_end_date'] = array(
'rule' => 'date',
'message' => $dateError
);
$this->validate['lottery_type'] = array(
'rule' => 'notEmpty',
'message' => $noInputError
);
if (!empty($this->data[$this->alias]['lottery_type']) && $this->data[$this->alias]['lottery_type'] == 'special') {
$this->validate['lottery_contact'] = array(
'rule' => 'notEmpty',
'message' => $noInputError
);
$this->validate['lottery_code'] = array(
'rule' => 'notEmpty',
'message' => $noInputError
);
$this->validate['lottery_contact_phone'] = array(
'rule' => 'notEmpty',
'message' => $noInputError
);
unset($this->validate['discount']);
}
} else if ($this->data[$this->alias]['deal_type'] == 'unlock') {
$this->validate['scan_limit'] = array(
'rule' => 'notEmpty',
'message' => $noInputError
);
$this->validate['scan_frequency_count'] = array(
'rule' => 'notEmpty',
'message' => $noInputError
);
$this->validate['scan_frequency_interval'] = array(
'rule' => 'notEmpty',
'message' => $noInputError
);
}
}
return parent::beforeValidate($options);
}
public function afterSave($created) {
parent::afterSave($created);
$campaigns = $this->find('first', array(
'recursive' => -1,
'conditions' => array('Campaign.id' => $this->id),
'fields' => array('Campaign.id', 'Campaign.company_url', 'Campaign.created', 'Campaign.user_id', 'Campaign.promotion_type')
));
if (!empty($campaigns['Campaign']['company_url']) && $campaigns['Campaign']['promotion_type'] == 'code') {
Data::qrGen($this->id, $campaigns['Campaign']['user_id'], $campaigns['Campaign']['company_url']);
}
if (!$created) {
$winnerUserIds = $this->field('winner_user_id', array('Campaign.id' => $this->id));
if (!empty($winnerUserIds)) {
$this->Winner->setWinners($this->id, $winnerUserIds);
}
} else {
$this->User->admin = true;
$test_phase_start = $this->User->field('test_phase_start', array('User.id' => $campaigns['Campaign']['user_id']));
if (empty($test_phase_start)) {
$this->User->id = $campaigns['Campaign']['user_id'];
$this->User->saveField('test_phase_start', $campaigns['Campaign']['created']);
}
}
}
public function deal_datas($private_token, $campaign_ids) {
$campaigns = $this->find('all', array(
'fields' => array(
'User.country_id',
'User.street',
'User.zipcode',
'User.location',
'User.phone',
'Campaign.id',
'Campaign.deal_type',
'Campaign.company_url',
'Campaign.name',
'Campaign.company_name',
'Campaign.start_date',
'Campaign.end_date',
'Campaign.promotion_name',
'Campaign.promotion_description',
'Campaign.barcode',
'Campaign.product_logo',
'Campaign.product_picture',
'Campaign.lottery_type',
'Campaign.redemption_frequency_count',
'Campaign.redemption_frequency_interval',
'Campaign.redemptions_limit',
'Campaign.lottery_end_date',
'Campaign.lottery_code',
'Campaign.lottery_contact',
'Campaign.lottery_contact_phone',
'Campaign.scan_limit',
'Campaign.rating',
'Campaign.category_id',
'Campaign.status',
'Campaign.standard_price',
'Campaign.discount_nach_price',
'Campaign.discount',
'Campaign.discount_percent',
'Campaign.discount_count',
'Campaign.discount_reference'
),
'conditions' => array(
'Campaign.id' => $campaign_ids
),
'contain' => array(
'User',
'Saving' => array('conditions' => array('Saving.private_token' => $private_token), 'fields' => array('Saving.id', 'Saving.created')),
'Scan' => array('conditions' => array('Scan.private_token' => $private_token), 'fields' => array('Scan.id')),
'Social' => array('conditions' => array('Social.private_token' => $private_token), 'fields' => array('Social.id')),
'Geocode' => array(
'fields' => array('lng', 'lat', 'formatted_address', 'phone'),
'Opening' => array('fields' => array('title', 'start', 'end'))
)
//'Rating' => array('fields' => array('SUM(Rating.value) as sum, count(*) as count'))
)
));
$redemptions = $this->Redemption->find('all', array(
'fields' => array('campaign_id', 'max(created) AS last_redeemed'),
'conditions' => array('private_token' => $private_token, 'campaign_id' => $campaign_ids),
'recursive' => -1,
'group' => 'campaign_id'));
$lastRedemptions = Hash::combine($redemptions, '{n}.Redemption.campaign_id', '{n}.0.last_redeemed');
$result = array();
foreach ($campaigns as $ckey => $campaign) {
$savingCount = count($campaign['Saving']);
// cut off seconds
if (isset($campaign['Geocode'])) {
foreach ($campaign['Geocode'] AS $geocodeIndex => $geocode) {
foreach ($geocode['Opening'] AS $openingIndex => $opening) {
$campaign['Geocode'][$geocodeIndex]['Opening'][$openingIndex]['start'] = substr($opening['start'], 0, 5);
$campaign['Geocode'][$geocodeIndex]['Opening'][$openingIndex]['end'] = substr($opening['end'], 0, 5);
}
}
}
$addedTimestamp = 0;
if ($savingCount > 0) {
$addedTimestamp = strtotime($campaign['Saving'][0]['created']);
}
$endtime = strtotime($campaign['Campaign']['end_date']);
$phone = '';
if ($campaign['User']['phone']) {
$phone = $campaign['User']['phone'];
}
// check redeemed
$lastRedeemed = 0;
$redemptionsLimit = 0;
$countRedeemed = 0;
if (isset($lastRedemptions[$campaign['Campaign']['id']])) {
// check reached redemption frequency
$createdCondition = array();
switch ($campaign['Campaign']['redemption_frequency_interval']) {
// day
case 'day':
$createdCondition = array('created >' => date('Y-m-d H:i:s', time() - DAY));
break;
// week
case 'week':
$createdCondition = array('created >' => date('Y-m-d H:i:s', time() - WEEK));
break;
// month (30 days)
case 'month':
$createdCondition = array('created >' => date('Y-m-d H:i:s', time() - MONTH));
break;
}
$countRedeemed = $this->Redemption->find('first', array(
'fields' => array('count(*) AS count_redeemed'),
'conditions' => $createdCondition +
array(
'private_token' => $private_token,
'campaign_id' => $campaign['Campaign']['id']
),
'recursive' => -1));
$countRedeemed = isset($countRedeemed[0]['count_redeemed']) ? $countRedeemed[0]['count_redeemed'] : 0;
if ($countRedeemed >= $campaign['Campaign']['redemption_frequency_count']) {
// invalid
$lastRedeemed = strtotime($lastRedemptions[$campaign['Campaign']['id']]);
} else {
$valid = $this->Redemption->checkRedemptionLimit($campaign['Campaign']['id']);
if (!$valid) {
// count redeemed not higher than count
$lastRedeemed = strtotime($lastRedemptions[$campaign['Campaign']['id']]);
$redemptionsLimit = $campaign['Campaign']['redemptions_limit'];
}
}
}
$result[$ckey] = array(
'id' => $campaign['Campaign']['id'],
'type' => $campaign['Campaign']['deal_type'],
'locked' => false,
'entered_lottery' => false,
'added' => $addedTimestamp,
// 0 if valid
'last_redeemed' => $lastRedeemed,
// 0 if valid
'redemptions_limit' => $redemptionsLimit,
'count_redeemed' => $countRedeemed,
'saving' => $savingCount,
'adress' => Data::formatAddress($campaign['User']),
'phone' => $phone,
'company_url' => $campaign['Campaign']['company_url'],
'campaign_url' => 'http://ec2-54-201-243-213.us-west-2.compute.amazonaws.com/?site=view&id=' . $campaign['Campaign']['id'],
'title' => $campaign['Campaign']['name'],
'company' => $campaign['Campaign']['company_name'],
'end_time' => $endtime,
'promotion_name' => $campaign['Campaign']['promotion_name'],
'promotion_description' => $campaign['Campaign']['promotion_description'],
'barcode' => $campaign['Campaign']['barcode'],
'product_logo' => $campaign['Campaign']['product_logo'],
'product_picture' => $campaign['Campaign']['product_picture'],
'rating' => $campaign['Campaign']['rating'],
'category_id' => $campaign['Campaign']['category_id'],
'status' => $campaign['Campaign']['status'],
'discount' => $campaign['Campaign']['discount'],
'discount_percent' => Data::formatNumberOutputStrict($campaign['Campaign']['discount_percent']),
'standard_price' => Data::formatNumberOutputStrict($campaign['Campaign']['standard_price']),
'discount_nach_price' => Data::formatNumberOutputStrict($campaign['Campaign']['discount_nach_price']),
'discount_count' => $campaign['Campaign']['discount_count'],
'discount_reference' => $campaign['Campaign']['discount_reference'],
'Geocode' => $campaign['Geocode']
);
switch ($campaign['Campaign']['deal_type']) {
case 'lottery':
$enteredLotteryCount = $this->SpecialSaving->find('count', array(
'recursive' => -1,
'conditions' => array(
'private_token' => $private_token,
'campaign_id' => $campaign['Campaign']['id']
)
));
if ($enteredLotteryCount > 0) {
$result[$ckey]['entered_lottery'] = true;
}
$result[$ckey]['locked'] = true;
if (time() >= (strtotime($campaign['Campaign']['lottery_end_date']))) {
$winner = $this->Winner->find('count', array(
'conditions' => array(
'Winner.private_token' => $private_token,
'Winner.campaign_id' => $campaign['Campaign']['id']
)
));
if ($winner) {
$result[$ckey]['winner'] = true;
if (!empty($campaign['Campaign']['lottery_type']) AND $campaign['Campaign']['lottery_type'] == 'special') {
$result[$ckey]['lottery_contact'] = $campaign['Campaign']['lottery_contact'];
$result[$ckey]['lottery_contact_phone'] = $campaign['Campaign']['lottery_contact_phone'];
$result[$ckey]['lottery_code'] = $campaign['Campaign']['lottery_code'];
$result[$ckey]['discount'] = '';
$result[$ckey]['discount_percent'] = '';
} else {
$result[$ckey]['locked'] = false;
}
}
}
$result[$ckey]['lottery_end_date'] = strtotime($campaign['Campaign']['lottery_end_date']);
break;
case 'unlock':
$scanCount = count($campaign['Scan']);
$result[$ckey]['number_of_scan'] = $scanCount;
$result[$ckey]['scan_limit'] = (int) $campaign['Campaign']['scan_limit'];
if ($campaign['Campaign']['scan_limit'] < $scanCount) {
$result[$ckey]['locked'] = true;
}
break;
case 'social':
if (count($campaign['Social']) == 0) {
$result[$ckey]['locked'] = true;
}
break;
default:
break;
}
}
return $result;
}
/* public function setValidate(array $data = array()) {
$uploadError = Configure::read('Translations.Messages.noInputError');
$processUploadError = Configure::read('Translations.Messages.processUploadError');
$mimeTypeError = Configure::read('Translations.Messages.mimeTypeError');
$dateError = Configure::read('Translations.Messages.dateError');
$noInputError = Configure::read('Translations.Messages.noInputError');
$checkUploads = array('barcode', 'product_logo', 'product_picture');
$this->validate = array(
'company_name' => array(
'rule' => 'notEmpty',
'message' => $noInputError
),
'promotion_type' => array(
'rule' => 'notEmpty',
'message' => $noInputError
),
'name' => array(
'rule' => 'notEmpty',
'message' => $noInputError
),
'promotion_name' => array(
'rule' => 'notEmpty',
'message' => $noInputError
),
'promotion_description' => array(
'rule' => 'notEmpty',
'message' => $noInputError
),
'category_id' => array(
'rule' => 'notEmpty',
'message' => $noInputError
),
'start_date' => array(
'rule' => 'date',
'message' => $noInputError
),
'end_date' => array(
'rule' => 'date',
'message' => $noInputError
),
'redemption_frequency' => array(
'rule' => 'notEmpty',
'message' => $noInputError
),
'company_url' => array(
'rule' => 'url',
'message' => $urlError
)
);
if (empty($data)) {
return;
}
$this->validate['discount'] = array(
'rule' => 'notEmpty',
'message' => $noInputError
);
$this->validate['discount_percent'] = array(
'rule' => 'notEmpty',
'message' => $noInputError
);
foreach ($checkUploads as $checkUpload) {
if (!(!empty($data[$this->alias][$checkUpload]) && empty($data[$this->alias][$checkUpload . '_file']['tmp_name']))) {
$this->validate[$checkUpload . '_file'] = array(
'uploadError' => array(
'rule' => 'uploadError',
'message' => $uploadError,
'required' => FALSE,
'allowEmpty' => TRUE,
),
// custom callback to deal with the file upload
'processUpload' => array(
'rule' => 'processUpload',
'message' => $processUploadError,
'required' => FALSE,
'allowEmpty' => TRUE,
'last' => TRUE,
),
'mimeType' => array(
'rule' => array('isValidMimeType', array('image/gif', 'image/png', 'image/jpg', 'image/jpeg')),
'message' => $mimeTypeError,
)
);
}
}
if (!empty($data[$this->alias]['deal_type'])) {
if ($data[$this->alias]['deal_type'] == 'lottery') {
$this->validate['lottery_end_date'] = array(
'rule' => 'date',
'message' => $dateError
);
$this->validate['lottery_type'] = array(
'rule' => 'notEmpty',
'message' => $noInputError
);
if (!empty($data[$this->alias]['lottery_type']) && $data[$this->alias]['lottery_type'] == 'special') {
$this->validate['lottery_contact'] = array(
'rule' => 'notEmpty',
'message' => $noInputError
);
$this->validate['lottery_code'] = array(
'rule' => 'notEmpty',
'message' => $noInputError
);
$this->validate['lottery_contact_phone'] = array(
'rule' => 'notEmpty',
'message' => $noInputError
);
unset($this->validate['discount']);
unset($this->validate['discount_percent']);
}
} else if ($data[$this->alias]['deal_type'] == 'unlock') {
$this->validate['scan_limit'] = array(
'rule' => 'notEmpty',
'message' => $noInputError
);
}
}
} */
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment