PageRenderTime 44ms CodeModel.GetById 15ms RepoModel.GetById 1ms app.codeStats 0ms

/app/code/core/Mage/SalesRule/Model/Mysql4/Rule.php

https://github.com/joebushi/magento-mirror
PHP | 347 lines | 242 code | 54 blank | 51 comment | 27 complexity | 1d6c7b33300bd0ed113d31a9d0baba5f MD5 | raw file
  1. <?php
  2. /**
  3. * Magento
  4. *
  5. * NOTICE OF LICENSE
  6. *
  7. * This source file is subject to the Open Software License (OSL 3.0)
  8. * that is bundled with this package in the file LICENSE.txt.
  9. * It is also available through the world-wide-web at this URL:
  10. * http://opensource.org/licenses/osl-3.0.php
  11. * If you did not receive a copy of the license and are unable to
  12. * obtain it through the world-wide-web, please send an email
  13. * to license@magentocommerce.com so we can send you a copy immediately.
  14. *
  15. * DISCLAIMER
  16. *
  17. * Do not edit or add to this file if you wish to upgrade Magento to newer
  18. * versions in the future. If you wish to customize Magento for your
  19. * needs please refer to http://www.magentocommerce.com for more information.
  20. *
  21. * @category Mage
  22. * @package Mage_SalesRule
  23. * @copyright Copyright (c) 2009 Irubin Consulting Inc. DBA Varien (http://www.varien.com)
  24. * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
  25. */
  26. class Mage_SalesRule_Model_Mysql4_Rule extends Mage_Core_Model_Mysql4_Abstract
  27. {
  28. protected function _construct()
  29. {
  30. $this->_init('salesrule/rule', 'rule_id');
  31. }
  32. public function _beforeSave(Mage_Core_Model_Abstract $object)
  33. {
  34. if (!$object->getFromDate()) {
  35. $object->setFromDate(Mage::app()->getLocale()->date());
  36. }
  37. if ($object->getFromDate() instanceof Zend_Date) {
  38. $object->setFromDate($object->getFromDate()->toString(Varien_Date::DATETIME_INTERNAL_FORMAT));
  39. }
  40. if (!$object->getToDate()) {
  41. $object->setToDate(new Zend_Db_Expr('NULL'));
  42. }
  43. else {
  44. if ($object->getToDate() instanceof Zend_Date) {
  45. $object->setToDate($object->getToDate()->toString(Varien_Date::DATETIME_INTERNAL_FORMAT));
  46. }
  47. }
  48. if (!$object->getDiscountQty()) {
  49. $object->setDiscountQty(new Zend_Db_Expr('NULL'));
  50. }
  51. parent::_beforeSave($object);
  52. }
  53. public function getCustomerUses($rule, $customerId)
  54. {
  55. $read = $this->_getReadAdapter();
  56. $select = $read->select()->from($this->getTable('rule_customer'), array('cnt'=>'count(*)'))
  57. ->where('rule_id=?', $rule->getRuleId())
  58. ->where('customer_id=?', $customerId);
  59. return $read->fetchOne($select);
  60. }
  61. /**
  62. * Save rule labels for different store views
  63. *
  64. * @param int $ruleId
  65. * @param array $labels
  66. * @return Mage_SalesRule_Model_Mysql4_Rule
  67. */
  68. public function saveStoreLabels($ruleId, $labels)
  69. {
  70. $delete = array();
  71. $save = array();
  72. $table = $this->getTable('salesrule/label');
  73. $adapter = $this->_getWriteAdapter();
  74. foreach ($labels as $storeId => $label) {
  75. if (Mage::helper('core/string')->strlen($label)) {
  76. $data = array('rule_id' => $ruleId, 'store_id' => $storeId, 'label' => $label);
  77. $adapter->insertOnDuplicate($table, $data, array('label'));
  78. } else {
  79. $delete[] = $storeId;
  80. }
  81. }
  82. if (!empty($delete)) {
  83. $adapter->delete($table,
  84. $adapter->quoteInto('rule_id=? AND ', $ruleId) . $adapter->quoteInto('store_id IN (?)', $delete)
  85. );
  86. }
  87. return $this;
  88. }
  89. /**
  90. * Get all existing rule labels
  91. *
  92. * @param int $ruleId
  93. * @return array
  94. */
  95. public function getStoreLabels($ruleId)
  96. {
  97. $select = $this->_getReadAdapter()->select()
  98. ->from($this->getTable('salesrule/label'), array('store_id', 'label'))
  99. ->where('rule_id=?', $ruleId);
  100. return $this->_getReadAdapter()->fetchPairs($select);
  101. }
  102. /**
  103. * Get rule label by specific store id
  104. *
  105. * @param int $ruleId
  106. * @param int $storeId
  107. * @return string
  108. */
  109. public function getStoreLabel($ruleId, $storeId)
  110. {
  111. $select = $this->_getReadAdapter()->select()
  112. ->from($this->getTable('salesrule/label'), 'label')
  113. ->where('rule_id=?', $ruleId)
  114. ->where('store_id IN(?)', array($storeId, 0))
  115. ->order('store_id DESC');
  116. return $this->_getReadAdapter()->fetchOne($select);
  117. }
  118. /**
  119. * Aggregate Coupons data
  120. *
  121. * @param mixed $from
  122. * @param mixed $to
  123. * @return Mage_SalesRule_Model_Mysql4_Rule
  124. */
  125. public function aggregate($from = null, $to = null)
  126. {
  127. if (!is_null($from)) {
  128. $from = $this->formatDate($from);
  129. }
  130. if (!is_null($to)) {
  131. $from = $this->formatDate($to);
  132. }
  133. $this->_aggregateByOrderCreatedAt($from, $to);
  134. $this->_aggregateByOrderUpdatedAt($from, $to);
  135. $reportsFlagModel = Mage::getModel('reports/flag');
  136. $reportsFlagModel->setReportFlagCode(Mage_Reports_Model_Flag::REPORT_COUPNS_FLAG_CODE);
  137. $reportsFlagModel->loadSelf();
  138. $reportsFlagModel->save();
  139. return $this;
  140. }
  141. protected function _aggregateByOrderCreatedAt($from, $to)
  142. {
  143. try {
  144. $tableName = $this->getTable('salesrule/coupon_aggregated');
  145. $writeAdapter = $this->_getWriteAdapter();
  146. $writeAdapter->beginTransaction();
  147. if (is_null($from) && is_null($to)) {
  148. $writeAdapter->query("TRUNCATE TABLE {$tableName}");
  149. } else {
  150. $where = (!is_null($from)) ? "so.updated_at >= '{$from}'" : '';
  151. if (!is_null($to)) {
  152. $where .= (!empty($where)) ? " AND so.updated_at <= '{$to}'" : "so.updated_at <= '{$to}'";
  153. }
  154. $subQuery = $writeAdapter->select();
  155. $subQuery->from(array('so'=>'sales_order'), array('DISTINCT DATE(so.created_at)'))
  156. ->where($where);
  157. $deleteCondition = 'DATE(period) IN (' . new Zend_Db_Expr($subQuery) . ')';
  158. $writeAdapter->delete($tableName, $deleteCondition);
  159. }
  160. $columns = array(
  161. 'period' => "DATE(created_at)",
  162. 'store_id' => 'store_id',
  163. 'order_status' => 'status',
  164. 'coupon_code' => 'coupon_code',
  165. 'coupon_uses' => 'COUNT(`entity_id`)',
  166. 'subtotal_amount' => 'SUM(`base_subtotal` * `base_to_global_rate`)',
  167. 'discount_amount' => 'SUM(`base_discount_amount` * `base_to_global_rate`)',
  168. 'total_amount' => 'SUM((`base_subtotal` - `base_discount_amount`) * `base_to_global_rate`)'
  169. );
  170. $select = $writeAdapter->select()->from($this->getTable('sales/order'), $columns);
  171. if (!is_null($from) || !is_null($to)) {
  172. $select->where("DATE(created_at) IN(?)", new Zend_Db_Expr($subQuery));
  173. }
  174. $select->where("coupon_code <> ''");
  175. $select->group(array(
  176. "DATE(created_at)",
  177. 'store_id',
  178. 'status',
  179. 'coupon_code'
  180. ));
  181. $select->having('coupon_uses > 0');
  182. $writeAdapter->query("
  183. INSERT INTO `{$tableName}` (" . implode(',', array_keys($columns)) . ") {$select}
  184. ");
  185. $select = $writeAdapter->select();
  186. $columns = array(
  187. 'period' => 'period',
  188. 'store_id' => new Zend_Db_Expr('0'),
  189. 'order_status' => 'order_status',
  190. 'coupon_code' => 'coupon_code',
  191. 'coupon_uses' => 'SUM(`coupon_uses`)',
  192. 'subtotal_amount' => 'SUM(`subtotal_amount`)',
  193. 'discount_amount' => 'SUM(`discount_amount`)',
  194. 'total_amount' => 'SUM(`total_amount`)'
  195. );
  196. $select
  197. ->from($tableName, $columns)
  198. ->where("store_id <> 0");
  199. if (!is_null($from) || !is_null($to)) {
  200. $select->where("DATE(period) IN(?)", new Zend_Db_Expr($subQuery));
  201. }
  202. $select->group(array(
  203. 'period',
  204. 'order_status',
  205. 'coupon_code'
  206. ));
  207. $writeAdapter->query("
  208. INSERT INTO `{$tableName}` (" . implode(',', array_keys($columns)) . ") {$select}
  209. ");
  210. } catch (Exception $e) {
  211. $writeAdapter->rollBack();
  212. throw $e;
  213. }
  214. $writeAdapter->commit();
  215. return $this;
  216. }
  217. protected function _aggregateByOrderUpdatedAt($from, $to)
  218. {
  219. try {
  220. $tableName = $this->getTable('salesrule/coupon_aggregated_order');
  221. $writeAdapter = $this->_getWriteAdapter();
  222. $writeAdapter->beginTransaction();
  223. if (is_null($from) && is_null($to)) {
  224. $writeAdapter->query("TRUNCATE TABLE {$tableName}");
  225. } else {
  226. $where = (!is_null($from)) ? "so.updated_at >= '{$from}'" : '';
  227. if (!is_null($to)) {
  228. $where .= (!empty($where)) ? " AND so.updated_at <= '{$to}'" : "so.updated_at <= '{$to}'";
  229. }
  230. $subQuery = $writeAdapter->select();
  231. $subQuery->from(array('so'=>'sales_order'), array('DISTINCT DATE(so.created_at)'))
  232. ->where($where);
  233. $deleteCondition = 'DATE(period) IN (' . new Zend_Db_Expr($subQuery) . ')';
  234. $writeAdapter->delete($tableName, $deleteCondition);
  235. }
  236. $columns = array(
  237. 'period' => "DATE(updated_at)",
  238. 'store_id' => 'store_id',
  239. 'order_status' => 'status',
  240. 'coupon_code' => 'coupon_code',
  241. 'coupon_uses' => 'COUNT(`entity_id`)',
  242. 'subtotal_amount' => 'SUM(`base_subtotal` * `base_to_global_rate`)',
  243. 'discount_amount' => 'SUM(`base_discount_amount` * `base_to_global_rate`)',
  244. 'total_amount' => 'SUM((`base_subtotal` - `base_discount_amount`) * `base_to_global_rate`)'
  245. );
  246. $select = $writeAdapter->select()->from($this->getTable('sales/order'), $columns);
  247. if (!is_null($from) || !is_null($to)) {
  248. $select->where("DATE(updated_at) IN(?)", new Zend_Db_Expr($subQuery));
  249. }
  250. $select->where("coupon_code <> ''");
  251. $select->group(array(
  252. "DATE(updated_at)",
  253. 'store_id',
  254. 'status',
  255. 'coupon_code'
  256. ));
  257. $select->having('coupon_uses > 0');
  258. $writeAdapter->query("
  259. INSERT INTO `{$tableName}` (" . implode(',', array_keys($columns)) . ") {$select}
  260. ");
  261. $select = $writeAdapter->select();
  262. $columns = array(
  263. 'period' => 'period',
  264. 'store_id' => new Zend_Db_Expr('0'),
  265. 'order_status' => 'order_status',
  266. 'coupon_code' => 'coupon_code',
  267. 'coupon_uses' => 'SUM(`coupon_uses`)',
  268. 'subtotal_amount' => 'SUM(`subtotal_amount`)',
  269. 'discount_amount' => 'SUM(`discount_amount`)',
  270. 'total_amount' => 'SUM(`total_amount`)'
  271. );
  272. $select
  273. ->from($tableName, $columns)
  274. ->where("store_id <> 0");
  275. if (!is_null($from) || !is_null($to)) {
  276. $select->where("DATE(period) IN(?)", new Zend_Db_Expr($subQuery));
  277. }
  278. $select->group(array(
  279. 'period',
  280. 'order_status',
  281. 'coupon_code'
  282. ));
  283. $writeAdapter->query("
  284. INSERT INTO `{$tableName}` (" . implode(',', array_keys($columns)) . ") {$select}
  285. ");
  286. } catch (Exception $e) {
  287. $writeAdapter->rollBack();
  288. throw $e;
  289. }
  290. $writeAdapter->commit();
  291. return $this;
  292. }
  293. }